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 unittest
import os.path
from tableaudocumentapi import Datasource, Workbook
TEST_ASSET_DIR = os.path.join(
os.path.dirname(__file__),
'assets'
)
TEST_TDS_FILE = os.path.join(
TEST_ASSET_DIR,
'datasource_test.tds'
)
TEST_TWB_FILE = os.path.join(
TEST_ASSET_DIR,
'datasource_test.twb'
)
... | test/test_datasource.py | import unittest
import os.path
from tableaudocumentapi import Datasource, Workbook
TEST_ASSET_DIR = os.path.join(
os.path.dirname(__file__),
'assets'
)
TEST_TDS_FILE = os.path.join(
TEST_ASSET_DIR,
'datasource_test.tds'
)
TEST_TWB_FILE = os.path.join(
TEST_ASSET_DIR,
'datasource_test.twb'
)
... | 0.474388 | 0.644393 |
import math
import tensorflow as tf
import pc.configuration.config as cfg
import pc.model.base as base
import pc.model.point_cnn_patch as patch
import pc.model.point_cnn_util as pf
import pc.model.sampling.sampling as sampling
def xconv(pts, fts, qrs, tag, N, K, D, P, C, C_pts_fts, is_training, depth_multiplier,
... | pc/model/point_cnn.py | import math
import tensorflow as tf
import pc.configuration.config as cfg
import pc.model.base as base
import pc.model.point_cnn_patch as patch
import pc.model.point_cnn_util as pf
import pc.model.sampling.sampling as sampling
def xconv(pts, fts, qrs, tag, N, K, D, P, C, C_pts_fts, is_training, depth_multiplier,
... | 0.779532 | 0.518059 |
import h5py
import numpy
import sys
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('datafile', metavar='FILE',
help='the HDF5 file containing the dataset')
parser.add_argument('queryfile', metavar='FILE',
help='the text ... | additional-scripts/pick-queries.py | import h5py
import numpy
import sys
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('datafile', metavar='FILE',
help='the HDF5 file containing the dataset')
parser.add_argument('queryfile', metavar='FILE',
help='the text ... | 0.280419 | 0.171685 |
from typing import Dict, List, Optional
from flytekit.common import constants as _constants
from flytekit.common.exceptions import system as _system_exceptions
from flytekit.common.exceptions import user as _user_exceptions
from flytekit.common.mixins import hash as _hash_mixin
from flytekit.core.interface import Inte... | flytekit/remote/workflow.py | from typing import Dict, List, Optional
from flytekit.common import constants as _constants
from flytekit.common.exceptions import system as _system_exceptions
from flytekit.common.exceptions import user as _user_exceptions
from flytekit.common.mixins import hash as _hash_mixin
from flytekit.core.interface import Inte... | 0.855293 | 0.149128 |
import json
import dash.html as html
import dash.dcc as dcc
import dash_bootstrap_components as dbc
from apps.sections.m_cyto_elements import get_cyto_elements
import dash_cytoscape as cyto
from app import app
from dash.dependencies import Input, Output
stylesheet_cyto = [
{
'selector': '.box',
... | apps/sections/m_flow.py | import json
import dash.html as html
import dash.dcc as dcc
import dash_bootstrap_components as dbc
from apps.sections.m_cyto_elements import get_cyto_elements
import dash_cytoscape as cyto
from app import app
from dash.dependencies import Input, Output
stylesheet_cyto = [
{
'selector': '.box',
... | 0.307462 | 0.148201 |
import os, pdb
import torch
import torch.utils.data as data
import cv2, pickle
import numpy as np
from .shared import CLASSES, make_lists
np.random.seed(123)
class ActionDetection(data.Dataset):
def __init__(self, args, image_set, transform=None, normlise_boxes=None, anno_transform=None, full_test=False):
... | data/dataset.py | import os, pdb
import torch
import torch.utils.data as data
import cv2, pickle
import numpy as np
from .shared import CLASSES, make_lists
np.random.seed(123)
class ActionDetection(data.Dataset):
def __init__(self, args, image_set, transform=None, normlise_boxes=None, anno_transform=None, full_test=False):
... | 0.14851 | 0.256279 |
import torch
from torch import nn
from pysc2.lib import actions, features
from env_wrapper_abstract.env_wrapper import EnvWrapperAbstract
import numpy as np
from math import sqrt
FUNCTIONS = actions.FUNCTIONS
_NO_OP = actions.FUNCTIONS.no_op.id
_MOVE_SCREEN = actions.FUNCTIONS.Move_screen.id
_PLAYER_NEUTRAL = features... | env_pysc2/env_wrapper.py | import torch
from torch import nn
from pysc2.lib import actions, features
from env_wrapper_abstract.env_wrapper import EnvWrapperAbstract
import numpy as np
from math import sqrt
FUNCTIONS = actions.FUNCTIONS
_NO_OP = actions.FUNCTIONS.no_op.id
_MOVE_SCREEN = actions.FUNCTIONS.Move_screen.id
_PLAYER_NEUTRAL = features... | 0.846006 | 0.422803 |
from types import *
_dir = lambda o: o.__dict__.keys()
def _get_type_dict(object):
# create a dict with keys: attr, instance, list
type_dict = {'attr': [], 'instance': [], 'list': []}
for membname in _dir(object):
if membname == '__parent__':
continue
object_type = type(getattr... | download/gnosis/xml/objectify/_printer.py |
from types import *
_dir = lambda o: o.__dict__.keys()
def _get_type_dict(object):
# create a dict with keys: attr, instance, list
type_dict = {'attr': [], 'instance': [], 'list': []}
for membname in _dir(object):
if membname == '__parent__':
continue
object_type = type(getattr... | 0.271059 | 0.056914 |
from random import random
from normals import inverse_cumulative_normal
from sys import version_info
if version_info[0] == 3:
xrange = range
class RandomBase(object):
"""
Abstract random number class.
Uses the standard library's random() for uniform random variables and
normals.inverse_cumulativ... | random_base.py |
from random import random
from normals import inverse_cumulative_normal
from sys import version_info
if version_info[0] == 3:
xrange = range
class RandomBase(object):
"""
Abstract random number class.
Uses the standard library's random() for uniform random variables and
normals.inverse_cumulativ... | 0.615088 | 0.375621 |
"""##### 1 [ Split into training ] #####"""
"""##### 2 [ Extract train and test idx for later merge with geography coord ] #####"""
"""##### 3 [ Fit: Polynomial Regression ] ######"""
## 3. 1 Fit Model: Polynomial Regression
### Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialF... | polynomial_regression.py | """##### 1 [ Split into training ] #####"""
"""##### 2 [ Extract train and test idx for later merge with geography coord ] #####"""
"""##### 3 [ Fit: Polynomial Regression ] ######"""
## 3. 1 Fit Model: Polynomial Regression
### Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialF... | 0.887595 | 0.881717 |
import argparse
import json
import logging
from os.path import join as pathjoin
from os.path import abspath, exists, isdir
from time import time
from tsstats import config
from tsstats.exceptions import InvalidConfiguration
from tsstats.log import parse_logs
from tsstats.logger import file_handler, stream_handler
from... | tsstats/__main__.py | import argparse
import json
import logging
from os.path import join as pathjoin
from os.path import abspath, exists, isdir
from time import time
from tsstats import config
from tsstats.exceptions import InvalidConfiguration
from tsstats.log import parse_logs
from tsstats.logger import file_handler, stream_handler
from... | 0.278453 | 0.065455 |
import json
import sys
import unittest
import os
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.append(SCRIPT_DIR)
CODESEARCH_DIR = os.path.join(
os.path.dirname(SCRIPT_DIR), 'third_party', 'codesearch-py')
sys.path.append(CODESEARCH_DIR)
import render as r
import codesearch as cs
def TestD... | render/test_render.py |
import json
import sys
import unittest
import os
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.append(SCRIPT_DIR)
CODESEARCH_DIR = os.path.join(
os.path.dirname(SCRIPT_DIR), 'third_party', 'codesearch-py')
sys.path.append(CODESEARCH_DIR)
import render as r
import codesearch as cs
def TestD... | 0.453504 | 0.36139 |
import parser_utils
from datetime import datetime
from decimal import *
from typing import Dict
from rbc_statement import Statement
class RbcBankStatement(Statement):
def parse(self, str_data: str):
if "No activity for this period" in str_data:
return
str_data = str_data.spl... | rbc_chequing.py | import parser_utils
from datetime import datetime
from decimal import *
from typing import Dict
from rbc_statement import Statement
class RbcBankStatement(Statement):
def parse(self, str_data: str):
if "No activity for this period" in str_data:
return
str_data = str_data.spl... | 0.346099 | 0.152316 |
class Funcionario(object):
def __init__(self, nome, cpf, salario):
self._nome = nome
self._cpf = cpf
self._salario = salario
def get_bonificacao(self):
return self._salario * 0.10
class Gerente(Funcionario):
def __init__(self, nome, cpf, salario, senha, qtd_funcionarios):
... | Caelum_Classes.py | class Funcionario(object):
def __init__(self, nome, cpf, salario):
self._nome = nome
self._cpf = cpf
self._salario = salario
def get_bonificacao(self):
return self._salario * 0.10
class Gerente(Funcionario):
def __init__(self, nome, cpf, salario, senha, qtd_funcionarios):
... | 0.506591 | 0.1495 |
import sys
import serial
import serial.tools.list_ports
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import QTimer
from ui_demo_1 import Ui_Form
from PyQt5.QtGui import QFont
from binascii import *
from crcmod import *
class Pyqt5_Serial(QtWidgets.QWidget, Ui_Form):
def __in... | main.py | import sys
import serial
import serial.tools.list_ports
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import QTimer
from ui_demo_1 import Ui_Form
from PyQt5.QtGui import QFont
from binascii import *
from crcmod import *
class Pyqt5_Serial(QtWidgets.QWidget, Ui_Form):
def __in... | 0.243822 | 0.080466 |
import sys, time, gpiod
from argparse import *
class buttonpress:
def __init__(self, chip_button, chip_led):
"""Handle possibility of button and led on different GPIO chips
"""
self.chip_button = gpiod.Chip(chip_button, gpiod.Chip.OPEN_BY_PATH)
if chip_led != chip_but... | libgpiod/python/src/buttonpress.py | import sys, time, gpiod
from argparse import *
class buttonpress:
def __init__(self, chip_button, chip_led):
"""Handle possibility of button and led on different GPIO chips
"""
self.chip_button = gpiod.Chip(chip_button, gpiod.Chip.OPEN_BY_PATH)
if chip_led != chip_but... | 0.250821 | 0.102934 |
import os
import logging
import threading
import yaml
from inotify_simple import INotify, flags
from ambianic.config_mgm.config_diff import Config
from ambianic.config_mgm import fileutils
log = logging.getLogger(__name__)
class ConfigurationManager:
"""Configuration manager handles configuration centrally and
... | src/ambianic/config_mgm/configuration_manager.py |
import os
import logging
import threading
import yaml
from inotify_simple import INotify, flags
from ambianic.config_mgm.config_diff import Config
from ambianic.config_mgm import fileutils
log = logging.getLogger(__name__)
class ConfigurationManager:
"""Configuration manager handles configuration centrally and
... | 0.604983 | 0.076477 |
import os
import zipfile
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras import layers
from tensorflow.keras import Model
import matplotlib.pyplot as plt
from keras.applications.vgg16 import VGG16
batch_size = 32
img_height = 180
img_width = 180
... | VGG_Classification.py | import os
import zipfile
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras import layers
from tensorflow.keras import Model
import matplotlib.pyplot as plt
from keras.applications.vgg16 import VGG16
batch_size = 32
img_height = 180
img_width = 180
... | 0.573201 | 0.504822 |
import concurrent.futures
import cv2
import os
import shutil
import imaging_db.filestorage.data_storage as data_storage
class LocalStorage(data_storage.DataStorage):
"""Class for handling image and file transfers to local storage"""
def __init__(self,
storage_dir,
nbr_worke... | imaging_db/filestorage/local_storage.py | import concurrent.futures
import cv2
import os
import shutil
import imaging_db.filestorage.data_storage as data_storage
class LocalStorage(data_storage.DataStorage):
"""Class for handling image and file transfers to local storage"""
def __init__(self,
storage_dir,
nbr_worke... | 0.68342 | 0.326164 |
import hashlib
from os import makedirs, symlink
from shutil import rmtree
from os.path import join, basename
from unittest.mock import patch
from egcg_core import util
from tests import TestEGCG
fastq_dir = join(TestEGCG.assets_path, 'fastqs')
def test_find_files():
expected = [join(TestEGCG.assets_path, f) for ... | tests/test_util.py | import hashlib
from os import makedirs, symlink
from shutil import rmtree
from os.path import join, basename
from unittest.mock import patch
from egcg_core import util
from tests import TestEGCG
fastq_dir = join(TestEGCG.assets_path, 'fastqs')
def test_find_files():
expected = [join(TestEGCG.assets_path, f) for ... | 0.625896 | 0.469338 |
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\13")
buf.write("\65\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t")
buf.write("\7\4\b\t\b\4... | antlr/BooleanExprLexer.py | from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\13")
buf.write("\65\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t")
buf.write("\7\4\b\t\b\4... | 0.31237 | 0.367128 |
from functools import lru_cache
from typing import Any, cast, Optional, Type, Callable, Union, Dict, Tuple, TypeVar, List
import django
from django.db import router, DEFAULT_DB_ALIAS, connections
from django.db.backends.base.base import BaseDatabaseWrapper
from django.db.backends.base.operations import BaseDatabaseOpe... | dj_hybrid/expression_wrapper/convert.py | from functools import lru_cache
from typing import Any, cast, Optional, Type, Callable, Union, Dict, Tuple, TypeVar, List
import django
from django.db import router, DEFAULT_DB_ALIAS, connections
from django.db.backends.base.base import BaseDatabaseWrapper
from django.db.backends.base.operations import BaseDatabaseOpe... | 0.780788 | 0.12787 |
import asyncio
from typing import List
import pyppeteer
from tqdm import tqdm
from tiktokpy.client import Client
from tiktokpy.utils.client import catch_response_and_store
from tiktokpy.utils.logger import logger
class Trending:
def __init__(self, client: Client):
self.client = client
async def fee... | tiktokpy/client/trending.py | import asyncio
from typing import List
import pyppeteer
from tqdm import tqdm
from tiktokpy.client import Client
from tiktokpy.utils.client import catch_response_and_store
from tiktokpy.utils.logger import logger
class Trending:
def __init__(self, client: Client):
self.client = client
async def fee... | 0.424293 | 0.130951 |
import time
import torch
from torch.utils.data import DataLoader, random_split
from torch.optim import Adam, SGD
from torchvision import transforms
from dataset import Caltech101Data, load_caltech101_pretrained, load_caltech256_pretrained, classes_101, classes_256
from classifier import DIM, ClassifierResnetLight, cla... | trainer.py | import time
import torch
from torch.utils.data import DataLoader, random_split
from torch.optim import Adam, SGD
from torchvision import transforms
from dataset import Caltech101Data, load_caltech101_pretrained, load_caltech256_pretrained, classes_101, classes_256
from classifier import DIM, ClassifierResnetLight, cla... | 0.86764 | 0.501892 |
import random
import math
class RSA:
def gen_prime(self):
prime=0
while True:
c=0
a=random.randint(100, 1000)
if not a%2==0:
i=3
while i*i<=a:
if a%i==0:
c+=1
i+=2
... | rsa.py |
import random
import math
class RSA:
def gen_prime(self):
prime=0
while True:
c=0
a=random.randint(100, 1000)
if not a%2==0:
i=3
while i*i<=a:
if a%i==0:
c+=1
i+=2
... | 0.113113 | 0.173323 |
import json
from apischema.json_schema import deserialization_schema, JsonSchemaVersion
from optunaz.config.optconfig import OptimizationConfig
from optunaz.utils.schema import (
replacekey,
addsibling,
delsibling,
copytitle,
replaceenum,
addtitles,
)
def patch_schema_generic(schema):
a... | optunaz/schemagen.py | import json
from apischema.json_schema import deserialization_schema, JsonSchemaVersion
from optunaz.config.optconfig import OptimizationConfig
from optunaz.utils.schema import (
replacekey,
addsibling,
delsibling,
copytitle,
replaceenum,
addtitles,
)
def patch_schema_generic(schema):
a... | 0.531939 | 0.299656 |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from django.shortcuts import render
from django.urls import reverse
from ..forms import UserProfileForm
from ..utilities import set_message_and_red... | blackbook/archive/views/profile.py | from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from django.shortcuts import render
from django.urls import reverse
from ..forms import UserProfileForm
from ..utilities import set_message_and_red... | 0.420124 | 0.111145 |
import logging
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.utils import shuffle
from tqdm import tqdm
from webias.constants import LOGGING_CONFIG
from webias.utils import build_word_embedding_cache
logging.basicConfig(**LOGGING_CONFIG)
class RNSB:
"""An implementation o... | webias/rnsb.py |
import logging
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.utils import shuffle
from tqdm import tqdm
from webias.constants import LOGGING_CONFIG
from webias.utils import build_word_embedding_cache
logging.basicConfig(**LOGGING_CONFIG)
class RNSB:
"""An implementation o... | 0.929648 | 0.72309 |
from nose.tools import eq_
import appvalidator.testcases.markup.markuptester as markuptester
from ..helper import TestCase
from js_helper import silent, TestCase as JSTestCase
class TestCSPTags(TestCase):
def analyze(self, snippet, app_type="web"):
self.setup_err()
self.err.save_resource("app_t... | tests/js/test_csp.py | from nose.tools import eq_
import appvalidator.testcases.markup.markuptester as markuptester
from ..helper import TestCase
from js_helper import silent, TestCase as JSTestCase
class TestCSPTags(TestCase):
def analyze(self, snippet, app_type="web"):
self.setup_err()
self.err.save_resource("app_t... | 0.532425 | 0.382718 |
from __future__ import (absolute_import, print_function, division,
unicode_literals)
import logging
import ema_workbench
try:
import unittest.mock as mock
except ImportError:
import mock
import unittest
from ema_workbench.util import ema_logging
def tearDownModule():
ema_logging._... | test/test_util/test_ema_logging.py | from __future__ import (absolute_import, print_function, division,
unicode_literals)
import logging
import ema_workbench
try:
import unittest.mock as mock
except ImportError:
import mock
import unittest
from ema_workbench.util import ema_logging
def tearDownModule():
ema_logging._... | 0.524638 | 0.240758 |
from gocept.amqprun.readfiles import FileStoreReader, FileStoreDataManager
from unittest import mock
import gocept.amqprun.interfaces
import gocept.amqprun.testing
import os
import shutil
import tempfile
import unittest
import zope.component
import time
class ReaderTest(unittest.TestCase):
def setUp(self):
... | src/gocept/amqprun/tests/test_readfiles.py | from gocept.amqprun.readfiles import FileStoreReader, FileStoreDataManager
from unittest import mock
import gocept.amqprun.interfaces
import gocept.amqprun.testing
import os
import shutil
import tempfile
import unittest
import zope.component
import time
class ReaderTest(unittest.TestCase):
def setUp(self):
... | 0.454714 | 0.305341 |
from DBC import *
import unit_testing as ut
# Class tests
class TestArgumentError(ut.ClassTest):
def __init__(self):
ut.ClassTest.__init__(self)
def test___init__(self):
ut.test(isinstance(ArgumentError('function', 'parameter', tuple),
Argume... | DBC_test.py | from DBC import *
import unit_testing as ut
# Class tests
class TestArgumentError(ut.ClassTest):
def __init__(self):
ut.ClassTest.__init__(self)
def test___init__(self):
ut.test(isinstance(ArgumentError('function', 'parameter', tuple),
Argume... | 0.432663 | 0.419351 |
from __future__ import unicode_literals
import tarfile
from .buffer import DockerTempFile
from .dockerfile import DockerFile
class DockerContext(DockerTempFile):
"""
Class for constructing a Docker context tarball, that can be sent to the remote API. If a :class:`~DockerFile`
instance is added, the resu... | dockermap/build/context.py | from __future__ import unicode_literals
import tarfile
from .buffer import DockerTempFile
from .dockerfile import DockerFile
class DockerContext(DockerTempFile):
"""
Class for constructing a Docker context tarball, that can be sent to the remote API. If a :class:`~DockerFile`
instance is added, the resu... | 0.786336 | 0.151341 |
"""Module containing the get_ece_bias function."""
import numpy as np
from caltrain.run_calibration import estimate_ece
from caltrain.utils import get_hash_key
def get_ece_bias(config,
n_samples,
ce_types,
params,
cached_result=None,
... | caltrain/get_ece_bias.py |
"""Module containing the get_ece_bias function."""
import numpy as np
from caltrain.run_calibration import estimate_ece
from caltrain.utils import get_hash_key
def get_ece_bias(config,
n_samples,
ce_types,
params,
cached_result=None,
... | 0.804483 | 0.487978 |
import tracking.helpers as hlp
from config.locations import locations
class Sensor():
"""
Handles data and new events for a single sensor.
One Sensor object per sensor in scheme.
Handles buffering scheme for grouping CCONs.
"""
def __init__(self, device, sensor_id):
"""
Sens... | tracking/sensors.py | import tracking.helpers as hlp
from config.locations import locations
class Sensor():
"""
Handles data and new events for a single sensor.
One Sensor object per sensor in scheme.
Handles buffering scheme for grouping CCONs.
"""
def __init__(self, device, sensor_id):
"""
Sens... | 0.649467 | 0.339061 |
from shop.shopper_base import ShopperBase
import datetime
import os
import time
import math
import random
from typing import Dict, Tuple, Union, List, Callable
import keyboard
import numpy as np
from screen import convert_screen_to_monitor, grab, convert_abs_to_monitor, convert_screen_to_abs, convert_monitor_to_scree... | src/shop/shopper_drognan.py | from shop.shopper_base import ShopperBase
import datetime
import os
import time
import math
import random
from typing import Dict, Tuple, Union, List, Callable
import keyboard
import numpy as np
from screen import convert_screen_to_monitor, grab, convert_abs_to_monitor, convert_screen_to_abs, convert_monitor_to_scree... | 0.47025 | 0.202049 |
import numpy
import h5py
from optparse import OptionParser
import matplotlib
parser = OptionParser()
parser.add_option("--folder", type="string", default='full/pass1/', dest="folder", help="folder of the output data to be plotted")
parser.add_option("--savePlots", action="store_true", dest="savePlots", help="include t... | tests/syntheticTestScripts/plotResiduals.py | import numpy
import h5py
from optparse import OptionParser
import matplotlib
parser = OptionParser()
parser.add_option("--folder", type="string", default='full/pass1/', dest="folder", help="folder of the output data to be plotted")
parser.add_option("--savePlots", action="store_true", dest="savePlots", help="include t... | 0.477311 | 0.377455 |
"""Dynamic Data"""
import asyncio
import base64
import random
import uuid
from fastapi import APIRouter
from fastapi import Path
from fastapi import Query
from fastapi.responses import PlainTextResponse
from starlette import status
from starlette.requests import Request
from starlette.responses import JSONResponse
fr... | httpbin/routers/dynamicdata.py | """Dynamic Data"""
import asyncio
import base64
import random
import uuid
from fastapi import APIRouter
from fastapi import Path
from fastapi import Query
from fastapi.responses import PlainTextResponse
from starlette import status
from starlette.requests import Request
from starlette.responses import JSONResponse
fr... | 0.763131 | 0.143788 |
import mock
from armada import const
from armada.exceptions import manifest_exceptions
from armada.handlers import helm
from armada.handlers import wait
from armada.tests.unit import base
test_chart = {'wait': {'timeout': 10, 'native': {'enabled': False}}}
class ChartWaitTestCase(base.ArmadaTestCase):
def get_... | armada/tests/unit/handlers/test_wait.py |
import mock
from armada import const
from armada.exceptions import manifest_exceptions
from armada.handlers import helm
from armada.handlers import wait
from armada.tests.unit import base
test_chart = {'wait': {'timeout': 10, 'native': {'enabled': False}}}
class ChartWaitTestCase(base.ArmadaTestCase):
def get_... | 0.655777 | 0.222594 |
import unittest
import pytest
from pants.option.option_value_container import OptionValueContainerBuilder
from pants.option.ranked_value import Rank, RankedValue
class OptionValueContainerTest(unittest.TestCase):
def test_unknown_values(self) -> None:
ob = OptionValueContainerBuilder()
ob.foo =... | src/python/pants/option/option_value_container_test.py |
import unittest
import pytest
from pants.option.option_value_container import OptionValueContainerBuilder
from pants.option.ranked_value import Rank, RankedValue
class OptionValueContainerTest(unittest.TestCase):
def test_unknown_values(self) -> None:
ob = OptionValueContainerBuilder()
ob.foo =... | 0.703957 | 0.492798 |
import subprocess
import re
from enum import Enum
class SolverQueryResult(Enum):
"""
Enum to store the result of a single solver query through "(check-sat)" query.
"""
SAT = 0 # solver query reports SAT
UNSAT = 1 # solver query reports UNSAT
UNKNOWN = 2 # solver query reports... | src/modules/Solver.py | import subprocess
import re
from enum import Enum
class SolverQueryResult(Enum):
"""
Enum to store the result of a single solver query through "(check-sat)" query.
"""
SAT = 0 # solver query reports SAT
UNSAT = 1 # solver query reports UNSAT
UNKNOWN = 2 # solver query reports... | 0.524882 | 0.337968 |
import requests_mock
import json
from unittest.mock import patch
from iconsdk.builder.transaction_builder import DepositTransactionBuilder
from iconsdk.signed_transaction import SignedTransaction
from iconsdk.utils.validation import is_T_HASH
from tests.api_send.test_send_super import TestSendSuper
from tests.example_... | tests/api_send/test_send_deposit.py | import requests_mock
import json
from unittest.mock import patch
from iconsdk.builder.transaction_builder import DepositTransactionBuilder
from iconsdk.signed_transaction import SignedTransaction
from iconsdk.utils.validation import is_T_HASH
from tests.api_send.test_send_super import TestSendSuper
from tests.example_... | 0.631708 | 0.234988 |
# Standard Imports
from mysql.connector import connect, errorcode, Error
import pandas as pd
from .privatekeys import config
import os
def get_weatherData():
"""
API to query data for all available weather data from the database
Input: None
Output: Pandas Dataframe
"""
try:
cnx = connect(**config)
... | db/connection.py | # Standard Imports
from mysql.connector import connect, errorcode, Error
import pandas as pd
from .privatekeys import config
import os
def get_weatherData():
"""
API to query data for all available weather data from the database
Input: None
Output: Pandas Dataframe
"""
try:
cnx = connect(**config)
... | 0.403802 | 0.188137 |
import setuptools
from PyTrinamic.version import __version__
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="PyTrinamic",
version=__version__,
author="ED, LK, LH, JM, ..",
author_email="<EMAIL>",
description="TRINAMIC's Python Technology Acces... | setup.py | import setuptools
from PyTrinamic.version import __version__
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="PyTrinamic",
version=__version__,
author="ED, LK, LH, JM, ..",
author_email="<EMAIL>",
description="TRINAMIC's Python Technology Acces... | 0.393385 | 0.14885 |
from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
from users.serializers import UserSerializer
from .models import Event
class EventSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.HyperlinkedRelatedField(view_name='user-detail', blank=True)
... | onegreek/events/serializers.py | from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
from users.serializers import UserSerializer
from .models import Event
class EventSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.HyperlinkedRelatedField(view_name='user-detail', blank=True)
... | 0.656878 | 0.127653 |
import pytest
from eth.db.atomic import AtomicDB
from tests.core.integration_test_helpers import (
load_fixture_db,
load_mining_chain,
DBFixture,
)
@pytest.fixture
def leveldb_20():
yield from load_fixture_db(DBFixture.TWENTY_POW_HEADERS)
@pytest.fixture
def leveldb_1000():
yield from load_fix... | tests/core/p2p-proto/conftest.py | import pytest
from eth.db.atomic import AtomicDB
from tests.core.integration_test_helpers import (
load_fixture_db,
load_mining_chain,
DBFixture,
)
@pytest.fixture
def leveldb_20():
yield from load_fixture_db(DBFixture.TWENTY_POW_HEADERS)
@pytest.fixture
def leveldb_1000():
yield from load_fix... | 0.668015 | 0.429489 |
import pandas as pd
import world_bank_data as wb
from common import *
import info_gdf
def info_countries_df():
countries = wb.get_countries()
# Population dataset, by the World Bank (most recent value), indexed with the country code
population = wb.get_series('SP.POP.TOTL', id_or_value='id', simplify_ind... | info_df.py | import pandas as pd
import world_bank_data as wb
from common import *
import info_gdf
def info_countries_df():
countries = wb.get_countries()
# Population dataset, by the World Bank (most recent value), indexed with the country code
population = wb.get_series('SP.POP.TOTL', id_or_value='id', simplify_ind... | 0.315209 | 0.386416 |
from __future__ import unicode_literals
import django
from django.test.testcases import TestCase
from data.data.data import Data
from data.data.exceptions import InvalidData
from data.data.value import FileValue, JsonValue
from data.interface.parameter import FileParameter, JsonParameter
from data.dataset.dataset im... | scale/data/test/dataset/test_dataset.py | from __future__ import unicode_literals
import django
from django.test.testcases import TestCase
from data.data.data import Data
from data.data.exceptions import InvalidData
from data.data.value import FileValue, JsonValue
from data.interface.parameter import FileParameter, JsonParameter
from data.dataset.dataset im... | 0.491456 | 0.569613 |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | benchmarks/SimResults/combinations_spec_ml_deepnet/cmp_astarlbmtontoh264ref/power.py | power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | 0.600188 | 0.285646 |
import os
import random
import numpy as np
import glob
import librosa
import tensorflow as tf
from models.relgan import RelGAN
from speech_tools import load_pickle, sample_train_data
from speech_tools import *
import argparse
from hparams import *
random.seed(seed)
np.random.seed(seed)
tf.set_random_seed(seed)
def ma... | train_relgan_vm.py | import os
import random
import numpy as np
import glob
import librosa
import tensorflow as tf
from models.relgan import RelGAN
from speech_tools import load_pickle, sample_train_data
from speech_tools import *
import argparse
from hparams import *
random.seed(seed)
np.random.seed(seed)
tf.set_random_seed(seed)
def ma... | 0.378459 | 0.174164 |
import logging
import pygame
import pygame.event
from and_beyond.client import globals
from and_beyond.client.consts import SERVER_DISCONNECT_EVENT
from and_beyond.client.ui import Ui, UiButton, UiLabel
from and_beyond.client.ui.label_screen import LabelScreen
from and_beyond.client.ui.options_menu import OptionsMenu
... | and_beyond/client/ui/pause_menu.py | import logging
import pygame
import pygame.event
from and_beyond.client import globals
from and_beyond.client.consts import SERVER_DISCONNECT_EVENT
from and_beyond.client.ui import Ui, UiButton, UiLabel
from and_beyond.client.ui.label_screen import LabelScreen
from and_beyond.client.ui.options_menu import OptionsMenu
... | 0.272799 | 0.091463 |
# Copyright (c) 2016 GoSecure Inc.
OPCODES = {
0 : "NOP",
1 : "ADD",
2 : "SUB",
3 : "MUL",
4 : "DIV",
5 : "MOD",
6 : "SL",
7 : "SR",
8 : "CONCAT",
9 : "BW_OR",
10 : "BW_AND",
11 : "BW_XOR",
12 : "BW_NOT",
13 : "BOOL_NOT",
14 : "BOOL_XOR",
15 : "IS_IDENTI... | analysis_tools/definitions.py |
# Copyright (c) 2016 GoSecure Inc.
OPCODES = {
0 : "NOP",
1 : "ADD",
2 : "SUB",
3 : "MUL",
4 : "DIV",
5 : "MOD",
6 : "SL",
7 : "SR",
8 : "CONCAT",
9 : "BW_OR",
10 : "BW_AND",
11 : "BW_XOR",
12 : "BW_NOT",
13 : "BOOL_NOT",
14 : "BOOL_XOR",
15 : "IS_IDENTI... | 0.357904 | 0.465752 |
try:
import tensorflow as tf
except ImportError:
print 'Need to install the "tensorflow" module (available on Linux and MacOS only for python 2.7) : "pip install tensorflow" or with Anaconda "conda install tensorflow"'
exit()
import sys
sys.path.insert(0, '../src/') # To be able to import packages from p... | examples/DAE_pre_processing.py | try:
import tensorflow as tf
except ImportError:
print 'Need to install the "tensorflow" module (available on Linux and MacOS only for python 2.7) : "pip install tensorflow" or with Anaconda "conda install tensorflow"'
exit()
import sys
sys.path.insert(0, '../src/') # To be able to import packages from p... | 0.463201 | 0.427217 |
from __future__ import absolute_import, print_function
from abc import ABCMeta, abstractmethod
import six
from .utilities import inherit_docstrings, Parantheses
__all__ = ['ReprHelper', 'PrettyReprHelper']
@six.add_metaclass(ABCMeta)
class BaseReprHelper(object):
def __init__(self, other):
self.parant... | dbops_venv/lib/python3.5/site-packages/represent/helper.py | from __future__ import absolute_import, print_function
from abc import ABCMeta, abstractmethod
import six
from .utilities import inherit_docstrings, Parantheses
__all__ = ['ReprHelper', 'PrettyReprHelper']
@six.add_metaclass(ABCMeta)
class BaseReprHelper(object):
def __init__(self, other):
self.parant... | 0.839832 | 0.154058 |
from game import Game
import sys
class TicTacToe(Game):
"""Tic Tac Toe game class."""
def __init__(self):
"""Construct new tictactoe game instance."""
self.board = ['-', '-', '-', '-', '-', '-', '-', '-', '-']
self.player = 'X'
self.winner = None
def reset(self):
... | game/tictactoe.py | from game import Game
import sys
class TicTacToe(Game):
"""Tic Tac Toe game class."""
def __init__(self):
"""Construct new tictactoe game instance."""
self.board = ['-', '-', '-', '-', '-', '-', '-', '-', '-']
self.player = 'X'
self.winner = None
def reset(self):
... | 0.718792 | 0.408749 |
import mock
import uuid
from cinder import test
import cinder.volume.drivers.netapp.api as ntapi
import cinder.volume.drivers.netapp.iscsi as ntap_iscsi
class NetAppDirectISCSIDriverTestCase(test.TestCase):
def setUp(self):
super(NetAppDirectISCSIDriverTestCase, self).setUp()
self.driver = ntap_... | cinder/tests/volume/drivers/netapp/test_iscsi.py | import mock
import uuid
from cinder import test
import cinder.volume.drivers.netapp.api as ntapi
import cinder.volume.drivers.netapp.iscsi as ntap_iscsi
class NetAppDirectISCSIDriverTestCase(test.TestCase):
def setUp(self):
super(NetAppDirectISCSIDriverTestCase, self).setUp()
self.driver = ntap_... | 0.580471 | 0.182608 |
from collections.abc import Sequence
import numpy as np
class Vertex:
"""
# VERTEX
The vertex class is a fundemental, versatille and easy to use class containing positional and color data.
The data is stored as x,y,z,r,g,b attributes. However the data can be accessed and modified in a variety of... | src/pygline/common.py | from collections.abc import Sequence
import numpy as np
class Vertex:
"""
# VERTEX
The vertex class is a fundemental, versatille and easy to use class containing positional and color data.
The data is stored as x,y,z,r,g,b attributes. However the data can be accessed and modified in a variety of... | 0.955236 | 0.882022 |
"""Tests for the FileSystemTimelineJob job."""
from __future__ import unicode_literals
import glob
import unittest
import os
import mock
from turbinia.evidence import BodyFile
from turbinia.workers import file_system_timeline
from turbinia.workers import TurbiniaTaskResult
from turbinia.workers.workers_test import T... | turbinia/workers/file_system_timeline_test.py | """Tests for the FileSystemTimelineJob job."""
from __future__ import unicode_literals
import glob
import unittest
import os
import mock
from turbinia.evidence import BodyFile
from turbinia.workers import file_system_timeline
from turbinia.workers import TurbiniaTaskResult
from turbinia.workers.workers_test import T... | 0.624523 | 0.241054 |
from helpers import show_dotted_image
import cv2
import numpy as np
class BirdsEye:
def __init__(self, source_points, dest_points, cam_matrix, distortion_coef):
self.spoints = source_points
self.dpoints = dest_points
self.src_points = np.array(source_points, np.float32)
self.dest_points = np.a... | birdseye.py | from helpers import show_dotted_image
import cv2
import numpy as np
class BirdsEye:
def __init__(self, source_points, dest_points, cam_matrix, distortion_coef):
self.spoints = source_points
self.dpoints = dest_points
self.src_points = np.array(source_points, np.float32)
self.dest_points = np.a... | 0.536799 | 0.330228 |
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
print(f"PyTorch version: {torch.__version__}")
# Device configuration
if torch.cuda.is_available():
device = torch.device("cuda")
print("GPU found :)")
else:
device = torch.device("cpu")
print("No GPU :(")
def main():
"""Main fu... | pytorch/linear_regression.py |
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
print(f"PyTorch version: {torch.__version__}")
# Device configuration
if torch.cuda.is_available():
device = torch.device("cuda")
print("GPU found :)")
else:
device = torch.device("cpu")
print("No GPU :(")
def main():
"""Main fu... | 0.788135 | 0.603465 |
import datasets
import torch # type: ignore
import numpy as np
import absl.flags
import absl.app
import os
import aux
from typing import Tuple
# user flags
absl.flags.DEFINE_string("path_models", None, "Path of the trained model")
absl.flags.DEFINE_string("dir_dataset", 'datasets/', "dir path where datasets are stored... | paper/explanation_accuracy.py | import datasets
import torch # type: ignore
import numpy as np
import absl.flags
import absl.app
import os
import aux
from typing import Tuple
# user flags
absl.flags.DEFINE_string("path_models", None, "Path of the trained model")
absl.flags.DEFINE_string("dir_dataset", 'datasets/', "dir path where datasets are stored... | 0.853058 | 0.497864 |
import logging
import os
import shutil
from tempfile import mkdtemp
from service_buddy.ci.ci import BuildCreator
from service_buddy.ci.travis_build_creator import TravisBuildCreator
from service_buddy.service import loader
from service_buddy.service.service import Service
from service_buddy.util import pretty_printer
... | src/unittest/python/travis_build_tests.py | import logging
import os
import shutil
from tempfile import mkdtemp
from service_buddy.ci.ci import BuildCreator
from service_buddy.ci.travis_build_creator import TravisBuildCreator
from service_buddy.service import loader
from service_buddy.service.service import Service
from service_buddy.util import pretty_printer
... | 0.213131 | 0.251418 |
import time
from donkeycar.gym import remote_controller
class DonkeyCar:
def __init__(self, car = "kari", server = "mqtt.eclipse.org"):
self.control = remote_controller.DonkeyRemoteContoller(car, server)
self.state = self.control.observe()
self.action = [0, 0]
self.throttle = ... | environments/donkey_car.py | import time
from donkeycar.gym import remote_controller
class DonkeyCar:
def __init__(self, car = "kari", server = "mqtt.eclipse.org"):
self.control = remote_controller.DonkeyRemoteContoller(car, server)
self.state = self.control.observe()
self.action = [0, 0]
self.throttle = ... | 0.446977 | 0.180504 |
import os
import re
import subprocess
BASE_COMMAND = 'python bert_experiments.py'
def evaluate(model, task, max_seq_length, checkpoint_dir,
linformer_k=None, blocks=None):
command = ('{0} --model {1} --task {2} --max_seq_length {3} '
'--load_from_checkpoint --checkpoint_dir {4} --eval'... | src/bert_optimizer.py | import os
import re
import subprocess
BASE_COMMAND = 'python bert_experiments.py'
def evaluate(model, task, max_seq_length, checkpoint_dir,
linformer_k=None, blocks=None):
command = ('{0} --model {1} --task {2} --max_seq_length {3} '
'--load_from_checkpoint --checkpoint_dir {4} --eval'... | 0.595963 | 0.178222 |
import ROOT
import pyhf
import click
import json
@click.command()
@click.option(
"--root-workspace",
help="The location of the root file containing the combined root workspace",
)
@click.option(
"--pyhf-json",
help="The location of the json file containing the pyhf likelihood info",
)
def compare_nuis... | scripts/compare_nuisance.py | import ROOT
import pyhf
import click
import json
@click.command()
@click.option(
"--root-workspace",
help="The location of the root file containing the combined root workspace",
)
@click.option(
"--pyhf-json",
help="The location of the json file containing the pyhf likelihood info",
)
def compare_nuis... | 0.38885 | 0.245571 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def epilepsy(path):
"""Epilepsy Attacks Data Set
Data from a clinical trial of 59 patients wit... | observations/r/epilepsy.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def epilepsy(path):
"""Epilepsy Attacks Data Set
Data from a clinical trial of 59 patients wit... | 0.784484 | 0.504089 |
from __future__ import print_function
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME> and <NAME>
# --------------------------------------------------------
# --------------------------... | lib/model/rpn_v1/generate_anchors.py | from __future__ import print_function
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME> and <NAME>
# --------------------------------------------------------
# --------------------------... | 0.809314 | 0.391435 |
import matplotlib
matplotlib.use('Agg')
import pandas as pd
import seaborn as sns
import sys
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from keyname import keyname as kn
from fileshash import fileshash as fsh
import math
dataframe_filename = sys.argv[2]
df_key = ... | script/LowDimensionalityStat.py | import matplotlib
matplotlib.use('Agg')
import pandas as pd
import seaborn as sns
import sys
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from keyname import keyname as kn
from fileshash import fileshash as fsh
import math
dataframe_filename = sys.argv[2]
df_key = ... | 0.277767 | 0.198472 |
import mmap
import time
import struct
import ctypes
import io
import _thread
import weakref
from time import sleep
from ctypes import wintypes
INVALID = 0
# https://stackoverflow.com/questions/31495461/mmap-cant-attach-to-existing-region-without-knowing-its-size-windows
kernel32 = ctypes.WinDLL('kernel32', use_last_... | speedysvc/client_server/shared_memory/Win32SHM.py | import mmap
import time
import struct
import ctypes
import io
import _thread
import weakref
from time import sleep
from ctypes import wintypes
INVALID = 0
# https://stackoverflow.com/questions/31495461/mmap-cant-attach-to-existing-region-without-knowing-its-size-windows
kernel32 = ctypes.WinDLL('kernel32', use_last_... | 0.255622 | 0.109658 |
from typing import Optional, List
from rdflib import Graph, URIRef, Literal
from rdflib.namespace import RDF, RDFS, OWL, DCTERMS, XSD
from client.model._TERN import TERN
from client.model.klass import Klass
from client.model.agent import Agent
from client.model.concept import Concept
import re
class RDFDataset(Klas... | client/model/rdf_dataset.py | from typing import Optional, List
from rdflib import Graph, URIRef, Literal
from rdflib.namespace import RDF, RDFS, OWL, DCTERMS, XSD
from client.model._TERN import TERN
from client.model.klass import Klass
from client.model.agent import Agent
from client.model.concept import Concept
import re
class RDFDataset(Klas... | 0.846863 | 0.267393 |
reftable = """
CREATE TABLE `by0001` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`fld1` char(10) DEFAULT NULL,
`fld2` smallint(6) DEFAULT NULL,
`fld4` mediumint(9) DEFAULT NULL,
`fld5` int(11) DEFAULT NULL,
`fld6` bigint(20) DEFAULT NULL,
`fld7` float DEFAULT NULL,
`fld8` double DEFAULT NULL,
`fl... | tests/pretest.py | reftable = """
CREATE TABLE `by0001` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`fld1` char(10) DEFAULT NULL,
`fld2` smallint(6) DEFAULT NULL,
`fld4` mediumint(9) DEFAULT NULL,
`fld5` int(11) DEFAULT NULL,
`fld6` bigint(20) DEFAULT NULL,
`fld7` float DEFAULT NULL,
`fld8` double DEFAULT NULL,
`fl... | 0.481698 | 0.101056 |
def padded_binary(num, length=36):
binary_value = bin(num).removeprefix("0b")
return "0" * (length - len(binary_value)) + binary_value
class Memory:
def __init__(self):
self._mask = "X" * 36
self._data = dict()
def __setitem__(self, key, value):
binary_value = padded_binary(va... | 2020/day14/day14.py | def padded_binary(num, length=36):
binary_value = bin(num).removeprefix("0b")
return "0" * (length - len(binary_value)) + binary_value
class Memory:
def __init__(self):
self._mask = "X" * 36
self._data = dict()
def __setitem__(self, key, value):
binary_value = padded_binary(va... | 0.582491 | 0.369998 |
import numpy as np
import pytest
from psyneulink.core.components.functions.transferfunctions import Linear
from psyneulink.core.components.mechanisms.processing.transfermechanism import TransferMechanism
from psyneulink.core.components.process import Process
from psyneulink.core.components.system import System
from ps... | tests/mechanisms/test_lca.py | import numpy as np
import pytest
from psyneulink.core.components.functions.transferfunctions import Linear
from psyneulink.core.components.mechanisms.processing.transfermechanism import TransferMechanism
from psyneulink.core.components.process import Process
from psyneulink.core.components.system import System
from ps... | 0.413359 | 0.393618 |
"""Analyze the simulation results."""
import os
import shutil
import numpy as np
import pandas as pd
from wfa_cardinality_estimation_evaluation_framework.common import plotting
from wfa_cardinality_estimation_evaluation_framework.evaluations import evaluator
from wfa_cardinality_estimation_evaluation_framework.simul... | evaluations/analyzer.py |
"""Analyze the simulation results."""
import os
import shutil
import numpy as np
import pandas as pd
from wfa_cardinality_estimation_evaluation_framework.common import plotting
from wfa_cardinality_estimation_evaluation_framework.evaluations import evaluator
from wfa_cardinality_estimation_evaluation_framework.simul... | 0.908958 | 0.430626 |
import amqpstorm
from amqpstorm import Message
class FibonacciRpcClient(object):
def __init__(self, host, username, password):
"""
:param host: RabbitMQ Server e.g. localhost
:param username: RabbitMQ Username e.g. guest
:param password: <PASSWORD>MQ Password e.g. <PASSWORD>
... | examples/simple_rpc_client.py | import amqpstorm
from amqpstorm import Message
class FibonacciRpcClient(object):
def __init__(self, host, username, password):
"""
:param host: RabbitMQ Server e.g. localhost
:param username: RabbitMQ Username e.g. guest
:param password: <PASSWORD>MQ Password e.g. <PASSWORD>
... | 0.465145 | 0.061312 |
from rest_framework.test import APITestCase, APIClient
from api.models import Sample, Disease, Mutation, Gene
class SampleTests(APITestCase):
sample_keys = ['sample_id',
'disease',
'mutations',
'gender',
'age_diagnosed']
def setUp(se... | api/test/test_sample.py | from rest_framework.test import APITestCase, APIClient
from api.models import Sample, Disease, Mutation, Gene
class SampleTests(APITestCase):
sample_keys = ['sample_id',
'disease',
'mutations',
'gender',
'age_diagnosed']
def setUp(se... | 0.58261 | 0.281511 |
import random
import numpy as np
import torch
import torch.nn.functional as F
from base_batch_gen import Base_batch_generator
from helper_functions import encode_content
class CNNFisherBatchGen(Base_batch_generator):
def __init__(self, num_rows, num_classes, action_to_id):
super(CNNFisherBatchGen, self)... | utils/cnn_fisher_batch_gen.py | import random
import numpy as np
import torch
import torch.nn.functional as F
from base_batch_gen import Base_batch_generator
from helper_functions import encode_content
class CNNFisherBatchGen(Base_batch_generator):
def __init__(self, num_rows, num_classes, action_to_id):
super(CNNFisherBatchGen, self)... | 0.802556 | 0.262257 |
from urlextract import URLExtract
from Nemesis.lib.Color import Color
# General
# Matches url but not direct path
#url_regex = "((http|https)://)[a-zA-Z0-9\./?:@-_=]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*"
#url_regex_without_netloc = "((http|https)://)?[a-zA-Z0-9\./?:@-_=]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/... | src/Nemesis/lib/Globals.py | from urlextract import URLExtract
from Nemesis.lib.Color import Color
# General
# Matches url but not direct path
#url_regex = "((http|https)://)[a-zA-Z0-9\./?:@-_=]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*"
#url_regex_without_netloc = "((http|https)://)?[a-zA-Z0-9\./?:@-_=]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/... | 0.259638 | 0.111434 |
import bcrypt
import pymysql.cursors
import json
import os
import sys
from flask import Flask, request, session, redirect, render_template
from flask_api import status
from werkzeug.serving import run_simple
from datetime import timezone, datetime
def utc_to_local(utc_dt):
return utc_dt.replace(tzinfo=timezone.ut... | main.py | import bcrypt
import pymysql.cursors
import json
import os
import sys
from flask import Flask, request, session, redirect, render_template
from flask_api import status
from werkzeug.serving import run_simple
from datetime import timezone, datetime
def utc_to_local(utc_dt):
return utc_dt.replace(tzinfo=timezone.ut... | 0.214691 | 0.081666 |
import ast
from collections import ChainMap
from dataclasses import dataclass, field
from functools import singledispatch
from typing import ChainMap as CM
from typing import Iterator, List, Optional, Tuple, Type
from breakfast.position import Position
from breakfast.source import Source
from tests import make_source... | tests/test_attempt_6.py | import ast
from collections import ChainMap
from dataclasses import dataclass, field
from functools import singledispatch
from typing import ChainMap as CM
from typing import Iterator, List, Optional, Tuple, Type
from breakfast.position import Position
from breakfast.source import Source
from tests import make_source... | 0.840897 | 0.196363 |
from django.contrib import admin
from apps.website.models.article import Article
from apps.website.models.inbox import Inbox
from apps.website.models.comments import Comments
from apps.website.models.authors import Authors
from apps.website.models.settings import WebsiteSettings
from django.utils import timezone
from d... | apps/website/admin.py | from django.contrib import admin
from apps.website.models.article import Article
from apps.website.models.inbox import Inbox
from apps.website.models.comments import Comments
from apps.website.models.authors import Authors
from apps.website.models.settings import WebsiteSettings
from django.utils import timezone
from d... | 0.5564 | 0.08218 |
import unittest
import app.gpio as gpio
class TestMemoryUtils(unittest.TestCase):
def test_constructor_rejects_invalid_pin_numbers(self):
self.assertRaises(Exception, gpio.GpioInfo, -1)
self.assertRaises(Exception, gpio.GpioInfo, 54)
def test_constructor_calculates_correct_pin_bit_offset(se... | tests/test_gpio_info.py | import unittest
import app.gpio as gpio
class TestMemoryUtils(unittest.TestCase):
def test_constructor_rejects_invalid_pin_numbers(self):
self.assertRaises(Exception, gpio.GpioInfo, -1)
self.assertRaises(Exception, gpio.GpioInfo, 54)
def test_constructor_calculates_correct_pin_bit_offset(se... | 0.597843 | 0.730819 |
from abc import ABCMeta, abstractmethod
from hackernewslib.mixins import KidsMixin, UserMixin, ContentMixin
class Item(object, metaclass=ABCMeta):
def __init__(self, client, id, data):
self.client = client
self.id = id
self.data = data
self.type = data.get("type")
@classmetho... | hackernewslib/models.py | from abc import ABCMeta, abstractmethod
from hackernewslib.mixins import KidsMixin, UserMixin, ContentMixin
class Item(object, metaclass=ABCMeta):
def __init__(self, client, id, data):
self.client = client
self.id = id
self.data = data
self.type = data.get("type")
@classmetho... | 0.701815 | 0.060169 |
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp import Sid
from etl.parsers.etw.core import Etw, declare, guid
@declare(guid=guid("28cb46c7-4003-4e50-8bd9-442086762d12"), ... | etl/parsers/etw/Microsoft_AppV_Client_StreamingUX.py | from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp import Sid
from etl.parsers.etw.core import Etw, declare, guid
@declare(guid=guid("28cb46c7-4003-4e50-8bd9-442086762d12"), ... | 0.326701 | 0.069447 |
import json
from tornado import escape
from tornado.gen import coroutine, Return
from tornado.web import RequestHandler
from torndsession.sessionhandler import SessionBaseHandler
from urllib import quote, urlencode
import constant
from core.utils import send_request
from wechat import get_access_token
class BaseHand... | handler/mobile.py | import json
from tornado import escape
from tornado.gen import coroutine, Return
from tornado.web import RequestHandler
from torndsession.sessionhandler import SessionBaseHandler
from urllib import quote, urlencode
import constant
from core.utils import send_request
from wechat import get_access_token
class BaseHand... | 0.287868 | 0.046357 |
from collections import defaultdict
import sys
from nordlys.logic.entity.entity import Entity
from nordlys.logic.query.mention import Mention
from nordlys.logic.query.query import Query
class Cmns(object):
def __init__(self, query, entity, cmns_th=0.1):
self.__query = query
self.__entity = entit... | nordlys/logic/el/cmns.py | from collections import defaultdict
import sys
from nordlys.logic.entity.entity import Entity
from nordlys.logic.query.mention import Mention
from nordlys.logic.query.query import Query
class Cmns(object):
def __init__(self, query, entity, cmns_th=0.1):
self.__query = query
self.__entity = entit... | 0.621771 | 0.205874 |
import torch
import torch.nn.functional
from torch import nn
from typing import List, Dict, Tuple
from ..utils import build_stack_conv_layers, random_init_weights
from ..builder import HEADS, build_loss
from ...core import PointGenerator, generate_gt, assign_and_sample
from ...utils import multi_apply
@HEADS.regist... | siam_tracker/models/heads/fc_head.py |
import torch
import torch.nn.functional
from torch import nn
from typing import List, Dict, Tuple
from ..utils import build_stack_conv_layers, random_init_weights
from ..builder import HEADS, build_loss
from ...core import PointGenerator, generate_gt, assign_and_sample
from ...utils import multi_apply
@HEADS.regist... | 0.953697 | 0.58602 |
import pandas as pd
from woodwork.exceptions import TypeConversionError
from woodwork.logical_types import Datetime, LatLong, Ordinal
from woodwork.type_sys.utils import _get_ltype_class
from woodwork.utils import (
_get_column_logical_type,
_reformat_to_latlong,
import_or_none
)
dd = import_or_none('dask... | woodwork/accessor_utils.py | import pandas as pd
from woodwork.exceptions import TypeConversionError
from woodwork.logical_types import Datetime, LatLong, Ordinal
from woodwork.type_sys.utils import _get_ltype_class
from woodwork.utils import (
_get_column_logical_type,
_reformat_to_latlong,
import_or_none
)
dd = import_or_none('dask... | 0.795301 | 0.425247 |
import model_wrapper as mw
import torch
from torchvision import datasets, transforms, models
from torch import nn, optim
import torch.nn.functional as F
from collections import OrderedDict
from torch.optim import lr_scheduler
from PIL import Image
import json
import pprint
def train(mw,epochs,gpu,learning_rate):
... | img_classifier_utils.py | import model_wrapper as mw
import torch
from torchvision import datasets, transforms, models
from torch import nn, optim
import torch.nn.functional as F
from collections import OrderedDict
from torch.optim import lr_scheduler
from PIL import Image
import json
import pprint
def train(mw,epochs,gpu,learning_rate):
... | 0.880399 | 0.538741 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .multibox_layer import MultiBoxLayer
class SSD(nn.Module):
"""SSD300 model."""
def __init__(self, num_classes=21):
super(SSD, self).__init__()
self.base = VGG16()
# output feature map size: 38
self.norm4 ... | src/ssd.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .multibox_layer import MultiBoxLayer
class SSD(nn.Module):
"""SSD300 model."""
def __init__(self, num_classes=21):
super(SSD, self).__init__()
self.base = VGG16()
# output feature map size: 38
self.norm4 ... | 0.950307 | 0.550003 |
import cx_Freeze, os.path
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')
executables = [
cx_Freeze.Executable(
scri... | setup.py | import cx_Freeze, os.path
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')
executables = [
cx_Freeze.Executable(
scri... | 0.293911 | 0.053775 |
from pulp import *
# Creates a list of the Ingredients
import numpy
import fileinput
inp = fileinput.input()
num_cases = int(inp.next());
for case in range(num_cases):
arboles, prediccio, lenadores = map(int,inp.next()[:-1].split(" ")[:3])
Treball_maxim = []
Work_required = []
for jj in range(lena... | problem16/snippet.py | from pulp import *
# Creates a list of the Ingredients
import numpy
import fileinput
inp = fileinput.input()
num_cases = int(inp.next());
for case in range(num_cases):
arboles, prediccio, lenadores = map(int,inp.next()[:-1].split(" ")[:3])
Treball_maxim = []
Work_required = []
for jj in range(lena... | 0.23014 | 0.241791 |
import numpy as np
def astype(obj, type):
try:
return obj.astype(type)
except AttributeError:
return type(obj)
def _n_chunks(n, seq):
step = len(seq) // n
return [seq[i:i+step] for i in range(0, step*n, step)]
def _hex_to_uint8(value):
return np.array(list(map(lambda s: int(s, ... | glance/colors/colorconversions.py | import numpy as np
def astype(obj, type):
try:
return obj.astype(type)
except AttributeError:
return type(obj)
def _n_chunks(n, seq):
step = len(seq) // n
return [seq[i:i+step] for i in range(0, step*n, step)]
def _hex_to_uint8(value):
return np.array(list(map(lambda s: int(s, ... | 0.542136 | 0.340403 |
from .base_node import BaseNode
class AchUsNode(BaseNode):
"""Represents an ACH-US node."""
@classmethod
def unverified_from_response(cls, user, response):
"""Create an AchUsNode instance for an ACH-US node that needs MFA.
The API record is not actually created until the MFA has been cor... | synapse_pay_rest/models/nodes/ach_us_node.py | from .base_node import BaseNode
class AchUsNode(BaseNode):
"""Represents an ACH-US node."""
@classmethod
def unverified_from_response(cls, user, response):
"""Create an AchUsNode instance for an ACH-US node that needs MFA.
The API record is not actually created until the MFA has been cor... | 0.897128 | 0.28549 |
import json
from botocore.vendored import requests
from connector_response import ConnectorResponse as ConnectorResponse
import traceback
import base64
default_jira_server = "https://issues.apache.org/jira"
jira_get_project_api = "/rest/api/2/project/"
default_authorization = "<configure-your-base64-endcoded-authoriz... | connectors/GetJiraProjectInfo.py | import json
from botocore.vendored import requests
from connector_response import ConnectorResponse as ConnectorResponse
import traceback
import base64
default_jira_server = "https://issues.apache.org/jira"
jira_get_project_api = "/rest/api/2/project/"
default_authorization = "<configure-your-base64-endcoded-authoriz... | 0.325949 | 0.101411 |
import qumulo.lib.opts
import qumulo.lib.util as util
import qumulo.rest.fs as fs
import qumulo.rest.ftp as ftp
class FtpGetStatus(qumulo.lib.opts.Subcommand):
NAME = "ftp_get_status"
DESCRIPTION = "Get FTP server settings and status"
@staticmethod
def main(conninfo, credentials, _args):
prin... | qumulo/commands/ftp.py |
import qumulo.lib.opts
import qumulo.lib.util as util
import qumulo.rest.fs as fs
import qumulo.rest.ftp as ftp
class FtpGetStatus(qumulo.lib.opts.Subcommand):
NAME = "ftp_get_status"
DESCRIPTION = "Get FTP server settings and status"
@staticmethod
def main(conninfo, credentials, _args):
prin... | 0.354433 | 0.097605 |
from __future__ import print_function
import torch
import numpy as np
from PIL import Image
import os
import torch.nn.functional as F
synthia_txtpath='/home/dut-ai/Documents/temp/synthia_encoding.txt'
cat2color_synthia={}
with open(synthia_txtpath,'r') as file:
for line in file.readlines():
templist = line.... | util/util.py | from __future__ import print_function
import torch
import numpy as np
from PIL import Image
import os
import torch.nn.functional as F
synthia_txtpath='/home/dut-ai/Documents/temp/synthia_encoding.txt'
cat2color_synthia={}
with open(synthia_txtpath,'r') as file:
for line in file.readlines():
templist = line.... | 0.314051 | 0.274807 |
import base64
import io
import json
import posixpath
from datetime import timedelta
from typing import Any, BinaryIO, Dict, Optional
from google.cloud import storage # type: ignore
from google.oauth2 import service_account # type: ignore
from giftless.storage import ExternalStorage, StreamingStorage
from .exc impo... | giftless/storage/google_cloud.py | import base64
import io
import json
import posixpath
from datetime import timedelta
from typing import Any, BinaryIO, Dict, Optional
from google.cloud import storage # type: ignore
from google.oauth2 import service_account # type: ignore
from giftless.storage import ExternalStorage, StreamingStorage
from .exc impo... | 0.736306 | 0.129018 |
import asm.cms.cms
import asm.cmsui.base
import asm.cmsui.interfaces
import grok
import megrok.pagelet
import zope.interface
grok.context(asm.cms.cms.CMS)
class SearchAndReplace(megrok.pagelet.Pagelet):
"""Present the user a form to allow entering search and replace terms."""
grok.layer(asm.cmsui.interfaces... | src/asm/cmsui/replace.py | import asm.cms.cms
import asm.cmsui.base
import asm.cmsui.interfaces
import grok
import megrok.pagelet
import zope.interface
grok.context(asm.cms.cms.CMS)
class SearchAndReplace(megrok.pagelet.Pagelet):
"""Present the user a form to allow entering search and replace terms."""
grok.layer(asm.cmsui.interfaces... | 0.444083 | 0.185467 |
import math
import numpy as np
from functools import cmp_to_key as ctk
from PIL import Image
class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
class EndPoint(Point):
def __init__(self, x: float, y: float, begins_segment: bool = None, segment=None, angle: float = None... | utils/visibility_polygon.py | import math
import numpy as np
from functools import cmp_to_key as ctk
from PIL import Image
class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
class EndPoint(Point):
def __init__(self, x: float, y: float, begins_segment: bool = None, segment=None, angle: float = None... | 0.715325 | 0.543045 |