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
from concurrent.futures.thread import ThreadPoolExecutor import functools import os import sys import time import pytest import requests import ray from ray._private.test_utils import SignalActor, wait_for_condition from ray import serve from ray.serve.api import deploy_group class TestGetDeployment: def get_d...
python/ray/serve/tests/test_deploy_2.py
from concurrent.futures.thread import ThreadPoolExecutor import functools import os import sys import time import pytest import requests import ray from ray._private.test_utils import SignalActor, wait_for_condition from ray import serve from ray.serve.api import deploy_group class TestGetDeployment: def get_d...
0.514644
0.261461
import numpy as np from scipy.stats import chi2 from scipy.optimize import minimize from scipy.stats import beta def checkattr(classifier): try: assert(hasattr(classifier, "predict_proba")) assert(hasattr(classifier, "fit")) except: return -1 return 0 def DKL(hx0, hx1): epsilon...
BayesCCal.py
import numpy as np from scipy.stats import chi2 from scipy.optimize import minimize from scipy.stats import beta def checkattr(classifier): try: assert(hasattr(classifier, "predict_proba")) assert(hasattr(classifier, "fit")) except: return -1 return 0 def DKL(hx0, hx1): epsilon...
0.753285
0.673849
import os import time import unittest from mars.compat import reload_module class Test(unittest.TestCase): def testStats(self): from mars import resource resource = reload_module(resource) resource.cpu_percent() mem_stats = resource.virtual_memory() self.assertGreaterEqu...
mars/tests/test_resource.py
import os import time import unittest from mars.compat import reload_module class Test(unittest.TestCase): def testStats(self): from mars import resource resource = reload_module(resource) resource.cpu_percent() mem_stats = resource.virtual_memory() self.assertGreaterEqu...
0.392104
0.356363
import contextlib import copy import json import shlex from typing import Dict, List @contextlib.contextmanager def temp_defrost(cfg): is_frozen = cfg.is_frozen() if is_frozen: cfg.defrost() yield cfg if is_frozen: cfg.freeze() def str_wrap_fbnet_arch_def(d: Dict, inplace=False) ->...
d2go/config/utils.py
import contextlib import copy import json import shlex from typing import Dict, List @contextlib.contextmanager def temp_defrost(cfg): is_frozen = cfg.is_frozen() if is_frozen: cfg.defrost() yield cfg if is_frozen: cfg.freeze() def str_wrap_fbnet_arch_def(d: Dict, inplace=False) ->...
0.54359
0.227888
import logging import os import uuid from abc import abstractmethod from tempfile import TemporaryDirectory import cloudpickle from dq0.sdk.errors.errors import fatal_error from dq0.sdk.projects import Project logger = logging.getLogger(__name__) class Model(Project): """Abstract base class for all models avai...
dq0/sdk/models/model.py
import logging import os import uuid from abc import abstractmethod from tempfile import TemporaryDirectory import cloudpickle from dq0.sdk.errors.errors import fatal_error from dq0.sdk.projects import Project logger = logging.getLogger(__name__) class Model(Project): """Abstract base class for all models avai...
0.804406
0.277669
load("//node:internal/node_utils.bzl", "execute") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") NODE_TOOLCHAIN_BUILD_FILE = """ package(default_visibility = [ "//visibility:public" ]) exports_files(["bin/node", "bin/npm", "bin/tsc", "bin/yarn", "bin/bower"]) """ def _mirror_path(ctx, workspace_...
node/internal/repositories.bzl
load("//node:internal/node_utils.bzl", "execute") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") NODE_TOOLCHAIN_BUILD_FILE = """ package(default_visibility = [ "//visibility:public" ]) exports_files(["bin/node", "bin/npm", "bin/tsc", "bin/yarn", "bin/bower"]) """ def _mirror_path(ctx, workspace_...
0.229018
0.101233
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import authenticate, login, logout, get_user_model from chat.forms import LoginForm, RegisterForm, ComposeForm from django.contrib.auth.decorators import login_required from django.contrib import messages from django.db.models i...
src/chat/views.py
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import authenticate, login, logout, get_user_model from chat.forms import LoginForm, RegisterForm, ComposeForm from django.contrib.auth.decorators import login_required from django.contrib import messages from django.db.models i...
0.299208
0.075278
from selenium.webdriver.common.by import By from Browser import BrowserBot, url_changes, find_elements_in_sequence, element_is_clicked from loguru import logger import sys # DECORATORS def login_required(inner_func): def wrapper(self): if not self.logged_in: self.login() inner_func(sel...
Instagram.py
from selenium.webdriver.common.by import By from Browser import BrowserBot, url_changes, find_elements_in_sequence, element_is_clicked from loguru import logger import sys # DECORATORS def login_required(inner_func): def wrapper(self): if not self.logged_in: self.login() inner_func(sel...
0.286968
0.064095
from functools import wraps from ..explanation.explanation import ( _aggregate_global_from_local_explanation, _aggregate_streamed_local_explanations, _create_global_explanation) from .constants import Defaults, ExplainParams, ModelTask def init_aggregator_decorator(init_func): """Decorate a constructor t...
python/interpret_community/common/aggregate.py
from functools import wraps from ..explanation.explanation import ( _aggregate_global_from_local_explanation, _aggregate_streamed_local_explanations, _create_global_explanation) from .constants import Defaults, ExplainParams, ModelTask def init_aggregator_decorator(init_func): """Decorate a constructor t...
0.922312
0.482429
import sys import socket from datetime import datetime import nacl.secret import nacl.utils import base64 import psycopg2 from threading import Thread def postsqlg(): conn = None try: conn = psycopg2.connect(host="localhost",database="temp", user="postgres", password=str(sys.argv[1])) cur = conn.cursor() cur....
server.py
import sys import socket from datetime import datetime import nacl.secret import nacl.utils import base64 import psycopg2 from threading import Thread def postsqlg(): conn = None try: conn = psycopg2.connect(host="localhost",database="temp", user="postgres", password=str(sys.argv[1])) cur = conn.cursor() cur....
0.019842
0.096578
from smarts import db from flask import jsonify, request from smarts.models import Message, MessageSchema, message_schema from webargs.flaskparser import use_args from smarts.utils import validate_json_content_type, token_required from smarts.messages import messages_bp @messages_bp.route('/messages', methods=['GET']...
smarts/messages/messages.py
from smarts import db from flask import jsonify, request from smarts.models import Message, MessageSchema, message_schema from webargs.flaskparser import use_args from smarts.utils import validate_json_content_type, token_required from smarts.messages import messages_bp @messages_bp.route('/messages', methods=['GET']...
0.476092
0.049245
from django.contrib.messages import constants import os from decouple import config from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = config("SECRET_KEY") DEBUG = config("DEBUG", default=False, cast=bool) ALLOWED...
encurtador_de_link/settings.py
from django.contrib.messages import constants import os from decouple import config from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = config("SECRET_KEY") DEBUG = config("DEBUG", default=False, cast=bool) ALLOWED...
0.416678
0.069542
import whois from dns import query from urllib.parse import urlparse import whois import tldextract import pandas as pd import numpy as np pd.set_option('display.max_columns', 10000) pd.set_option('display.max_rows', 10000) pd.set_option('display.max_colwidth', 10000) pd.set_option('display.width',1000) np.set_printop...
Feature Comparison/Whois.py
import whois from dns import query from urllib.parse import urlparse import whois import tldextract import pandas as pd import numpy as np pd.set_option('display.max_columns', 10000) pd.set_option('display.max_rows', 10000) pd.set_option('display.max_colwidth', 10000) pd.set_option('display.width',1000) np.set_printop...
0.073422
0.230811
__author__ = "<NAME>" __copyright__ = "Copyright (c) 2020 <NAME>. All rights reserved." __license__ = "MIT" __version__ = "0.1" from enum import IntEnum, unique from typing import Any, Dict, List, Tuple from simple_i2c import read_bytes, write_bytes import struct, sys # Globals ADDR = 0x08 # bus address @unique c...
controller/i2c_comms.py
__author__ = "<NAME>" __copyright__ = "Copyright (c) 2020 <NAME>. All rights reserved." __license__ = "MIT" __version__ = "0.1" from enum import IntEnum, unique from typing import Any, Dict, List, Tuple from simple_i2c import read_bytes, write_bytes import struct, sys # Globals ADDR = 0x08 # bus address @unique c...
0.448909
0.267974
"""Generated protocol buffer code.""" # third party from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = ...
packages/syft/src/syft/proto/core/node/common/action/action_sequence_pb2.py
"""Generated protocol buffer code.""" # third party from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = ...
0.497803
0.103749
import logging from typing import Union import numpy as np import tensorflow as tf from .external import TFEstimatorGLM, InputDataGLM, Model from .external import closedform_beta_glm_logitmean, closedform_beta_glm_logsamplesize from .estimator_graph import EstimatorGraph from .model import ProcessModel from .training...
batchglm/train/tf1/glm_beta/estimator.py
import logging from typing import Union import numpy as np import tensorflow as tf from .external import TFEstimatorGLM, InputDataGLM, Model from .external import closedform_beta_glm_logitmean, closedform_beta_glm_logsamplesize from .estimator_graph import EstimatorGraph from .model import ProcessModel from .training...
0.936081
0.360883
import core.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migra...
core/migrations/0001_initial.py
import core.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migra...
0.489748
0.178418
from unittest import TestCase from auto_rl.learning.policy import MLPActorCritic import numpy as np import torch as th import gym class TestMLPActorCritic(TestCase): def __init__(self, *args, **kwargs): super(TestMLPActorCritic, self).__init__(*args, **kwargs) self.env = gym.make("Pendulum-v0") ...
algorithms/refactor/tests/learning/test_policy.py
from unittest import TestCase from auto_rl.learning.policy import MLPActorCritic import numpy as np import torch as th import gym class TestMLPActorCritic(TestCase): def __init__(self, *args, **kwargs): super(TestMLPActorCritic, self).__init__(*args, **kwargs) self.env = gym.make("Pendulum-v0") ...
0.90684
0.677127
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import absltest from validate import handler from os import path _TEST_DIR = path.dirname(path.realpath(__file__)) _TESTCASE_PATH = path.join(_TEST_DIR, 'fake_instances') class HandlerTest(a...
tools/validators/instance_validator/tests/handler_test.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import absltest from validate import handler from os import path _TEST_DIR = path.dirname(path.realpath(__file__)) _TESTCASE_PATH = path.join(_TEST_DIR, 'fake_instances') class HandlerTest(a...
0.466116
0.215371
from pathlib import Path from typing import Generator import pandas as pd import typer from cgr_gwas_qc.parsers import eigensoft, plink from cgr_gwas_qc.typing import PathLike app = typer.Typer(add_completion=False) DTYPES = { "population": "string", "Subject_ID": "string", "QC_Family_ID": "string", ...
src/cgr_gwas_qc/workflow/scripts/population_qc_table.py
from pathlib import Path from typing import Generator import pandas as pd import typer from cgr_gwas_qc.parsers import eigensoft, plink from cgr_gwas_qc.typing import PathLike app = typer.Typer(add_completion=False) DTYPES = { "population": "string", "Subject_ID": "string", "QC_Family_ID": "string", ...
0.759404
0.420778
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Position', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=...
lab1/autosaloon/saloon/migrations/0001_initial.py
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Position', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=...
0.665954
0.196363
import os from gym import error, spaces from gym.utils import seeding import numpy as np from os import path import gym import six import cythonized from .mujoco.generated import const class MujocoEnv(gym.Env): """ Superclass for all MuJoCo environments. """ def __init__(self, model_path, frame_ski...
gym2/mujoco_env.py
import os from gym import error, spaces from gym.utils import seeding import numpy as np from os import path import gym import six import cythonized from .mujoco.generated import const class MujocoEnv(gym.Env): """ Superclass for all MuJoCo environments. """ def __init__(self, model_path, frame_ski...
0.80837
0.362151
from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from accounts.forms import RegistrationForm, LoginForm, ProfileForm # Crea...
accounts/views.py
from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from accounts.forms import RegistrationForm, LoginForm, ProfileForm # Crea...
0.252016
0.063482
import torch from mmcls.models import ImageClassifier from mmcv.runner import auto_fp16 from ..builder import ALGORITHMS @ALGORITHMS.register_module() class MMClsImageClassifierWrapper(ImageClassifier): """Workaround to use models from mmclassificaiton. Since the output of classifier from mmclassification i...
mmselfsup/models/algorithms/mmcls_classifier_wrapper.py
import torch from mmcls.models import ImageClassifier from mmcv.runner import auto_fp16 from ..builder import ALGORITHMS @ALGORITHMS.register_module() class MMClsImageClassifierWrapper(ImageClassifier): """Workaround to use models from mmclassificaiton. Since the output of classifier from mmclassification i...
0.914178
0.359392
import unittest from programy.config.file.yaml_file import YamlConfigurationFile from programy.config.bot.sentiment import BotSentimentAnalyserConfiguration from programy.clients.events.console.config import ConsoleConfiguration class BotSentimentAnalyserConfigurationTests(unittest.TestCase): def test_with_data...
test/programytest/config/bot/test_sentiment.py
import unittest from programy.config.file.yaml_file import YamlConfigurationFile from programy.config.bot.sentiment import BotSentimentAnalyserConfiguration from programy.clients.events.console.config import ConsoleConfiguration class BotSentimentAnalyserConfigurationTests(unittest.TestCase): def test_with_data...
0.504394
0.292317
from __future__ import annotations import json from time import sleep import click from pioreactor.background_jobs import stirring from pioreactor.config import config from pioreactor.logging import create_logger from pioreactor.pubsub import publish from pioreactor.pubsub import publish_to_pioreactor_cloud from pio...
pioreactor/actions/stirring_calibration.py
from __future__ import annotations import json from time import sleep import click from pioreactor.background_jobs import stirring from pioreactor.config import config from pioreactor.logging import create_logger from pioreactor.pubsub import publish from pioreactor.pubsub import publish_to_pioreactor_cloud from pio...
0.695958
0.214671
import pygame import time import scripts.helpers as helpers class Button(object): def __init__(self, display, text, pos, size, inactive_col, active_col, font, reset_time=0.2): self.last_pressed = time.time() self.reset_time = reset_time self.display = display self.text = text ...
catkin/src/distributed_robot_system/src/nodes/scripts/widgets.py
import pygame import time import scripts.helpers as helpers class Button(object): def __init__(self, display, text, pos, size, inactive_col, active_col, font, reset_time=0.2): self.last_pressed = time.time() self.reset_time = reset_time self.display = display self.text = text ...
0.309545
0.344195
__all__ = ["EntityWithNationality"] import os import six import logging import json import tensorflow as tf import tensorflow_datasets as tfds from aispace.datasets import BaseDataset from aispace.datasets import data_transformers as Transformer _GLUE_CITATION = "TODO" logger = logging.getLogger(__name__) class...
aispace/datasets/entity_with_nationality.py
__all__ = ["EntityWithNationality"] import os import six import logging import json import tensorflow as tf import tensorflow_datasets as tfds from aispace.datasets import BaseDataset from aispace.datasets import data_transformers as Transformer _GLUE_CITATION = "TODO" logger = logging.getLogger(__name__) class...
0.660829
0.29931
import shelve import time import sys, os from operator import itemgetter class EmailLogger: def __init__(self, path=""): self.path = os.path.normpath(path) self.blockPath = os.path.normpath(os.path.dirname(path) + "/blocked_IPs.db") def getNumberOfPosts(self, ipNr, secondsBack=None): ...
WS/email/logEmail.py
import shelve import time import sys, os from operator import itemgetter class EmailLogger: def __init__(self, path=""): self.path = os.path.normpath(path) self.blockPath = os.path.normpath(os.path.dirname(path) + "/blocked_IPs.db") def getNumberOfPosts(self, ipNr, secondsBack=None): ...
0.421909
0.161783
import numpy as np import matplotlib.pyplot as plt from mm2d.util import rotation_matrix from matplotlib.animation import FFMpegWriter class PointRenderer: def __init__(self, p, color='k'): self.p = p self.color = color def render(self, ax): self.plot, = ax.plot(self.p[0], self.p[1], ...
mm2d/plotter.py
import numpy as np import matplotlib.pyplot as plt from mm2d.util import rotation_matrix from matplotlib.animation import FFMpegWriter class PointRenderer: def __init__(self, p, color='k'): self.p = p self.color = color def render(self, ax): self.plot, = ax.plot(self.p[0], self.p[1], ...
0.628293
0.579936
import random import string import pyperclip class User: ''' class that generate user objects ''' user_list = [] def __init__(self, username, password): ''' method that helps us define properties for our objects ''' self.username = username self.password = password def save_user(s...
password.py
import random import string import pyperclip class User: ''' class that generate user objects ''' user_list = [] def __init__(self, username, password): ''' method that helps us define properties for our objects ''' self.username = username self.password = password def save_user(s...
0.332744
0.135318
class DavidStrategyLevel2: def __init__(self, player_index): self.player_index = player_index self.name = 'berserk' self.first_location=False def decide_ship_movement(self, ship_index, game_state): ship_coords = game_state['players'][self.player_index]['units'][ship_index]['coo...
files/strategies/cohort-1/level-2/david_strategy_level_2.py
class DavidStrategyLevel2: def __init__(self, player_index): self.player_index = player_index self.name = 'berserk' self.first_location=False def decide_ship_movement(self, ship_index, game_state): ship_coords = game_state['players'][self.player_index]['units'][ship_index]['coo...
0.252937
0.381076
import numpy as np import networkx as nx from scipy.spatial.distance import cdist from networkx.algorithms.dag import dag_longest_path def compute_similarities(query_features, refer_features): """ 用于计算两组特征(已经做过l2-norm)之间的相似度 Args: query_features: shape: [N, D] refer_features: shape: [M,...
app/controller/algorithms/retrieval_util.py
import numpy as np import networkx as nx from scipy.spatial.distance import cdist from networkx.algorithms.dag import dag_longest_path def compute_similarities(query_features, refer_features): """ 用于计算两组特征(已经做过l2-norm)之间的相似度 Args: query_features: shape: [N, D] refer_features: shape: [M,...
0.599368
0.584419
import json import requests import sys from pyspark import SparkContext, SparkConf from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils from pyspark.sql.functions import window import numpy as np from kafka import KafkaProducer PHASENET_API_URL = "http://localhost:8000" if __...
kafka-spark/spark.py
import json import requests import sys from pyspark import SparkContext, SparkConf from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils from pyspark.sql.functions import window import numpy as np from kafka import KafkaProducer PHASENET_API_URL = "http://localhost:8000" if __...
0.320715
0.288506
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * import requests import traceback from typing import Dict, Any, Tuple import base64 import json from dateparser import parse from pytz import utc # Disable insecure warnings requests.packages.urllib3.disable_warnings() ...
Packs/GuardiCore/Integrations/GuardiCoreV2/GuardiCoreV2.py
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * import requests import traceback from typing import Dict, Any, Tuple import base64 import json from dateparser import parse from pytz import utc # Disable insecure warnings requests.packages.urllib3.disable_warnings() ...
0.658308
0.109515
import os import cv2 import json labels = { '102': 0, '103': 1, '104': 2, '105': 3, '106': 4, '107': 5, '108': 6, '109': 7, '110': 8, '111': 9, '112': 10, '201': 11, '202': 12, '203': 13, '204': 14, '205': 15, '206': 16, '207': 17, '301': 18...
star2020/process_classification/genTrueDetectImage.py
import os import cv2 import json labels = { '102': 0, '103': 1, '104': 2, '105': 3, '106': 4, '107': 5, '108': 6, '109': 7, '110': 8, '111': 9, '112': 10, '201': 11, '202': 12, '203': 13, '204': 14, '205': 15, '206': 16, '207': 17, '301': 18...
0.097482
0.240117
import cv2 from basecam import BaseCam from util import apply_doc, get_cascade_file_path, is_escape, wait_frames class HaarCam(BaseCam): """ Webcam that performs Haar Cascade object detection on the video stream. """ @apply_doc(BaseCam.__init__) def __init__(self, window): super(HaarCam,...
cannycam/haarcam.py
import cv2 from basecam import BaseCam from util import apply_doc, get_cascade_file_path, is_escape, wait_frames class HaarCam(BaseCam): """ Webcam that performs Haar Cascade object detection on the video stream. """ @apply_doc(BaseCam.__init__) def __init__(self, window): super(HaarCam,...
0.753376
0.14439
# Import an interfile volume as an Image3D and export. from ...Transformation.Transformations import Transform_Scale from ...DataSources.FileSources.interfile import load_interfile import os import numpy as np __all__ = ["import_interfile_volume", "export_interfile_volume"] def import_interfile_volume_data( ...
tomolab/DataSources/PET/PET_volume.py
# Import an interfile volume as an Image3D and export. from ...Transformation.Transformations import Transform_Scale from ...DataSources.FileSources.interfile import load_interfile import os import numpy as np __all__ = ["import_interfile_volume", "export_interfile_volume"] def import_interfile_volume_data( ...
0.415966
0.49762
from __future__ import absolute_import from builtins import object from flask.json import JSONEncoder class DynamicJSONEncoder(JSONEncoder): """ JSON encoder for custom classes: Uses __json__() method if available to prepare the object. Especially useful for SQLAlchemy models """ def de...
flask_jsontools/formatting.py
from __future__ import absolute_import from builtins import object from flask.json import JSONEncoder class DynamicJSONEncoder(JSONEncoder): """ JSON encoder for custom classes: Uses __json__() method if available to prepare the object. Especially useful for SQLAlchemy models """ def de...
0.734596
0.316224
from django.db import models from django.db.models import Q import random, os from django.db.models.signals import pre_save from django.urls import reverse from .utils import unique_slug_generator # Create your models here. def get_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.spl...
src/products/models.py
from django.db import models from django.db.models import Q import random, os from django.db.models.signals import pre_save from django.urls import reverse from .utils import unique_slug_generator # Create your models here. def get_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.spl...
0.476336
0.107204
import configparser import datetime import json import logging import multiprocessing import os import random import socket import sys import time from datetime import date from queue import Full import requests from dotenv import load_dotenv from europarl import configuration from europarl.db import ( DBInterfac...
europarl/jobs/crawler.py
import configparser import datetime import json import logging import multiprocessing import os import random import socket import sys import time from datetime import date from queue import Full import requests from dotenv import load_dotenv from europarl import configuration from europarl.db import ( DBInterfac...
0.211417
0.043305
from __future__ import absolute_import import argparse import os import subprocess VERSION = '1.13.1' REPO = 'sagemaker-tensorflow-scriptmode' PY2_CPU_BINARY = 'https://s3-us-west-2.amazonaws.com/tensorflow-aws/1.13/AmazonLinux/cpu/latest-patch-latest-patch/tensorflow-1.13.1-cp27-cp27mu-linux_x86_64.whl' # noqa PY3_C...
scripts/build_all.py
from __future__ import absolute_import import argparse import os import subprocess VERSION = '1.13.1' REPO = 'sagemaker-tensorflow-scriptmode' PY2_CPU_BINARY = 'https://s3-us-west-2.amazonaws.com/tensorflow-aws/1.13/AmazonLinux/cpu/latest-patch-latest-patch/tensorflow-1.13.1-cp27-cp27mu-linux_x86_64.whl' # noqa PY3_C...
0.506836
0.066995
from unittest import TestCase import odmlib.odm_1_3_2.model as ODM import odmlib.odm_parser as ODM_PARSER import os import datetime class TestClinicalData(TestCase): def setUp(self) -> None: self.odm_test_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data','test_clinical_data_01.xml') ...
tests/test_clinicalData.py
from unittest import TestCase import odmlib.odm_1_3_2.model as ODM import odmlib.odm_parser as ODM_PARSER import os import datetime class TestClinicalData(TestCase): def setUp(self) -> None: self.odm_test_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data','test_clinical_data_01.xml') ...
0.25992
0.285066
import numpy as np from QuantOPT.models import BaseModels class MaxRiskAdjReturn(BaseModels): """ the class for Maximum Risk Adjust Return Optimization(MRAO) requires: sigma2: the sigma2 function 协方差矩阵 lambda_r: 风险厌恶系数 portfolio_return: 组合收益率 TC function: the TC function ...
QuantOPT/models/model_MaxRiskAdjReturn.py
import numpy as np from QuantOPT.models import BaseModels class MaxRiskAdjReturn(BaseModels): """ the class for Maximum Risk Adjust Return Optimization(MRAO) requires: sigma2: the sigma2 function 协方差矩阵 lambda_r: 风险厌恶系数 portfolio_return: 组合收益率 TC function: the TC function ...
0.763484
0.487368
import unittest from unittest.mock import patch from unittest.mock import Mock import os from programy.services.rest.google.distance.service import GoogleDistanceService from programy.services.config import ServiceConfiguration from programy.services.config import ServiceRESTConfiguration from programytest.services.tes...
test/programytest/services/rest/google/distance/test_service.py
import unittest from unittest.mock import patch from unittest.mock import Mock import os from programy.services.rest.google.distance.service import GoogleDistanceService from programy.services.config import ServiceConfiguration from programy.services.config import ServiceRESTConfiguration from programytest.services.tes...
0.718693
0.344885
from django import forms class ProfileForm(forms.Form): first_name = forms.CharField( required=True, label='First Name:', max_length=32, widget=forms.TextInput( attrs={'class': 'form-control'})) last_name = forms.CharField( required=True, label='Last...
ad2dispatch/userprofiles/forms.py
from django import forms class ProfileForm(forms.Form): first_name = forms.CharField( required=True, label='First Name:', max_length=32, widget=forms.TextInput( attrs={'class': 'form-control'})) last_name = forms.CharField( required=True, label='Last...
0.422624
0.103749
from __future__ import absolute_import from flask import current_app, g from utils.response import output_json from utils.request import get_args, get_param from utils.misc import parse_int, now from utils.model import make_offset_paginator, attach_extend from helpers.record import recording from apiresps.validation...
server/blueprints/store/controllers/book.py
from __future__ import absolute_import from flask import current_app, g from utils.response import output_json from utils.request import get_args, get_param from utils.misc import parse_int, now from utils.model import make_offset_paginator, attach_extend from helpers.record import recording from apiresps.validation...
0.508544
0.168515
import asyncio import json from unittest import TestCase from unittest.mock import AsyncMock, patch from typing import Any, Dict from hummingbot.connector.exchange.bitmart.bitmart_auth import BitmartAuth import hummingbot.connector.exchange.bitmart.bitmart_constants as CONSTANTS from hummingbot.connector.exchange.bitm...
test/hummingbot/connector/exchange/bitmart/test_bitmart_user_stream_tracker.py
import asyncio import json from unittest import TestCase from unittest.mock import AsyncMock, patch from typing import Any, Dict from hummingbot.connector.exchange.bitmart.bitmart_auth import BitmartAuth import hummingbot.connector.exchange.bitmart.bitmart_constants as CONSTANTS from hummingbot.connector.exchange.bitm...
0.764804
0.233969
import cPickle as pickle import functools import logging import os import re import cloudstorage as gcs import jinja2 import webapp2 from google.appengine.api import urlfetch from google.appengine.api import memcache from webapp2_extras import sessions from webapp2_extras import security import secrets import filte...
gubernator/view_base.py
import cPickle as pickle import functools import logging import os import re import cloudstorage as gcs import jinja2 import webapp2 from google.appengine.api import urlfetch from google.appengine.api import memcache from webapp2_extras import sessions from webapp2_extras import security import secrets import filte...
0.627609
0.085595
# Imports import argparse import logging from json import dumps, loads from random import choice from wget import download from pathlib import Path from datetime import date, timedelta, datetime # Calendar integration from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials...
mealplanner.py
# Imports import argparse import logging from json import dumps, loads from random import choice from wget import download from pathlib import Path from datetime import date, timedelta, datetime # Calendar integration from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials...
0.358465
0.105027
from __future__ import division from __future__ import print_function import sys from six.moves import xrange import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.feature_selection import VarianceThreshold from sklearn.feature_selection import SelectKBest, RFE, f_classif from sklearn.svm i...
lib/segmentation/form_feature_selection.py
from __future__ import division from __future__ import print_function import sys from six.moves import xrange import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.feature_selection import VarianceThreshold from sklearn.feature_selection import SelectKBest, RFE, f_classif from sklearn.svm i...
0.572006
0.325145
import pandas as pd from gplearn.genetic import SymbolicTransformer from sklearn.model_selection import train_test_split class GPConfig: def __init__(self, feature_cols, target_col, generation=1000, population_size=5000, hall_of_fame=100, n_components=10, parsimony_coefficient=0....
src/tabular/feature_engineering/feature_generator/symbolic_learning.py
import pandas as pd from gplearn.genetic import SymbolicTransformer from sklearn.model_selection import train_test_split class GPConfig: def __init__(self, feature_cols, target_col, generation=1000, population_size=5000, hall_of_fame=100, n_components=10, parsimony_coefficient=0....
0.840946
0.315413
from typing import Optional from fastapi import ( APIRouter, Depends, HTTPException, Response, status, ) from sqlalchemy.orm import Session from . import crud from .deps import get_db from .schemas import Ticket, Train, TrainCreate router = APIRouter(prefix="/trains") @router.get("", response_m...
ch14/api_code/api/trains.py
from typing import Optional from fastapi import ( APIRouter, Depends, HTTPException, Response, status, ) from sqlalchemy.orm import Session from . import crud from .deps import get_db from .schemas import Ticket, Train, TrainCreate router = APIRouter(prefix="/trains") @router.get("", response_m...
0.71423
0.071364
import argparse class TrainOptions(): def __init__(self): self.parser = argparse.ArgumentParser() # data loader related self.parser.add_argument('--dataroot', type=str, required=True, help='path of data') self.parser.add_argument('--phase', type=str, default='train', help='phase for dataloading') ...
options.py
import argparse class TrainOptions(): def __init__(self): self.parser = argparse.ArgumentParser() # data loader related self.parser.add_argument('--dataroot', type=str, required=True, help='path of data') self.parser.add_argument('--phase', type=str, default='train', help='phase for dataloading') ...
0.625209
0.094761
"""Evaluation configurations.""" import itertools import math import numpy as np from wfa_cardinality_estimation_evaluation_framework.estimators import bloom_filter_sketch_operators from wfa_cardinality_estimation_evaluation_framework.estimators import bloom_filters from wfa_cardinality_estimation_evaluation_framework...
src/evaluations/data/evaluation_configs.py
"""Evaluation configurations.""" import itertools import math import numpy as np from wfa_cardinality_estimation_evaluation_framework.estimators import bloom_filter_sketch_operators from wfa_cardinality_estimation_evaluation_framework.estimators import bloom_filters from wfa_cardinality_estimation_evaluation_framework...
0.808105
0.313683
from enum import Enum import os import time import tkinter as tk from tkinter import ttk from typing import Iterable # Local library from .tree_evts import TreeEvt, TreeEvts from .utils import ascii_bell # === Enumerations ================================================================================= class Event(T...
MA/gui/dirview.py
from enum import Enum import os import time import tkinter as tk from tkinter import ttk from typing import Iterable # Local library from .tree_evts import TreeEvt, TreeEvts from .utils import ascii_bell # === Enumerations ================================================================================= class Event(T...
0.693473
0.095645
from odoo.addons.hr_expense.tests.common import TestExpenseCommon from odoo.tests import tagged @tagged('-at_install', 'post_install') class TestExpensesMailImport(TestExpenseCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) ...
addons/hr_expense/tests/test_expenses_mail_import.py
from odoo.addons.hr_expense.tests.common import TestExpenseCommon from odoo.tests import tagged @tagged('-at_install', 'post_install') class TestExpensesMailImport(TestExpenseCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) ...
0.651466
0.268171
__all__ = ["call_wa", "call_wm", "subsubm", "subm", "mainmacro", "runsubs"] __docformat__ = 'restructuredtext' from sardana.macroserver.macro import Macro, Type, ParamRepeat #-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- # First example: # A 'mainmacro' that executes a 'subm' that i...
src/sardana/macroserver/macros/examples/submacros.py
__all__ = ["call_wa", "call_wm", "subsubm", "subm", "mainmacro", "runsubs"] __docformat__ = 'restructuredtext' from sardana.macroserver.macro import Macro, Type, ParamRepeat #-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- # First example: # A 'mainmacro' that executes a 'subm' that i...
0.709724
0.177561
from dataclasses import dataclass import datetime import uuid from dcbench.common.table import RowMixin from typing import List import os import yaml from .solution import Solution from dcbench.config import config @dataclass class SolutionSet(RowMixin): set_id: str name: str summary: str task_id...
dcbench/common/solution_set.py
from dataclasses import dataclass import datetime import uuid from dcbench.common.table import RowMixin from typing import List import os import yaml from .solution import Solution from dcbench.config import config @dataclass class SolutionSet(RowMixin): set_id: str name: str summary: str task_id...
0.751283
0.203332
from ipaddress import IPv4Address from CybORG.Shared.Enums import SessionType, OperatingSystemType from CybORG.Simulator.Entity import Entity class Session(Entity): def __init__(self, ident: int, host: str, username: str, agent: str, pid: int, timeout: int = 0, session_type: str = 'shell', acti...
CybORG/CybORG/Simulator/Session.py
from ipaddress import IPv4Address from CybORG.Shared.Enums import SessionType, OperatingSystemType from CybORG.Simulator.Entity import Entity class Session(Entity): def __init__(self, ident: int, host: str, username: str, agent: str, pid: int, timeout: int = 0, session_type: str = 'shell', acti...
0.621196
0.207616
import re import sys import random from typing import List, Tuple import requests from requests.models import Response def find_links_in_text(text: str) -> List[str]: """Find links in a text and return a list of URLs.""" link_pattern = re.compile(r'((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:...
scripts/validate/links.py
import re import sys import random from typing import List, Tuple import requests from requests.models import Response def find_links_in_text(text: str) -> List[str]: """Find links in a text and return a list of URLs.""" link_pattern = re.compile(r'((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:...
0.610453
0.239249
import redis from openpyxl import Workbook import sys import os import time import datetime import platform import rank_user class Logger: def info(self, *args): print('[{}][info] {}'.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),*args)) def error(self, *args): print('[{}][error] {}'....
python/export_data_1.py
import redis from openpyxl import Workbook import sys import os import time import datetime import platform import rank_user class Logger: def info(self, *args): print('[{}][info] {}'.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),*args)) def error(self, *args): print('[{}][error] {}'....
0.052741
0.061059
import copy from django import forms from django.db import connection class AddInstituteForm(forms.Form): name = forms.CharField( label='Institute Name', help_text='Enter the name of the institute here.', min_length=1 ) city = forms.CharField( label='City', help_te...
creator/forms.py
import copy from django import forms from django.db import connection class AddInstituteForm(forms.Form): name = forms.CharField( label='Institute Name', help_text='Enter the name of the institute here.', min_length=1 ) city = forms.CharField( label='City', help_te...
0.479504
0.153105
import time import os from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_condi...
pila.py
import time import os from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_condi...
0.255344
0.123551
from SocketServer import UDPServer import socket, struct from py2030.utils.color_terminal import ColorTerminal try: import OSC except ImportError: ColorTerminal().warn("importing embedded version of pyOSC library for py2030.utils.osc_broadcast_server") import py2030.dependencies.OSC as OSC class OscBroad...
py2030/utils/osc_broadcast_server.py
from SocketServer import UDPServer import socket, struct from py2030.utils.color_terminal import ColorTerminal try: import OSC except ImportError: ColorTerminal().warn("importing embedded version of pyOSC library for py2030.utils.osc_broadcast_server") import py2030.dependencies.OSC as OSC class OscBroad...
0.420243
0.135375
import tempfile import numpy as np import pytest from ravenpy.utilities.testdata import get_local_testdata pytestmark = pytest.mark.online # FIXME: Remove XFAIL marks once OWSLib > 0.24.1 is released. class TestHydroBASINS: geoserver = pytest.importorskip("ravenpy.utilities.geoserver") fiona = pytest.imp...
tests/test_geoserver.py
import tempfile import numpy as np import pytest from ravenpy.utilities.testdata import get_local_testdata pytestmark = pytest.mark.online # FIXME: Remove XFAIL marks once OWSLib > 0.24.1 is released. class TestHydroBASINS: geoserver = pytest.importorskip("ravenpy.utilities.geoserver") fiona = pytest.imp...
0.319121
0.576631
from nvflare.apis.dxo import DXO, DataKind, from_shareable from nvflare.apis.fl_constant import ReturnCode from nvflare.apis.fl_context import FLContext from nvflare.apis.shareable import Shareable, make_reply from nvflare.apis.signal import Signal from nvflare.app_common.app_constant import AppConstants from nvflare....
tests/integration_test/data/apps/np_sag_weights_diff/custom/np_trainer.py
from nvflare.apis.dxo import DXO, DataKind, from_shareable from nvflare.apis.fl_constant import ReturnCode from nvflare.apis.fl_context import FLContext from nvflare.apis.shareable import Shareable, make_reply from nvflare.apis.signal import Signal from nvflare.app_common.app_constant import AppConstants from nvflare....
0.72594
0.161949
__author__ = '<NAME> <<EMAIL>>' __copyright__ = 'Copyright (c) 2013-2015, django ERP Team' __version__ = '0.0.5' from django.test import TestCase from django.contrib.auth import get_user_model from . import * from ..models import * from ..backends import * class ObjectPermissionBackendTestCase(TestCase): def t...
djangoerp/core/tests/test_backends.py
__author__ = '<NAME> <<EMAIL>>' __copyright__ = 'Copyright (c) 2013-2015, django ERP Team' __version__ = '0.0.5' from django.test import TestCase from django.contrib.auth import get_user_model from . import * from ..models import * from ..backends import * class ObjectPermissionBackendTestCase(TestCase): def t...
0.582966
0.262221
import time import tkinter as tk from tkinter import filedialog import os import base64 import hashlib class Storage(): def __init__(self): path = os.getcwd() try: os.mkdir(path + "/Storage") except: pass def digest(self, string): if not isinstance(str...
kademlia/storage.py
import time import tkinter as tk from tkinter import filedialog import os import base64 import hashlib class Storage(): def __init__(self): path = os.getcwd() try: os.mkdir(path + "/Storage") except: pass def digest(self, string): if not isinstance(str...
0.174833
0.078113
from conans import ConanFile, CMake, tools class GoogleBenchmarkConan(ConanFile): name = "google-benchmark" version = "1.4.1" description = "A microbenchmark support library" homepage = "https://github.com/google/benchmark" license = "https://github.com/google/benchmark/blob/master/LICENSE" ur...
conanfile.py
from conans import ConanFile, CMake, tools class GoogleBenchmarkConan(ConanFile): name = "google-benchmark" version = "1.4.1" description = "A microbenchmark support library" homepage = "https://github.com/google/benchmark" license = "https://github.com/google/benchmark/blob/master/LICENSE" ur...
0.538498
0.216622
from tkinter import * import tkinter as tk from tkinter import ttk, messagebox import pymysql # ---------------------------------------------------------------Login Function -------------------------------------- def clear(): userentry.delete(0, END) passentry.delete(0, END) def close(): win.destroy() ...
Demo/Code/app.py
from tkinter import * import tkinter as tk from tkinter import ttk, messagebox import pymysql # ---------------------------------------------------------------Login Function -------------------------------------- def clear(): userentry.delete(0, END) passentry.delete(0, END) def close(): win.destroy() ...
0.212395
0.251073
import time import uuid import random import Adafruit_BluefruitLE DEVICE_NAME = "m5-stack" # Define service and characteristic UUIDs used by the peripheral. SERVICE_UUID = uuid.UUID('00001111-0000-1000-8000-00805F9B34FB') TX_CHAR_UUID = uuid.UUID('00002222-0000-1000-8000-00805F9B34FB') RX_CHAR_UUID = uuid.UUID('00002...
code/Raspberry Pi/OLD/ble_m5.py
import time import uuid import random import Adafruit_BluefruitLE DEVICE_NAME = "m5-stack" # Define service and characteristic UUIDs used by the peripheral. SERVICE_UUID = uuid.UUID('00001111-0000-1000-8000-00805F9B34FB') TX_CHAR_UUID = uuid.UUID('00002222-0000-1000-8000-00805F9B34FB') RX_CHAR_UUID = uuid.UUID('00002...
0.410166
0.178204
from os import environ import LibServer from LibServer import app import random import string from LibServer.admin import admin from LibServer.browser import browser from pidfile import PIDFile from argparse import ArgumentParser if __name__ == '__main__': parser = ArgumentParser("libserv", ...
bin/runserver.py
from os import environ import LibServer from LibServer import app import random import string from LibServer.admin import admin from LibServer.browser import browser from pidfile import PIDFile from argparse import ArgumentParser if __name__ == '__main__': parser = ArgumentParser("libserv", ...
0.272315
0.04888
import json from functools import wraps import collections from django.http import JsonResponse, HttpResponse from django.utils.translation import ugettext_lazy as _ from django.views.decorators.csrf import csrf_exempt from djrad import types from djrad.json_schema import validate_schema, validate_params, validate_pa...
djrad/decorators.py
import json from functools import wraps import collections from django.http import JsonResponse, HttpResponse from django.utils.translation import ugettext_lazy as _ from django.views.decorators.csrf import csrf_exempt from djrad import types from djrad.json_schema import validate_schema, validate_params, validate_pa...
0.369998
0.164651
import pandas as pd with open("prob10_input.txt", 'r') as f: rawdata = f.readlines() nums = [int(i) for i in rawdata] nums_sorted = [0] + sorted(nums) + [max(nums) + 3] df = pd.DataFrame({'n':nums_sorted}) df['differ'] = df.n.diff() count1 = len(df[df.differ == 1]) count3 = len(df[df.differ == 3]) print(f"Prob 10 P...
2020/prob10.py
import pandas as pd with open("prob10_input.txt", 'r') as f: rawdata = f.readlines() nums = [int(i) for i in rawdata] nums_sorted = [0] + sorted(nums) + [max(nums) + 3] df = pd.DataFrame({'n':nums_sorted}) df['differ'] = df.n.diff() count1 = len(df[df.differ == 1]) count3 = len(df[df.differ == 3]) print(f"Prob 10 P...
0.208743
0.221414
from sys import stdout import click from auth0_login import fatal, setting from auth0_login.aws.console import open_aws_console from auth0_login.aws.credentials import write_aws_credentials from auth0_login.aws.account import aws_accounts from auth0_login.aws.saml_assertion import AWSSAMLAssertion from auth0_login.sa...
auth0_login/aws/sts_command.py
from sys import stdout import click from auth0_login import fatal, setting from auth0_login.aws.console import open_aws_console from auth0_login.aws.credentials import write_aws_credentials from auth0_login.aws.account import aws_accounts from auth0_login.aws.saml_assertion import AWSSAMLAssertion from auth0_login.sa...
0.567577
0.105303
from torch.utils.data import Dataset, DataLoader import torch from PIL import Image import glob import os.path as osp import os import random """ Posibles mejoras: - Comprobar image format es válido --> buscar en internet - Comprobar parámetros de entrada - get_image_name_wo_ext podría convertirse en una lambda - Comp...
tools/dataset_jld.py
from torch.utils.data import Dataset, DataLoader import torch from PIL import Image import glob import os.path as osp import os import random """ Posibles mejoras: - Comprobar image format es válido --> buscar en internet - Comprobar parámetros de entrada - get_image_name_wo_ext podría convertirse en una lambda - Comp...
0.596433
0.217712
import time, sys, math, random, csv import pygame from variables import * from simplePredator import SimplePredator from probPredator import ProbPredator from smartPredator import SmartPredator from coordPredator import CoordPredator from simpleFish import SimpleFish from advancedFish import AdvancedFish from circFish ...
simulator.py
import time, sys, math, random, csv import pygame from variables import * from simplePredator import SimplePredator from probPredator import ProbPredator from smartPredator import SmartPredator from coordPredator import CoordPredator from simpleFish import SimpleFish from advancedFish import AdvancedFish from circFish ...
0.26693
0.193757
# In[2]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import pathlib import os # In[50]: import tensorflow_datasets as tfds from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D, SeparableConv2D from tensorflow.keras import models from te...
CNN_with_brigs.py
# In[2]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import pathlib import os # In[50]: import tensorflow_datasets as tfds from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D, SeparableConv2D from tensorflow.keras import models from te...
0.688678
0.5919
from azureml.core import Workspace, Environment from azureml.core.conda_dependencies import CondaDependencies from azureml.core.runconfig import RunConfiguration from azureml.pipeline.core import Pipeline, PipelineEndpoint from azureml.pipeline.core._restclients.aeva.models.error_response import ErrorResponseException ...
samples/kaldi-asr-yesno/ml_service/pipelines/build_pipeline.py
from azureml.core import Workspace, Environment from azureml.core.conda_dependencies import CondaDependencies from azureml.core.runconfig import RunConfiguration from azureml.pipeline.core import Pipeline, PipelineEndpoint from azureml.pipeline.core._restclients.aeva.models.error_response import ErrorResponseException ...
0.660501
0.20091
class Node(): """链表中的节点,包括数据域和指针域;使用单链表实现""" def __init__(self, data): self.data = data self.next = None def get_data(self): return self.data def set_next(self, next_node): #python内变量为引用类型,可视作指针 self.next = next_node def get_next(self): return self.next class OrderedList(): """有序列表""" def __init...
basic-ADT/list/ordered_list/ordered_list.py
class Node(): """链表中的节点,包括数据域和指针域;使用单链表实现""" def __init__(self, data): self.data = data self.next = None def get_data(self): return self.data def set_next(self, next_node): #python内变量为引用类型,可视作指针 self.next = next_node def get_next(self): return self.next class OrderedList(): """有序列表""" def __init...
0.243463
0.322046
import pytest import layabase.mongo import layabase._database_mongo import mongomock def test_str_column_cannot_auto_increment(): with pytest.raises(Exception) as exception_info: layabase.mongo.Column(should_auto_increment=True) assert str(exception_info.value) == "Only int fields can be auto increme...
tests/test_mongo.py
import pytest import layabase.mongo import layabase._database_mongo import mongomock def test_str_column_cannot_auto_increment(): with pytest.raises(Exception) as exception_info: layabase.mongo.Column(should_auto_increment=True) assert str(exception_info.value) == "Only int fields can be auto increme...
0.701304
0.479565
import os.path import collections import logging from . import walletwrapper from . import database from . import blockchain from . import paymentchannel from two1 import TWO1_CHANNELS_FEE logger = logging.getLogger('channels') PaymentChannelStatus = collections.namedtuple( 'PaymentChannelStatus', [ ...
venv/Lib/site-packages/two1/channels/paymentchannelclient.py
import os.path import collections import logging from . import walletwrapper from . import database from . import blockchain from . import paymentchannel from two1 import TWO1_CHANNELS_FEE logger = logging.getLogger('channels') PaymentChannelStatus = collections.namedtuple( 'PaymentChannelStatus', [ ...
0.831622
0.125279
from scrapy.shell import inspect_response from scrapy.spiders import CrawlSpider from scrapy.http import Request, FormRequest from scrapy.linkextractors import LinkExtractor from scrapy.spiders import Rule import time import scrapy class APHCrawler(scrapy.Spider): name = 'inshea_crawler' allowed_domains = ['h...
scraper/tourScraper.py
from scrapy.shell import inspect_response from scrapy.spiders import CrawlSpider from scrapy.http import Request, FormRequest from scrapy.linkextractors import LinkExtractor from scrapy.spiders import Rule import time import scrapy class APHCrawler(scrapy.Spider): name = 'inshea_crawler' allowed_domains = ['h...
0.430866
0.09611
from audioop import avg import matplotlib.pyplot as plt import matplotlib import numpy as np import sys import re import csv from itertools import groupby import glob """ This script plots vertical frequency bars for one bandit experiment. Give -c as to load the experiment data from .csv files """ NUM_BARS = 2 BOUND...
plotting/boxplots.py
from audioop import avg import matplotlib.pyplot as plt import matplotlib import numpy as np import sys import re import csv from itertools import groupby import glob """ This script plots vertical frequency bars for one bandit experiment. Give -c as to load the experiment data from .csv files """ NUM_BARS = 2 BOUND...
0.147801
0.369685
import functools import asyncio import re class ClientProtocol(asyncio.Protocol): identity = None chunk = None onerror = None class Patterns: regex = functools.partial(re.compile, flags=re.DOTALL) session_id = regex('^HI\s(?P<sessionid>.+)$') incomming = regex(b'^MESSAGE (?P<m...
easyq/client.py
import functools import asyncio import re class ClientProtocol(asyncio.Protocol): identity = None chunk = None onerror = None class Patterns: regex = functools.partial(re.compile, flags=re.DOTALL) session_id = regex('^HI\s(?P<sessionid>.+)$') incomming = regex(b'^MESSAGE (?P<m...
0.492676
0.164215
import sys import tarfile import base64 import re from html2text import html2text from textsanitzer import TextSanitizer magic_number = "df6fa1abb58549287111ba8d776733e9" name2code = {"ENGLISH": "en", "FRENCH": "fr"} def read_statsfile(f): stats = {} url, length = None, None for line in f: if ...
baseline/tar2bitextor.py
import sys import tarfile import base64 import re from html2text import html2text from textsanitzer import TextSanitizer magic_number = "df6fa1abb58549287111ba8d776733e9" name2code = {"ENGLISH": "en", "FRENCH": "fr"} def read_statsfile(f): stats = {} url, length = None, None for line in f: if ...
0.193948
0.098425
from time import sleep from selenium import webdriver from selenium.webdriver.common.keys import Keys class instaspy: def __init__(self, username, password, target_username): self.username = username self.password = password self.target_username = target_username self.browser = webd...
InstaSpy-script.py
from time import sleep from selenium import webdriver from selenium.webdriver.common.keys import Keys class instaspy: def __init__(self, username, password, target_username): self.username = username self.password = password self.target_username = target_username self.browser = webd...
0.232833
0.067917
import re from threading import Timer import sublime import sublime_plugin from .console_logging import getLogger from .daemon import ask_daemon from .utils import get_settings, is_python_scope, is_repl logger = getLogger(__name__) FOLLOWING_CHARS = {"\r", "\n", "\t", " ", ")", "]", ";", "}", "\x00"} PLUGIN_ONLY_CO...
sublime_jedi/completion.py
import re from threading import Timer import sublime import sublime_plugin from .console_logging import getLogger from .daemon import ask_daemon from .utils import get_settings, is_python_scope, is_repl logger = getLogger(__name__) FOLLOWING_CHARS = {"\r", "\n", "\t", " ", ")", "]", ";", "}", "\x00"} PLUGIN_ONLY_CO...
0.534612
0.149004
import click import io from prog.cli import delete from prog.cli import show from prog.cli import request from prog import client from prog import multipart from prog import output from prog import utils MAX_PAGE_SIZE = 256 # --- sessions def _output_one_session(s): click.echo("ID=%d ether=0x%04x protocol=%d a...
cli/prog/diag.py
import click import io from prog.cli import delete from prog.cli import show from prog.cli import request from prog import client from prog import multipart from prog import output from prog import utils MAX_PAGE_SIZE = 256 # --- sessions def _output_one_session(s): click.echo("ID=%d ether=0x%04x protocol=%d a...
0.300951
0.055005
import doctest import itertools try: from unittest import mock except ImportError: # python 3.2 or lower import mock from django.test import TestCase from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.conf im...
tictactoe/contest/tests.py
import doctest import itertools try: from unittest import mock except ImportError: # python 3.2 or lower import mock from django.test import TestCase from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.conf im...
0.489992
0.335977
import asyncio import apigpio import functools # This sample demonstrates both writing to gpio and listening to gpio changes. # It also shows the Debounce decorator, which might be useful when registering # a callback for a gpio connected to a button, for example. BT_GPIO = 18 LED_GPIO = 21 class Blinker(object): ...
samples/gpio_debounce.py
import asyncio import apigpio import functools # This sample demonstrates both writing to gpio and listening to gpio changes. # It also shows the Debounce decorator, which might be useful when registering # a callback for a gpio connected to a button, for example. BT_GPIO = 18 LED_GPIO = 21 class Blinker(object): ...
0.558086
0.165796
from collections import OrderedDict import pandas as pd from sklearn import metrics from sklearn.feature_extraction import DictVectorizer from sklearn.feature_selection import SelectFromModel from sklearn.model_selection import train_test_split from xgboost import XGBClassifier from common.util_function import * prin...
demo_sklearn/xgb_cart_category/card_category_feature_importance.py
from collections import OrderedDict import pandas as pd from sklearn import metrics from sklearn.feature_extraction import DictVectorizer from sklearn.feature_selection import SelectFromModel from sklearn.model_selection import train_test_split from xgboost import XGBClassifier from common.util_function import * prin...
0.261614
0.380327
import sys, os import json import unittest import hashlib sys.path.append(os.path.join(sys.path[0],'..')) from application import app from parameterized import parameterized, parameterized_class from usermanager import get_salt class TestApi(unittest.TestCase): def setUp(self): self.myapp = app.test_clien...
backend/tests/test_api.py
import sys, os import json import unittest import hashlib sys.path.append(os.path.join(sys.path[0],'..')) from application import app from parameterized import parameterized, parameterized_class from usermanager import get_salt class TestApi(unittest.TestCase): def setUp(self): self.myapp = app.test_clien...
0.366476
0.166303
import configparser import psycopg2 import boto3 from sql_queries import copy_table_queries, insert_table_queries, counting_queries def load_staging_tables(cur, conn): """ Copy data from S3 into staging tables. """ for query in copy_table_queries: try: print("Loading staging table.") ...
project_03/src/etl/etl.py
import configparser import psycopg2 import boto3 from sql_queries import copy_table_queries, insert_table_queries, counting_queries def load_staging_tables(cur, conn): """ Copy data from S3 into staging tables. """ for query in copy_table_queries: try: print("Loading staging table.") ...
0.393152
0.426381
def get_my_profile_id(): my_profile_id = '76561198028705366' return my_profile_id def get_hard_coded_market_dict(): hard_coded_market_dict = { "340390": "Abomination Tower", "381640": "Allods Online RU", "342250": "Aspectus: Rinascimento Chronicles", "636700": "Crappy Day ...
data_utils.py
def get_my_profile_id(): my_profile_id = '76561198028705366' return my_profile_id def get_hard_coded_market_dict(): hard_coded_market_dict = { "340390": "Abomination Tower", "381640": "Allods Online RU", "342250": "Aspectus: Rinascimento Chronicles", "636700": "Crappy Day ...
0.579995
0.406626
import inspect import pdb import sys import traceback from ispyd.wrapper import ObjectWrapper from ispyd.console import acquire_console, release_console _probes = {} _tracebacks = {} class DebuggerWrapper(ObjectWrapper): def __init__(self, wrapped, name): super(DebuggerWrapper, self).__init__(wrapped) ...
ispyd/plugins/debugger.py
import inspect import pdb import sys import traceback from ispyd.wrapper import ObjectWrapper from ispyd.console import acquire_console, release_console _probes = {} _tracebacks = {} class DebuggerWrapper(ObjectWrapper): def __init__(self, wrapped, name): super(DebuggerWrapper, self).__init__(wrapped) ...
0.329068
0.064742
import numpy as np import requests def day2a(dirs, start=None): """Update the horizontal position and depth Args: dirs (character list or generator): List of character strings of the form "forward/up/down int" start (int, optional): 2-dimensional starting point, where the first compone...
day2.py
import numpy as np import requests def day2a(dirs, start=None): """Update the horizontal position and depth Args: dirs (character list or generator): List of character strings of the form "forward/up/down int" start (int, optional): 2-dimensional starting point, where the first compone...
0.737914
0.535281
import numpy as np import xarray as xr import dask import dask.array as da from ._dask import randomize from ._masking import to_float_np, from_float_np def reshape_for_geomedian(ds, axis='time'): dims = set(v.dims for v in ds.data_vars.values()) if len(dims) != 1: raise ValueError("All bands should h...
libs/algo/odc/algo/_geomedian.py
import numpy as np import xarray as xr import dask import dask.array as da from ._dask import randomize from ._masking import to_float_np, from_float_np def reshape_for_geomedian(ds, axis='time'): dims = set(v.dims for v in ds.data_vars.values()) if len(dims) != 1: raise ValueError("All bands should h...
0.563618
0.575469
from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np from astropy.utils.misc import NumpyRNGContext from .pure_python_isolation import naive_spherical_isolation, naive_cylindrical_isolation from ..spherical_isolation import spherical_isolation from ..cylindrical_isola...
halotools/mock_observables/isolation_functions/tests/test_brute_force_comparisons.py
from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np from astropy.utils.misc import NumpyRNGContext from .pure_python_isolation import naive_spherical_isolation, naive_cylindrical_isolation from ..spherical_isolation import spherical_isolation from ..cylindrical_isola...
0.81283
0.701751