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 numpy as np import scipy.signal as signal import matplotlib.pyplot as plt def create_bassman(low, middle, high): R1 = 250e3 R2 = 1e6 R3 = 25e3 R4 = 45e3 C1 = 250e-12 C2 = 20e-9 C3 = 20e-9 b = (0, (high*C1*R1 + middle*C3*R3 + low*(C1*R2 + C2*R2) + (C1*R3 + C2*R3)), (high*(C1*C2*R1*R4 + C1*C3*R1...
Examples/EQ/compare_tonestack.py
import numpy as np import scipy.signal as signal import matplotlib.pyplot as plt def create_bassman(low, middle, high): R1 = 250e3 R2 = 1e6 R3 = 25e3 R4 = 45e3 C1 = 250e-12 C2 = 20e-9 C3 = 20e-9 b = (0, (high*C1*R1 + middle*C3*R3 + low*(C1*R2 + C2*R2) + (C1*R3 + C2*R3)), (high*(C1*C2*R1*R4 + C1*C3*R1...
0.466603
0.61633
import pytest from nornir.core.task import AggregatedResult from nornir_napalm.plugins import tasks from nuts.base_tests.napalm_get_vlans import CONTEXT from tests.utils import create_multi_result, SelfTestData nornir_raw_result_s1 = { "vlans": { "1": { "name": "default", "interf...
tests/base_tests/test_napalm_get_vlans.py
import pytest from nornir.core.task import AggregatedResult from nornir_napalm.plugins import tasks from nuts.base_tests.napalm_get_vlans import CONTEXT from tests.utils import create_multi_result, SelfTestData nornir_raw_result_s1 = { "vlans": { "1": { "name": "default", "interf...
0.516108
0.394493
import pytest from dlapp.collection import Element from dlapp.collection import LookupCls from dlapp.collection import List from dlapp.collection import ListIndexError @pytest.fixture def dict_data(): obj = { "widget": { "debug": "on", "window": { "title": "ABC Wid...
tests/unit/test_collection.py
import pytest from dlapp.collection import Element from dlapp.collection import LookupCls from dlapp.collection import List from dlapp.collection import ListIndexError @pytest.fixture def dict_data(): obj = { "widget": { "debug": "on", "window": { "title": "ABC Wid...
0.572723
0.446977
import numpy as np from steganography.utilities.rand import get_random_sequence import logging SIZE_LENGTH = 32 def hide_data_in_LSB(pixels, data, seed): """ Hide data in carry and return a numpy array. :param pixels: an np array image to hide data in :param data: an array of bits to hide :param ...
steganography/strategies/lsb.py
import numpy as np from steganography.utilities.rand import get_random_sequence import logging SIZE_LENGTH = 32 def hide_data_in_LSB(pixels, data, seed): """ Hide data in carry and return a numpy array. :param pixels: an np array image to hide data in :param data: an array of bits to hide :param ...
0.417628
0.720381
# Import PyIOmica import pyiomica as pio # Import Extended DataFrame from PyIOmica from pyiomica.extendedDataFrame import DataFrame # Create a simple data for testing and demonstration df_data = DataFrame(data=pio.np.array([[0.5,2,3], [0,2,6], ...
docs/examples/examplesExtendedDataFrame.py
# Import PyIOmica import pyiomica as pio # Import Extended DataFrame from PyIOmica from pyiomica.extendedDataFrame import DataFrame # Create a simple data for testing and demonstration df_data = DataFrame(data=pio.np.array([[0.5,2,3], [0,2,6], ...
0.423339
0.54353
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint from .activation import MyReLU from .bone_utils import get_canonical_pose from .stylegan import EqualLinear, EqualConv1d, NormalizedConv1d from .model_utils import in_cube from .utils_3d import SE3 cla...
NARF/models/nerf_model.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint from .activation import MyReLU from .bone_utils import get_canonical_pose from .stylegan import EqualLinear, EqualConv1d, NormalizedConv1d from .model_utils import in_cube from .utils_3d import SE3 cla...
0.901405
0.346597
import re from collections.abc import Mapping from functools import reduce from copy import deepcopy from arpoc.plugins._lib import Obligation, Optional, deep_dict_update from arpoc.ac.common import Effects from typing import Dict import logging """ Obligation Log Module. The classes here will either - log every...
arpoc/plugins/obl_loggers.py
import re from collections.abc import Mapping from functools import reduce from copy import deepcopy from arpoc.plugins._lib import Obligation, Optional, deep_dict_update from arpoc.ac.common import Effects from typing import Dict import logging """ Obligation Log Module. The classes here will either - log every...
0.853303
0.169922
import os import numpy as np import pandas as pd from hyperactive import Hyperactive from hyperactive.dashboards import ProgressBoard from hyperactive.dashboards.progress_board.streamlit_backend import StreamlitBackend from hyperactive.dashboards.progress_board.progress_io import ProgressIO def test_progress_io_0(): ...
tests/test_progress_board.py
import os import numpy as np import pandas as pd from hyperactive import Hyperactive from hyperactive.dashboards import ProgressBoard from hyperactive.dashboards.progress_board.streamlit_backend import StreamlitBackend from hyperactive.dashboards.progress_board.progress_io import ProgressIO def test_progress_io_0(): ...
0.514644
0.360264
from __future__ import unicode_literals from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import get_user_model from django import forms from django.utils.translation import ugettext_lazy as _ from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Fi...
src/accounts/forms.py
from __future__ import unicode_literals from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import get_user_model from django import forms from django.utils.translation import ugettext_lazy as _ from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Fi...
0.621426
0.087564
from functools import partial import requests from waiter import terminal, http_util from waiter.action import ping_token_on_cluster, process_kill_request from waiter.querying import get_target_cluster_from_token, get_token from waiter.token_post import post_failed_message, process_post_result from waiter.util import...
cli/waiter/subcommands/maintenance.py
from functools import partial import requests from waiter import terminal, http_util from waiter.action import ping_token_on_cluster, process_kill_request from waiter.querying import get_target_cluster_from_token, get_token from waiter.token_post import post_failed_message, process_post_result from waiter.util import...
0.47658
0.071786
import pandas as pd import numpy as np import cartopy.crs as ccrs import matplotlib.pyplot as plt import os, sys import matplotlib.ticker as mticker pd.set_option('display.max_rows', 5000) pd.set_option('display.max_columns', 5000) import xarray as xr def get_k_nearest_values_from_vector(arr, k): idx = np....
scripts/regridding/IDW_over_xarray.py
import pandas as pd import numpy as np import cartopy.crs as ccrs import matplotlib.pyplot as plt import os, sys import matplotlib.ticker as mticker pd.set_option('display.max_rows', 5000) pd.set_option('display.max_columns', 5000) import xarray as xr def get_k_nearest_values_from_vector(arr, k): idx = np....
0.333503
0.605974
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django_countries.fields import workshops.fields def update_contenttypes(apps, schema_editor): ContentType = apps.get_model('contenttypes', 'ContentType') # update application for all non-version...
amy/extrequests/migrations/0001_initial.py
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django_countries.fields import workshops.fields def update_contenttypes(apps, schema_editor): ContentType = apps.get_model('contenttypes', 'ContentType') # update application for all non-version...
0.469034
0.180287
from datetime import date from functools import reduce import logging from multiprocessing import cpu_count from os import chdir, getcwd from os.path import relpath from shutil import copy, copytree, rmtree from pathlib import Path from platform import system import sqlite3 from string import Template from subprocess i...
scripts/manager.py
from datetime import date from functools import reduce import logging from multiprocessing import cpu_count from os import chdir, getcwd from os.path import relpath from shutil import copy, copytree, rmtree from pathlib import Path from platform import system import sqlite3 from string import Template from subprocess i...
0.694199
0.253728
from kivy.uix.textinput import TextInput from kivy.properties import NumericProperty import math class IntEntry(TextInput): value = NumericProperty(0.0) def __init__(self, low=-math.inf, high=math.inf, **kwds): if low >= 10: # Because otherwise we couldn't ever type the first digit ...
timedata/ui/int_entry.py
from kivy.uix.textinput import TextInput from kivy.properties import NumericProperty import math class IntEntry(TextInput): value = NumericProperty(0.0) def __init__(self, low=-math.inf, high=math.inf, **kwds): if low >= 10: # Because otherwise we couldn't ever type the first digit ...
0.320396
0.326781
from confiture import Confiture from .i_command import ICommand from src.shell.chart.arity import ArityChart from src.shell.chart.type import TypeChart from src.shell.chart.couple import CoupleChart from src.shell.chart.alloc import AllocChart class ChartCmd(ICommand): """ usage: chart <analysis> <parame...
src/shell/command/chart.py
from confiture import Confiture from .i_command import ICommand from src.shell.chart.arity import ArityChart from src.shell.chart.type import TypeChart from src.shell.chart.couple import CoupleChart from src.shell.chart.alloc import AllocChart class ChartCmd(ICommand): """ usage: chart <analysis> <parame...
0.427636
0.273174
from infrastructor.Cryptography.CryptoService import CryptoService from infrastructor.data.ConnectionStrategy import ConnectionStrategy from infrastructor.data.DatabaseManager import DatabaseManager from infrastructor.data.OracleConnector import OracleDbConnector class OracleConnectionStrategy(ConnectionStrategy): ...
domain/imageprocessing/strategies/OracleConnectionStrategy.py
from infrastructor.Cryptography.CryptoService import CryptoService from infrastructor.data.ConnectionStrategy import ConnectionStrategy from infrastructor.data.DatabaseManager import DatabaseManager from infrastructor.data.OracleConnector import OracleDbConnector class OracleConnectionStrategy(ConnectionStrategy): ...
0.334046
0.074265
class TimeBlock: DAYS = ['M', 'T', 'W', 'R', 'F'] ''' returns a list of time blocks, repeating the start/end times for the given days ex: time_str = 'MWF:1000-1050' ''' @classmethod def get_time_blocks(cls, time_str): blocks = [] if ':' in time_str: colon_index = time_str.index(':') days = time_str[...
Planit/API/TimeBlock.py
class TimeBlock: DAYS = ['M', 'T', 'W', 'R', 'F'] ''' returns a list of time blocks, repeating the start/end times for the given days ex: time_str = 'MWF:1000-1050' ''' @classmethod def get_time_blocks(cls, time_str): blocks = [] if ':' in time_str: colon_index = time_str.index(':') days = time_str[...
0.458349
0.402099
from collections import namedtuple from datetime import datetime, timedelta from sqlalchemy import and_ import pandas as pd from app import db # ENTSO-E mappings RENEWABLES = ["wind", "hydro", "solar", "biomass"] NON_RENEWABLES = ["coal", "fossil", "natgas", "oil", "other", "refuse"] ModelParameters = namedtuple("M...
app/model.py
from collections import namedtuple from datetime import datetime, timedelta from sqlalchemy import and_ import pandas as pd from app import db # ENTSO-E mappings RENEWABLES = ["wind", "hydro", "solar", "biomass"] NON_RENEWABLES = ["coal", "fossil", "natgas", "oil", "other", "refuse"] ModelParameters = namedtuple("M...
0.918667
0.294494
from typing import Any, Dict, List, Tuple from overrides import overrides import numpy as np import torch # mostly for type annotations from miso.metrics.metric import Metric from miso.metrics.srl import compute_srl_f1 class GVDBScores(Metric): def __init__(self, vocab) -> None: self._scorer = Scorer() sel...
miso/metrics/gvdb_scores.py
from typing import Any, Dict, List, Tuple from overrides import overrides import numpy as np import torch # mostly for type annotations from miso.metrics.metric import Metric from miso.metrics.srl import compute_srl_f1 class GVDBScores(Metric): def __init__(self, vocab) -> None: self._scorer = Scorer() sel...
0.688154
0.176441
import gym, gym_envs from stable_baselines.common.vec_env import DummyVecEnv, VecNormalize from stable_baselines.common.env_checker import check_env import matplotlib.pyplot as plt import numpy as np import pandas as pd import os import time import argparse def main(): parser = argparse.ArgumentParser() par...
rl-baselines-zoo/7_run_random_policy.py
import gym, gym_envs from stable_baselines.common.vec_env import DummyVecEnv, VecNormalize from stable_baselines.common.env_checker import check_env import matplotlib.pyplot as plt import numpy as np import pandas as pd import os import time import argparse def main(): parser = argparse.ArgumentParser() par...
0.225672
0.305905
import slapd import pytest def test_nominal_case(): server = slapd.Slapd() server.start() server.restart() server.stop() def test_context_manager(): with slapd.Slapd() as server: assert server._proc is not None assert server._proc is None server.stop() def test_context_manager_...
tests/test_slapdobject.py
import slapd import pytest def test_nominal_case(): server = slapd.Slapd() server.start() server.restart() server.stop() def test_context_manager(): with slapd.Slapd() as server: assert server._proc is not None assert server._proc is None server.stop() def test_context_manager_...
0.369201
0.307423
import os import pytest from chimera_app.compat_tools import ExternalCompatTool @pytest.fixture def fake_data(fs, monkeypatch): files_path = os.path.join(os.path.dirname(__file__), 'files') fs.create_dir(os.path.expanduser('~/.cache')) fs.create_dir(os.path.expanduser('~/.local/share/chime...
tests/test_compat_tools.py
import os import pytest from chimera_app.compat_tools import ExternalCompatTool @pytest.fixture def fake_data(fs, monkeypatch): files_path = os.path.join(os.path.dirname(__file__), 'files') fs.create_dir(os.path.expanduser('~/.cache')) fs.create_dir(os.path.expanduser('~/.local/share/chime...
0.33112
0.112893
import numpy as np import pandas as pd from sklearn import metrics from sklearn import model_selection from sklearn.preprocessing import MinMaxScaler,StandardScaler from sklearn.neural_network import MLPClassifier from sklearn.linear_model import LogisticRegression from sklearn import svm,tree from sklearn.ens...
model/eval/evaluation.py
import numpy as np import pandas as pd from sklearn import metrics from sklearn import model_selection from sklearn.preprocessing import MinMaxScaler,StandardScaler from sklearn.neural_network import MLPClassifier from sklearn.linear_model import LogisticRegression from sklearn import svm,tree from sklearn.ens...
0.414188
0.250792
import time from data_structures import UnionFind def load_data(filename, dtype='edges'): if dtype == 'edges': f = open(filename) n = int(f.readline()) nodes = [i+1 for i in range(n)] data = f.readlines() f.close() left, right, length = [], [], [] for line in...
c3-greedy-dp/k_clustering.py
import time from data_structures import UnionFind def load_data(filename, dtype='edges'): if dtype == 'edges': f = open(filename) n = int(f.readline()) nodes = [i+1 for i in range(n)] data = f.readlines() f.close() left, right, length = [], [], [] for line in...
0.441191
0.314656
from asyncio import Task, get_event_loop, sleep, CancelledError from dataclasses import dataclass from enum import Enum from logging import getLogger from typing import Callable, Awaitable, Optional, Dict, List from pydantic import BaseModel from binp.events import Emitter class Status(str, Enum): """ Servi...
binp/service.py
from asyncio import Task, get_event_loop, sleep, CancelledError from dataclasses import dataclass from enum import Enum from logging import getLogger from typing import Callable, Awaitable, Optional, Dict, List from pydantic import BaseModel from binp.events import Emitter class Status(str, Enum): """ Servi...
0.775647
0.192388
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time import sys import math import numpy as np import argparse import functools import paddle import paddle.fluid as fluid from image_classification import reader from image_classification im...
PaddleCV/image_classification/eval.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time import sys import math import numpy as np import argparse import functools import paddle import paddle.fluid as fluid from image_classification import reader from image_classification im...
0.416678
0.169853
import os import tflearn OUTPUT_FOLDER = 'output/buff_bobo' # Residual blocks # 32 layers: n=5, 56 layers: n=9, 110 layers: n=18 N = 5 class ClassificationModel(object): """ A model for object classification. """ def __init__(self, image_size, weights): self.network = self._build_networ...
architectures/buff_bobo/classifier.py
import os import tflearn OUTPUT_FOLDER = 'output/buff_bobo' # Residual blocks # 32 layers: n=5, 56 layers: n=9, 110 layers: n=18 N = 5 class ClassificationModel(object): """ A model for object classification. """ def __init__(self, image_size, weights): self.network = self._build_networ...
0.755817
0.307696
from django.core.cache import caches def get_slug(node): """ Return short URL-able sting to use as identifier for current Node or File. """ return node.title.replace(' ', '_') def get_path_for_node(node): """ Returns the requestpath for accessing this node, e.g. 'topic_1/subtopic_2/conte...
fakolibri/statiksite/helpers.py
from django.core.cache import caches def get_slug(node): """ Return short URL-able sting to use as identifier for current Node or File. """ return node.title.replace(' ', '_') def get_path_for_node(node): """ Returns the requestpath for accessing this node, e.g. 'topic_1/subtopic_2/conte...
0.513181
0.18396
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score sonar_data = pd.read_csv("C:/Users/Sakthi/Desktop/Copy of sonar data.csv", header=None) sonar_dat...
sonar.py
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score sonar_data = pd.read_csv("C:/Users/Sakthi/Desktop/Copy of sonar data.csv", header=None) sonar_dat...
0.235372
0.316937
from bs4 import BeautifulSoup from src.model.models import Consulta, TermoConsulta, EntradaRanking from src.service.StopwordService import StopwordsService from src.service.IndexadorService import IndexadorService from src.service.TermoDocumentoService import TermoDocumentoService from src.service.IndiceInvertidoServi...
src/service/ProcessadorConsultaService.py
from bs4 import BeautifulSoup from src.model.models import Consulta, TermoConsulta, EntradaRanking from src.service.StopwordService import StopwordsService from src.service.IndexadorService import IndexadorService from src.service.TermoDocumentoService import TermoDocumentoService from src.service.IndiceInvertidoServi...
0.28607
0.121686
# jwc from: ~/01-Jwc/03t-StsPilot-MarkOrion/STS-PiLot """ Created on Wed Mar 15 11:56:25 2017 @author: <NAME> """ import explorerhat as xhat explorerhat = True # Inputs: Digital def input_one_read(): digital = xhat.input.one.read() return digital def input_two_read(): digital = xhat.input.two.read(...
io_Driver_File.py
# jwc from: ~/01-Jwc/03t-StsPilot-MarkOrion/STS-PiLot """ Created on Wed Mar 15 11:56:25 2017 @author: <NAME> """ import explorerhat as xhat explorerhat = True # Inputs: Digital def input_one_read(): digital = xhat.input.one.read() return digital def input_two_read(): digital = xhat.input.two.read(...
0.603348
0.434041
import ast import json from distutils.util import strtobool import click import six from tower_cli import models, resources, exceptions as exc from tower_cli.api import client from tower_cli.conf import pop_option from tower_cli.cli import types from tower_cli.utils.data_structures import OrderedDict from tower_cli....
tower_cli/resources/setting.py
import ast import json from distutils.util import strtobool import click import six from tower_cli import models, resources, exceptions as exc from tower_cli.api import client from tower_cli.conf import pop_option from tower_cli.cli import types from tower_cli.utils.data_structures import OrderedDict from tower_cli....
0.744935
0.19349
__version__ = '0.10.3' import matplotlib.pyplot as plt import tensorflow as tf import load_data import optimizers import data_preprocessing import keras from keras import layers from keras import losses from keras import backend as K from keras.models import Sequential, Input, Model from keras.models import load_mode...
deep learning models/CNN_feature_extractor.py
__version__ = '0.10.3' import matplotlib.pyplot as plt import tensorflow as tf import load_data import optimizers import data_preprocessing import keras from keras import layers from keras import losses from keras import backend as K from keras.models import Sequential, Input, Model from keras.models import load_mode...
0.710729
0.374362
from datetime import datetime import logging import uuid from django.conf import settings from django.contrib.auth.models import AbstractUser from django.core.mail import EmailMessage from django.db import models from django.utils.translation import gettext_lazy as _ import numpy as np from .email_utils import send_m...
backend/apps/accounts/models.py
from datetime import datetime import logging import uuid from django.conf import settings from django.contrib.auth.models import AbstractUser from django.core.mail import EmailMessage from django.db import models from django.utils.translation import gettext_lazy as _ import numpy as np from .email_utils import send_m...
0.393152
0.092934
while True: capitalchars = 0 smallchars = 0 notalphanum = 0 spaces = 0 nums = 0 charsinseq = 0 valid = True password = input('Enter password: ') for i in range(len(password)): if i < len(password) - 1: part1 = chr(ord(password[i]) + 32) if 65 <= ord(pas...
Password Strength Checker/main.py
while True: capitalchars = 0 smallchars = 0 notalphanum = 0 spaces = 0 nums = 0 charsinseq = 0 valid = True password = input('Enter password: ') for i in range(len(password)): if i < len(password) - 1: part1 = chr(ord(password[i]) + 32) if 65 <= ord(pas...
0.095666
0.250434
import os import time from matplotlib.pyplot import show import numpy as np from tqdm import tqdm import pandas as pd import torch from torch.cuda import amp from .checkpoint import Checkpoint from loggers.loggers import Logger class Trainer(): def __init__(self, config, model, ...
trainer/trainer.py
import os import time from matplotlib.pyplot import show import numpy as np from tqdm import tqdm import pandas as pd import torch from torch.cuda import amp from .checkpoint import Checkpoint from loggers.loggers import Logger class Trainer(): def __init__(self, config, model, ...
0.568056
0.185043
from pychain.async_server import AsyncServer from pychain.util import encodeMsg, decodeMsg, intToBytes import socket from struct import pack, unpack nodeVersion = 1 commandLen = 12 def addr(addrList): return { 'addrList': addrList } def block(addrFrom, block): return { 'a...
pychain/p2p_interface.py
from pychain.async_server import AsyncServer from pychain.util import encodeMsg, decodeMsg, intToBytes import socket from struct import pack, unpack nodeVersion = 1 commandLen = 12 def addr(addrList): return { 'addrList': addrList } def block(addrFrom, block): return { 'a...
0.329823
0.065217
import re import torch from torch.autograd import Function from .._ext import libspn class FunctionBackend(object): def __init__(self, lib): self.backends = dict() self.parse_lib(lib) self.current_backend = None def __getattr__(self, name): func = self.backends[self.current_ba...
spnlib/spn/functions/SPG.py
import re import torch from torch.autograd import Function from .._ext import libspn class FunctionBackend(object): def __init__(self, lib): self.backends = dict() self.parse_lib(lib) self.current_backend = None def __getattr__(self, name): func = self.backends[self.current_ba...
0.695855
0.132066
from keras.models import Sequential from keras.datasets import boston_housing from keras.layers import Dense from keras.optimizers import Adam from keras.callbacks import EarlyStopping import numpy as np import matplotlib.pyplot as plt from utils import randomize # Hyper-parameters EPOCHS = 500 NUM_HIDDEN_UNITS = 64 L...
1_Basics/3_basic_regression_keras.py
from keras.models import Sequential from keras.datasets import boston_housing from keras.layers import Dense from keras.optimizers import Adam from keras.callbacks import EarlyStopping import numpy as np import matplotlib.pyplot as plt from utils import randomize # Hyper-parameters EPOCHS = 500 NUM_HIDDEN_UNITS = 64 L...
0.93922
0.678913
import os import sys import json import shutil from argparse import ArgumentParser import numpy as np import torch import utils from torchvision.models import vgg16 import torch.nn as nn from config import add_eval_args from data import PartNetDataset, Tree from image_encoder import ImageEncoder # os.environ["CUDA_VIS...
code/eval_part_pc_vst_fea_multi.py
import os import sys import json import shutil from argparse import ArgumentParser import numpy as np import torch import utils from torchvision.models import vgg16 import torch.nn as nn from config import add_eval_args from data import PartNetDataset, Tree from image_encoder import ImageEncoder # os.environ["CUDA_VIS...
0.392337
0.084191
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import random import matplotlib.animation class Object(): def __init__(self,mass,position,speed,index=None): self.mass=mass self.position=position self.speed=speed self.index=index class Qu...
old versions/but2D simulation.py
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import random import matplotlib.animation class Object(): def __init__(self,mass,position,speed,index=None): self.mass=mass self.position=position self.speed=speed self.index=index class Qu...
0.311846
0.200812
print('Starting with m = 1, n = 1:') callStack = [{'m': 1, 'n': 1, 'indentation': 0, 'instrPtr': 'start'}] returnValue = None while len(callStack) != 0: m = callStack[-1]['m'] n = callStack[-1]['n'] indentation = callStack[-1]['indentation'] instrPtr = callStack[-1]['instrPtr'] if instrPtr == 'sta...
files/recursion/recursion_examples-master/ackermann_iterative.py
print('Starting with m = 1, n = 1:') callStack = [{'m': 1, 'n': 1, 'indentation': 0, 'instrPtr': 'start'}] returnValue = None while len(callStack) != 0: m = callStack[-1]['m'] n = callStack[-1]['n'] indentation = callStack[-1]['indentation'] instrPtr = callStack[-1]['instrPtr'] if instrPtr == 'sta...
0.177241
0.184327
from mock import patch from unittest import TestCase from api.task import TaskSerializer from logical.models import Database, DatabaseHistory from logical.tests.factory import DatabaseFactory, DatabaseHistoryFactory class GetDatabaseTestCase(TestCase): def setUp(self): self.serializer = TaskSerializer() ...
dbaas/api/tests/test_taskhistory_serializer.py
from mock import patch from unittest import TestCase from api.task import TaskSerializer from logical.models import Database, DatabaseHistory from logical.tests.factory import DatabaseFactory, DatabaseHistoryFactory class GetDatabaseTestCase(TestCase): def setUp(self): self.serializer = TaskSerializer() ...
0.769557
0.141934
import requests from ddipy import constants from ddipy.commons import StatRecord, DomainStats, StatOmicsRecord from ddipy.ddi_utils import BadRequest class StatisticsClient: def __init__(self): pass @staticmethod def get_statistics_organisms(size=20): res = requests.get(constants.STATIS...
ddipy/statistics_client.py
import requests from ddipy import constants from ddipy.commons import StatRecord, DomainStats, StatOmicsRecord from ddipy.ddi_utils import BadRequest class StatisticsClient: def __init__(self): pass @staticmethod def get_statistics_organisms(size=20): res = requests.get(constants.STATIS...
0.433622
0.135604
# Runs on the 'goodimgs' catalog output after matching catalogs and downloading/checking fits # 'not_gz': these are galaxies which are part of the sdss lost set (and actually are now in gz) # Not yet clear how to find which galaxies these are - what makes the data file? import os import warnings import numpy as np...
decals/willett/metadata/make_nsa_not_gz_metadata.py
# Runs on the 'goodimgs' catalog output after matching catalogs and downloading/checking fits # 'not_gz': these are galaxies which are part of the sdss lost set (and actually are now in gz) # Not yet clear how to find which galaxies these are - what makes the data file? import os import warnings import numpy as np...
0.608361
0.514156
import logging import zephyr.message import zephyr.util class BioHarnessSignalAnalysis: def __init__(self, signal_callbacks, event_callbacks): self.signal_callbacks = signal_callbacks self.event_callbacks = event_callbacks self.latest_rr_value_sign = 0 def handle_signal(...
src/zephyr/bioharness.py
import logging import zephyr.message import zephyr.util class BioHarnessSignalAnalysis: def __init__(self, signal_callbacks, event_callbacks): self.signal_callbacks = signal_callbacks self.event_callbacks = event_callbacks self.latest_rr_value_sign = 0 def handle_signal(...
0.646572
0.31777
import csv from datetime import datetime ESTIMATED_JOURNEY_DURATION = { 'Hammersmith (District, Piccadilly lines)': { 'Hatton Cross': 27, 'Barons Court': 1, 'West Kensington': 3 } } MINIMUM_DELAY_REFUND = 15 # CSV Keys KEY_DATE = "Date" KEY_START_TIME = "Start Time" KEY_END_TIME = "En...
utils.py
import csv from datetime import datetime ESTIMATED_JOURNEY_DURATION = { 'Hammersmith (District, Piccadilly lines)': { 'Hatton Cross': 27, 'Barons Court': 1, 'West Kensington': 3 } } MINIMUM_DELAY_REFUND = 15 # CSV Keys KEY_DATE = "Date" KEY_START_TIME = "Start Time" KEY_END_TIME = "En...
0.110184
0.192274
import cv2 from threading import Thread from imutils import face_utils import numpy as np import imutils import dlib import math class Webcam: def __init__(self): self.capturador = cv2.VideoCapture('data/obama.mp4') self.capturador.set(3, 640) self.capturador.set(4, 480) self.mod...
EspejoVirtual/EspejoVirtual/webcam.py
import cv2 from threading import Thread from imutils import face_utils import numpy as np import imutils import dlib import math class Webcam: def __init__(self): self.capturador = cv2.VideoCapture('data/obama.mp4') self.capturador.set(3, 640) self.capturador.set(4, 480) self.mod...
0.319227
0.185209
import os import sys from functools import wraps from base64 import b64decode, b64encode try: from jqdatasdk import auth jq_source = True except ImportError: jq_source = False from xalpha.exceptions import DataSourceNotFound thismodule = sys.modules[__name__] providers_list = ["jq"] b64encode_s = la...
xalpha/provider.py
import os import sys from functools import wraps from base64 import b64decode, b64encode try: from jqdatasdk import auth jq_source = True except ImportError: jq_source = False from xalpha.exceptions import DataSourceNotFound thismodule = sys.modules[__name__] providers_list = ["jq"] b64encode_s = la...
0.277669
0.163312
import csv from PIL import Image from torch.utils.data import dataset import torch class AbstractImageCSVDataset(dataset.Dataset): def __init__(self, **kwargs): super(AbstractImageCSVDataset, self).__init__() self.data = kwargs.get('data') self.csv_path = kwargs.get('csv_path') se...
datasets.py
import csv from PIL import Image from torch.utils.data import dataset import torch class AbstractImageCSVDataset(dataset.Dataset): def __init__(self, **kwargs): super(AbstractImageCSVDataset, self).__init__() self.data = kwargs.get('data') self.csv_path = kwargs.get('csv_path') se...
0.656878
0.271632
fruit = "banana" """ the counting for the string character starts from 0 by default. """ letter = fruit[1] print(letter) """ to print out the letter 3-1=2 (index value) of the word banana """ x = 3 print(fruit[x - 1]) """prints the length of the word banana """ print(len(fruit)) """ using while loop to...
Strings.py
fruit = "banana" """ the counting for the string character starts from 0 by default. """ letter = fruit[1] print(letter) """ to print out the letter 3-1=2 (index value) of the word banana """ x = 3 print(fruit[x - 1]) """prints the length of the word banana """ print(len(fruit)) """ using while loop to...
0.331552
0.439988
from kratos import * from lake.passes.passes import lift_config_reg from lake.modules.sram_wrapper import SRAMWrapper from lake.modules.for_loop import ForLoop from lake.modules.addr_gen import AddrGen from lake.modules.spec.sched_gen import SchedGen from lake.utils.util import extract_formal_annotation, safe_wire from...
lake/modules/spec/tb_formal.py
from kratos import * from lake.passes.passes import lift_config_reg from lake.modules.sram_wrapper import SRAMWrapper from lake.modules.for_loop import ForLoop from lake.modules.addr_gen import AddrGen from lake.modules.spec.sched_gen import SchedGen from lake.utils.util import extract_formal_annotation, safe_wire from...
0.524638
0.066206
from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Div, Submit, HTML from dal import autocomplete from django import forms from django.urls import reverse from project_core.forms.utils import cancel_edit_button, cancel_button from project_c...
ProjectApplication/grant_management/forms/project.py
from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Div, Submit, HTML from dal import autocomplete from django import forms from django.urls import reverse from project_core.forms.utils import cancel_edit_button, cancel_button from project_c...
0.558447
0.088899
import os import requests from gtts import gTTS from html import escape from pyrogram.types import Message from tronx import app, gen app.CMD_HELP.update( {"supertools" : ( "supertools", { "ud [query]" : "Get The Meaning Of Any Word In Urban Dictionary.", "short [link]" : "Shorten a link into da.gd link...
tronx/modules/supertools.py
import os import requests from gtts import gTTS from html import escape from pyrogram.types import Message from tronx import app, gen app.CMD_HELP.update( {"supertools" : ( "supertools", { "ud [query]" : "Get The Meaning Of Any Word In Urban Dictionary.", "short [link]" : "Shorten a link into da.gd link...
0.117458
0.123577
from __future__ import print_function import socket from empire.server.common.plugins import Plugin import empire.server.common.helpers as helpers class Plugin(Plugin): description = "Empire reverseshell stager server plugin." def onLoad(self): print(helpers.color("[*] Loading Empire reverseshell s...
empire/server/plugins/reverseshell_stager_server.py
from __future__ import print_function import socket from empire.server.common.plugins import Plugin import empire.server.common.helpers as helpers class Plugin(Plugin): description = "Empire reverseshell stager server plugin." def onLoad(self): print(helpers.color("[*] Loading Empire reverseshell s...
0.524151
0.127002
import json from cafe.engine.models.base \ import AutoMarshallingModel, AutoMarshallingListModel class VendorMetadata(AutoMarshallingModel): def __init__(self, network_info=None, region=None, ip_whitelist=None, roles=None, provider=None): self.network_info = network_info sel...
cloudcafe/compute/extensions/config_drive/models/config_drive_vendor_meta.py
import json from cafe.engine.models.base \ import AutoMarshallingModel, AutoMarshallingListModel class VendorMetadata(AutoMarshallingModel): def __init__(self, network_info=None, region=None, ip_whitelist=None, roles=None, provider=None): self.network_info = network_info sel...
0.516108
0.051272
import torch import torch.nn as nn import torch.nn.functional as F class _ASPPModule(nn.Module): def __init__(self, inplanes, planes, kernel_size, padding, dilation): super(_ASPPModule, self).__init__() self.atrous_conv = nn.Conv3d(inplanes, planes, kernel_size=kernel_size, ...
models/aspp_3d.py
import torch import torch.nn as nn import torch.nn.functional as F class _ASPPModule(nn.Module): def __init__(self, inplanes, planes, kernel_size, padding, dilation): super(_ASPPModule, self).__init__() self.atrous_conv = nn.Conv3d(inplanes, planes, kernel_size=kernel_size, ...
0.941975
0.478041
import pandas as pd import snowflake.connector import getpass as pwd pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.set_option('display.width', None) pd.set_option('display.max_colwidth',None) default_warehouse = 'PROD_ANALYTICS_WH' ctx = snowflake.connector.connect( user...
Security/Create_Admin_Roles.py
import pandas as pd import snowflake.connector import getpass as pwd pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.set_option('display.width', None) pd.set_option('display.max_colwidth',None) default_warehouse = 'PROD_ANALYTICS_WH' ctx = snowflake.connector.connect( user...
0.247441
0.038322
from __future__ import absolute_import, print_function, unicode_literals from wolframclient.serializers.wxfencoder.constants import ( WXF_HEADER_COMPRESS, WXF_HEADER_SEPARATOR, WXF_VERSION, ) from wolframclient.serializers.wxfencoder.streaming import ZipCompressedWriter __all__ = ["WXFExprSerializer", "Se...
wolframclient/serializers/wxfencoder/serializer.py
from __future__ import absolute_import, print_function, unicode_literals from wolframclient.serializers.wxfencoder.constants import ( WXF_HEADER_COMPRESS, WXF_HEADER_SEPARATOR, WXF_VERSION, ) from wolframclient.serializers.wxfencoder.streaming import ZipCompressedWriter __all__ = ["WXFExprSerializer", "Se...
0.78695
0.351033
import numpy as np from deep_utils.utils.box_utils.boxes import Point def resize(img, dsize, in_source='Numpy', mode='cv2', interpolation=None): mode = 'cv2' if mode is None else mode if mode == 'cv2': dsize = Point.point2point(dsize, in_source=in_source, to_source=Point.PointSource.CV) new_im...
deep_utils/utils/resize_utils/main_resize.py
import numpy as np from deep_utils.utils.box_utils.boxes import Point def resize(img, dsize, in_source='Numpy', mode='cv2', interpolation=None): mode = 'cv2' if mode is None else mode if mode == 'cv2': dsize = Point.point2point(dsize, in_source=in_source, to_source=Point.PointSource.CV) new_im...
0.779741
0.400046
import re import json import PySimpleGUI as GUI import requests from time import sleep from ebooklib import epub from selenium import webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.firefox.firefox_binary import FirefoxBinary # Set the theme for the window GUI.theme('DarkAmber...
main.py
import re import json import PySimpleGUI as GUI import requests from time import sleep from ebooklib import epub from selenium import webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.firefox.firefox_binary import FirefoxBinary # Set the theme for the window GUI.theme('DarkAmber...
0.271541
0.085633
import functools import hashlib import hmac import logging import os import random import string import time import msgpack import base64 import socket import sys LOGS_DIR = "logs" BUFFER_SIZE = 1024 HMAC_PASS_KEY = "<KEY>" LOG_FORMAT = "%(asctime)s %(levelname)-8s %(message)s" SOCK_DCCP = 6 IPROTO_DCCP = 33 SOL_D...
checkers/tracker/checker.py
import functools import hashlib import hmac import logging import os import random import string import time import msgpack import base64 import socket import sys LOGS_DIR = "logs" BUFFER_SIZE = 1024 HMAC_PASS_KEY = "<KEY>" LOG_FORMAT = "%(asctime)s %(levelname)-8s %(message)s" SOCK_DCCP = 6 IPROTO_DCCP = 33 SOL_D...
0.354992
0.112649
import logging import os import pprint import gspread import pandas from oauth2client.service_account import ServiceAccountCredentials # Remove all handlers associated with the root logger object. for handler in logging.root.handlers[:]: logging.root.removeHandler(handler) logging.basicConfig( level=logging.D...
curation_utils/google/sheets.py
import logging import os import pprint import gspread import pandas from oauth2client.service_account import ServiceAccountCredentials # Remove all handlers associated with the root logger object. for handler in logging.root.handlers[:]: logging.root.removeHandler(handler) logging.basicConfig( level=logging.D...
0.447219
0.147095
__author__ = 'mnowotka' import StringIO from chembl_beaker.beaker.draw import cairoCanvas from chembl_beaker.beaker import draw from collections import defaultdict try: from rdkit import Chem from rdkit.Chem import AllChem except ImportError: Chem = None Draw = None AllChem = None try: from c...
chembl_webservices/core/utils.py
__author__ = 'mnowotka' import StringIO from chembl_beaker.beaker.draw import cairoCanvas from chembl_beaker.beaker import draw from collections import defaultdict try: from rdkit import Chem from rdkit.Chem import AllChem except ImportError: Chem = None Draw = None AllChem = None try: from c...
0.276007
0.14445
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Tag, Montagem from montagem.serializers import TagSerializer TAGS_URL = reverse('montagem:tag-list') ...
app/montagem/tests/test_tags_api.py
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Tag, Montagem from montagem.serializers import TagSerializer TAGS_URL = reverse('montagem:tag-list') ...
0.520009
0.255512
import numpy as np import shutil import urllib import urlparse from os.path import splitext, basename import os from os import sys, path import re from gp import * from core import * import math from IPython.core.debugger import Tracer from myutils import MyUtils class DefaultSpecies(object): def ge...
database/task_class/defaultspecies.py
import numpy as np import shutil import urllib import urlparse from os.path import splitext, basename import os from os import sys, path import re from gp import * from core import * import math from IPython.core.debugger import Tracer from myutils import MyUtils class DefaultSpecies(object): def ge...
0.076533
0.071397
import time import uuid import asyncio import functools from typing import * import datetime def daterange(start_date: datetime.date, end_date: Optional[datetime.date] = None, end_inclusive: bool = True): """Iterate each day between two dates, yielding each found day. If end_date is None, use current date. ...
twitterscraper/utils.py
import time import uuid import asyncio import functools from typing import * import datetime def daterange(start_date: datetime.date, end_date: Optional[datetime.date] = None, end_inclusive: bool = True): """Iterate each day between two dates, yielding each found day. If end_date is None, use current date. ...
0.757166
0.448668
import pytest import numpy as np import scipy.linalg import scipy.sparse import qutip if qutip.settings.has_mkl: from qutip._mkl.spsolve import mkl_splu, mkl_spsolve pytestmark = [ pytest.mark.skipif(not qutip.settings.has_mkl, reason='MKL extensions not found.'), ] class Test_spsolve...
qutip/tests/test_mkl.py
import pytest import numpy as np import scipy.linalg import scipy.sparse import qutip if qutip.settings.has_mkl: from qutip._mkl.spsolve import mkl_splu, mkl_spsolve pytestmark = [ pytest.mark.skipif(not qutip.settings.has_mkl, reason='MKL extensions not found.'), ] class Test_spsolve...
0.433022
0.654315
import tensorflow as tf # type: ignore import tensorflow.keras.layers as L # type: ignore from board import BOARD_SIZE, BOARD_SQUARES def residual_block( x: tf.Tensor, filters: int, separable_convs: bool = False, prefix: str = "" ) -> tf.Tensor: """ Make a residual block of layers. Parameters ...
src/alphazero/model.py
import tensorflow as tf # type: ignore import tensorflow.keras.layers as L # type: ignore from board import BOARD_SIZE, BOARD_SQUARES def residual_block( x: tf.Tensor, filters: int, separable_convs: bool = False, prefix: str = "" ) -> tf.Tensor: """ Make a residual block of layers. Parameters ...
0.951818
0.694782
from functools import wraps import time import os import numpy as np import logging from scipy.interpolate import griddata import xarray as xr import dask from dask.distributed import get_client, secede, rejoin from functools import wraps, partial import rasterio import shutil import glob import gc logger = logging.g...
src/xsar/utils.py
from functools import wraps import time import os import numpy as np import logging from scipy.interpolate import griddata import xarray as xr import dask from dask.distributed import get_client, secede, rejoin from functools import wraps, partial import rasterio import shutil import glob import gc logger = logging.g...
0.796015
0.354796
import asyncio import collections import json import os from typing import Dict, List import click import humanfriendly import tabulate from cobras.client.client import subscribeClient, unsafeSubcribeClient from cobras.client.connection import ActionFlow from cobras.common.algorithm import transpose from cobras.common...
cobras/client/monitor.py
import asyncio import collections import json import os from typing import Dict, List import click import humanfriendly import tabulate from cobras.client.client import subscribeClient, unsafeSubcribeClient from cobras.client.connection import ActionFlow from cobras.common.algorithm import transpose from cobras.common...
0.584153
0.119254
from trac.core import Component, implements, TracError from trac.web.chrome import add_stylesheet from announcer.api import IAnnouncementSubscriber from announcer.api import IAnnouncementPreferenceProvider from announcer.api import _ from announcer.query import * class RuleBasedTicketSubscriber(Component): ...
announcer/subscribers/rulefilters.py
from trac.core import Component, implements, TracError from trac.web.chrome import add_stylesheet from announcer.api import IAnnouncementSubscriber from announcer.api import IAnnouncementPreferenceProvider from announcer.api import _ from announcer.query import * class RuleBasedTicketSubscriber(Component): ...
0.307774
0.096877
from __future__ import (absolute_import, division, print_function, unicode_literals) from warnings import warn from iminuit.iminuit_warnings import InitialParamWarning from iminuit import util as mutil import numpy as np def pedantic(self, parameters, kwds, errordef): def w(msg): w...
iminuit/_minuit_methods.py
from __future__ import (absolute_import, division, print_function, unicode_literals) from warnings import warn from iminuit.iminuit_warnings import InitialParamWarning from iminuit import util as mutil import numpy as np def pedantic(self, parameters, kwds, errordef): def w(msg): w...
0.591723
0.539347
from time import perf_counter_ns import pytest from didcomm.pack_encrypted import PackEncryptedConfig, pack_encrypted from didcomm.unpack import unpack, UnpackConfig from tests.test_vectors.common import BOB_DID, ALICE_DID from tests.test_vectors.didcomm_messages.messages import TEST_MESSAGE RECIPIENT_KEYS_COUNT = [...
tests/performance/test_performance.py
from time import perf_counter_ns import pytest from didcomm.pack_encrypted import PackEncryptedConfig, pack_encrypted from didcomm.unpack import unpack, UnpackConfig from tests.test_vectors.common import BOB_DID, ALICE_DID from tests.test_vectors.didcomm_messages.messages import TEST_MESSAGE RECIPIENT_KEYS_COUNT = [...
0.41324
0.230313
from tkinter import messagebox from os import path from tkinter.constants import DISABLED, NORMAL from babel.localedata import load import simplejson as json from threading import Thread from multiprocessing.dummy import Process import requests import pyodbc from datetime import datetime from tkinter import messagebox...
dev/export-service-sale-py/utils.py
from tkinter import messagebox from os import path from tkinter.constants import DISABLED, NORMAL from babel.localedata import load import simplejson as json from threading import Thread from multiprocessing.dummy import Process import requests import pyodbc from datetime import datetime from tkinter import messagebox...
0.394084
0.124479
from django.shortcuts import render, get_object_or_404 from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from products.models import Product from django.contrib import messages from .models import UserFavoriteslist from profiles.models import UserProfile # Function...
favorites/views.py
from django.shortcuts import render, get_object_or_404 from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from products.models import Product from django.contrib import messages from .models import UserFavoriteslist from profiles.models import UserProfile # Function...
0.487063
0.08152
from .image import subimage_by_roi import astimp class Antibiotic(): "an antibiotic tested in an AST" def __init__(self, short_name, pellet_circle, inhibition, image, roi, px_per_mm): self.short_name = short_name self.pellet_circle = pellet_circle self.inhibition = inhibition s...
python-module/astimp_tools/datamodels.py
from .image import subimage_by_roi import astimp class Antibiotic(): "an antibiotic tested in an AST" def __init__(self, short_name, pellet_circle, inhibition, image, roi, px_per_mm): self.short_name = short_name self.pellet_circle = pellet_circle self.inhibition = inhibition s...
0.656878
0.219693
from Actors import Teacher, Opening import random class Matcher: # TODO this shouldn't take teachers and openings, but preferences def __init__(self, teachers, openings): # TODO comment self.teachers = teachers self.openings = openings self.actors = teachers + openings ...
Matching Algo/Matching Algorithm/Matching Algorithm/match.py
from Actors import Teacher, Opening import random class Matcher: # TODO this shouldn't take teachers and openings, but preferences def __init__(self, teachers, openings): # TODO comment self.teachers = teachers self.openings = openings self.actors = teachers + openings ...
0.291989
0.339089
from marshmallow import Schema, fields, post_dump from sqlalchemy.sql import expression from app import db class AIModel(db.Model): __tablename__ = 'model' id = db.Column(db.Integer, primary_key=True) category = db.Column(db.String) uuid = db.Column(db.String) author = db.Column(db.String) upd...
web/models/AIModel.py
from marshmallow import Schema, fields, post_dump from sqlalchemy.sql import expression from app import db class AIModel(db.Model): __tablename__ = 'model' id = db.Column(db.Integer, primary_key=True) category = db.Column(db.String) uuid = db.Column(db.String) author = db.Column(db.String) upd...
0.629091
0.065485
from rest_framework import exceptions, status from rest_framework.views import APIView from magpie.apps.files.versions.v1.services.consumer import ConsumerService from magpie.core.permissions import AdminAPIUserPermission from magpie.core.response import response class ConsumersAPIView(APIView): permission_class...
magpie/apps/files/versions/v1/api/consumer.py
from rest_framework import exceptions, status from rest_framework.views import APIView from magpie.apps.files.versions.v1.services.consumer import ConsumerService from magpie.core.permissions import AdminAPIUserPermission from magpie.core.response import response class ConsumersAPIView(APIView): permission_class...
0.519278
0.062103
try: from numpy import array, transpose import pandas as pd from sklearn.model_selection import cross_val_score, cross_validate from time import time from sklearn.svm import SVC except Exception as e: print(e) raise Exception('Alguns módulos não foram instalados...') class MyGridSearch: ...
utils/myGridSearch.py
try: from numpy import array, transpose import pandas as pd from sklearn.model_selection import cross_val_score, cross_validate from time import time from sklearn.svm import SVC except Exception as e: print(e) raise Exception('Alguns módulos não foram instalados...') class MyGridSearch: ...
0.698946
0.325092
import os import time import threading import random import gevent import uuid import sha import logging import functools import contextlib from sqlalchemy import event from sqlalchemy import create_engine as sqlalchemy_create_engine from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta from sqlalc...
rest_arch/db.py
import os import time import threading import random import gevent import uuid import sha import logging import functools import contextlib from sqlalchemy import event from sqlalchemy import create_engine as sqlalchemy_create_engine from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta from sqlalc...
0.403214
0.09277
import tensorflow as tf import logging def flip_left_right(): return lambda x: tf.image.random_flip_left_right(x) def random_brightness(args_dict): max_delta = args_dict['max_delta'] assert (max_delta >= 0), logging.fatal("'max_delta' argument to " "tf.image.ra...
data/preprocessing.py
import tensorflow as tf import logging def flip_left_right(): return lambda x: tf.image.random_flip_left_right(x) def random_brightness(args_dict): max_delta = args_dict['max_delta'] assert (max_delta >= 0), logging.fatal("'max_delta' argument to " "tf.image.ra...
0.874654
0.503235
import cv2 from matplotlib.pyplot import spring import tqdm import math import numpy as np from linalg import get_center_of_mass, get_line_equation, get_perpendicular_line_equation3d, get_plane_equation, point2line_vector, rotate3d, signed_plane_point_distance, normalize from utils import load_points_and_faces_and_spri...
engine.py
import cv2 from matplotlib.pyplot import spring import tqdm import math import numpy as np from linalg import get_center_of_mass, get_line_equation, get_perpendicular_line_equation3d, get_plane_equation, point2line_vector, rotate3d, signed_plane_point_distance, normalize from utils import load_points_and_faces_and_spri...
0.439026
0.319453
import configparser import pyautogui import cv2 import time import winsound import playsound import random import numpy import win32gui import win32con import wmi import tkinter import multiprocessing import os import win32file import struct import requests import re from datetime import datetime from multiprocessing i...
cl.py
import configparser import pyautogui import cv2 import time import winsound import playsound import random import numpy import win32gui import win32con import wmi import tkinter import multiprocessing import os import win32file import struct import requests import re from datetime import datetime from multiprocessing i...
0.143038
0.069479
import base64 import os import cryptography from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from . import config class Remindme: '''A user's single rem...
remindme/Remindme.py
import base64 import os import cryptography from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from . import config class Remindme: '''A user's single rem...
0.576661
0.050705
import datetime as dt import pytest from rest_framework.reverse import reverse from rest_framework import status from appointments import models as m @pytest.mark.django_db def test_licence_plate_normalization(appointment_client, appointment): rv = appointment_client.patch( reverse("appointment-detail",...
code/backend/appointments/tests/test_appointments.py
import datetime as dt import pytest from rest_framework.reverse import reverse from rest_framework import status from appointments import models as m @pytest.mark.django_db def test_licence_plate_normalization(appointment_client, appointment): rv = appointment_client.patch( reverse("appointment-detail",...
0.582729
0.338856
# Force Python 2 to use float division even for ints from __future__ import division from __future__ import print_function import importlib import logging import os import re import time import stacktrain.config.general as conf import stacktrain.kvm.vm_create as vm import stacktrain.core.iso_image as iso_image impo...
labs/stacktrain/kvm/install_base.py
# Force Python 2 to use float division even for ints from __future__ import division from __future__ import print_function import importlib import logging import os import re import time import stacktrain.config.general as conf import stacktrain.kvm.vm_create as vm import stacktrain.core.iso_image as iso_image impo...
0.531453
0.092852
__all__ = ['pnsequence', 'zcsequence'] import numpy as np from numpy import empty, exp, pi, arange, int8, fromiter, sum def pnsequence(pn_order, pn_seed, pn_mask, seq_length): """ Generate a PN (Pseudo-Noise) sequence using a Linear Feedback Shift Register (LFSR). Seed and mask are ordered so that: ...
commpy/sequences.py
__all__ = ['pnsequence', 'zcsequence'] import numpy as np from numpy import empty, exp, pi, arange, int8, fromiter, sum def pnsequence(pn_order, pn_seed, pn_mask, seq_length): """ Generate a PN (Pseudo-Noise) sequence using a Linear Feedback Shift Register (LFSR). Seed and mask are ordered so that: ...
0.906424
0.68225
from __future__ import ( unicode_literals, absolute_import, print_function, division, ) str = type('') import sys import io import mmap import compoundfiles.mmap as fake_mmap import pytest @pytest.fixture(scope='session') def source(): return io.open('tests/mmap.dat', 'rb') @pytest.fixture...
tests/test_mmap.py
from __future__ import ( unicode_literals, absolute_import, print_function, division, ) str = type('') import sys import io import mmap import compoundfiles.mmap as fake_mmap import pytest @pytest.fixture(scope='session') def source(): return io.open('tests/mmap.dat', 'rb') @pytest.fixture...
0.522689
0.637405
from asyncio import sleep import os import discord from replit import db from keep_alive import keep_alive from discord.ext import commands from pretty_help import DefaultMenu, PrettyHelp def get_prefix(bot, message): """A callable Prefix for our bot. This could be edited to allow per server prefixes.""" pref...
bot/main.py
from asyncio import sleep import os import discord from replit import db from keep_alive import keep_alive from discord.ext import commands from pretty_help import DefaultMenu, PrettyHelp def get_prefix(bot, message): """A callable Prefix for our bot. This could be edited to allow per server prefixes.""" pref...
0.379378
0.092442
import copy import os import time import sys import pandas as pd import pytest from unittest.mock import patch, PropertyMock, MagicMock import geopandas as gpd import numpy as np from osgeo import ogr from plio.io import io_gdal from autocnet.examples import get_path from .. import network from .. import edge from...
autocnet/graph/tests/test_network.py
import copy import os import time import sys import pandas as pd import pytest from unittest.mock import patch, PropertyMock, MagicMock import geopandas as gpd import numpy as np from osgeo import ogr from plio.io import io_gdal from autocnet.examples import get_path from .. import network from .. import edge from...
0.2522
0.3219
import csv import os import yaml from box import Box class Config(): _cfg = None def __init__(self, src): self.src = src @property def config(self): if self._cfg is None: with open(self.src) as f: self._cfg = Box(yaml.load(f)) return self._cfg ...
src/main.py
import csv import os import yaml from box import Box class Config(): _cfg = None def __init__(self, src): self.src = src @property def config(self): if self._cfg is None: with open(self.src) as f: self._cfg = Box(yaml.load(f)) return self._cfg ...
0.219254
0.07208
import cv2 import numpy as np import os import csv import sys from PIL import Image import random minValue = 70 skinkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) low_range = np.array([0, 70, 100]) upper_range = np.array([20, 200, 255]) # cv2.imshow("final",img) # cv2.waitKey(0) kernel = np.ones((5, 5...
data_loader.py
import cv2 import numpy as np import os import csv import sys from PIL import Image import random minValue = 70 skinkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) low_range = np.array([0, 70, 100]) upper_range = np.array([20, 200, 255]) # cv2.imshow("final",img) # cv2.waitKey(0) kernel = np.ones((5, 5...
0.203312
0.182244
import sys import threading import types from abc import abstractmethod, ABCMeta from collections import Container, Iterable, Mapping, defaultdict, OrderedDict import mock import six from future.utils import iteritems from ducktest.base import PlainTypeWrapper, ContainerTypeWrapper, MappingTypeWrapper, Processor, cha...
ducktest/typing.py
import sys import threading import types from abc import abstractmethod, ABCMeta from collections import Container, Iterable, Mapping, defaultdict, OrderedDict import mock import six from future.utils import iteritems from ducktest.base import PlainTypeWrapper, ContainerTypeWrapper, MappingTypeWrapper, Processor, cha...
0.44553
0.121895
import json from wsgi_basic import exception from wsgi_basic.tests.base import BaseTestCase import wsgi_basic.tests.config as config class UserSingleAPITest(BaseTestCase): def create_user(self, username, password, role): url = "{s}/v1/users".format(s=config.TARGET_SERVICE_ADDRESS) payload = dict...
wsgi_basic/tests/api/v1/user/test_single_api.py
import json from wsgi_basic import exception from wsgi_basic.tests.base import BaseTestCase import wsgi_basic.tests.config as config class UserSingleAPITest(BaseTestCase): def create_user(self, username, password, role): url = "{s}/v1/users".format(s=config.TARGET_SERVICE_ADDRESS) payload = dict...
0.294824
0.088072
from json import loads as json_loads from typing import List # 3rd party from pytest import fixture from flask.testing import FlaskClient from sqlalchemy.orm import scoped_session # custom from test_system.models import Token, Test from test_system.routes.tests import ROUTE from test_system.constants import PRE_COLLECT...
test/test_test_system/test_routes/test_tests.py
from json import loads as json_loads from typing import List # 3rd party from pytest import fixture from flask.testing import FlaskClient from sqlalchemy.orm import scoped_session # custom from test_system.models import Token, Test from test_system.routes.tests import ROUTE from test_system.constants import PRE_COLLECT...
0.669529
0.475727
import tensorflow as tf import tensorflow.keras as ks from kgcnn.layers.base import GraphBaseLayer from kgcnn.ops.partition import partition_row_indexing from kgcnn.ops.segment import segment_ops_by_name, segment_softmax @tf.keras.utils.register_keras_serializable(package='kgcnn', name='PoolingLocalEdges') class Poo...
kgcnn/layers/pool/pooling.py
import tensorflow as tf import tensorflow.keras as ks from kgcnn.layers.base import GraphBaseLayer from kgcnn.ops.partition import partition_row_indexing from kgcnn.ops.segment import segment_ops_by_name, segment_softmax @tf.keras.utils.register_keras_serializable(package='kgcnn', name='PoolingLocalEdges') class Poo...
0.949623
0.456955
import numpy as np import pandas as pd import statsmodels.api as sm import statsmodels.formula.api as smf from stargazer.stargazer import Stargazer from IPython.core.display import HTML from IPython.core.interactiveshell import InteractiveShell from statsmodels.sandbox.regression.gmm import IV2SLS def create_table1...
auxiliary/Tables.py
import numpy as np import pandas as pd import statsmodels.api as sm import statsmodels.formula.api as smf from stargazer.stargazer import Stargazer from IPython.core.display import HTML from IPython.core.interactiveshell import InteractiveShell from statsmodels.sandbox.regression.gmm import IV2SLS def create_table1...
0.207696
0.499512
import dearpygui.dearpygui as dpg import dearpygui.demo as demo from cartoon_wnd import CartoonWindow class MainWindow: MIN_SIZE = (1320, 800) def __init__(self): self._cartoon_wnd = CartoonWindow() self._client_size = (MainWindow.MIN_SIZE[0] - 16, MainWindow.MIN_SIZE[1] - 39) self._...
main.py
import dearpygui.dearpygui as dpg import dearpygui.demo as demo from cartoon_wnd import CartoonWindow class MainWindow: MIN_SIZE = (1320, 800) def __init__(self): self._cartoon_wnd = CartoonWindow() self._client_size = (MainWindow.MIN_SIZE[0] - 16, MainWindow.MIN_SIZE[1] - 39) self._...
0.319015
0.057414