code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
from .api import api from .exceptions import mySword from .session import session as ses from requests import post class upload(object): def __init__(self, session): if not isinstance(session, ses): raise mySword("invalid session") self.vk = api(session).call def messageDocument(s...
pyVkBotApiV2/upload.py
from .api import api from .exceptions import mySword from .session import session as ses from requests import post class upload(object): def __init__(self, session): if not isinstance(session, ses): raise mySword("invalid session") self.vk = api(session).call def messageDocument(s...
0.416559
0.071235
__author__ = "<NAME>" __date__ = "17 Aug 2017" import tempfile import unittest from simbad.parsers import anode_parser class Test(unittest.TestCase): def test_anode_parser(self): content = """ANODE - ANOmalous DEnsity analysis - version 2013/1 =================================================== Comm...
simbad/parsers/tests/test_anode_parser.py
__author__ = "<NAME>" __date__ = "17 Aug 2017" import tempfile import unittest from simbad.parsers import anode_parser class Test(unittest.TestCase): def test_anode_parser(self): content = """ANODE - ANOmalous DEnsity analysis - version 2013/1 =================================================== Comm...
0.421076
0.229913
import logging from collections import defaultdict from typing import Dict, List, Optional import numpy as np from ..utils.colmap import read_model from ..utils.quaternions import weighted_pose logger = logging.getLogger(__name__) class Model3D: def __init__(self, path): logger.info('Reading COLMAP mode...
pixloc/localization/model3d.py
import logging from collections import defaultdict from typing import Dict, List, Optional import numpy as np from ..utils.colmap import read_model from ..utils.quaternions import weighted_pose logger = logging.getLogger(__name__) class Model3D: def __init__(self, path): logger.info('Reading COLMAP mode...
0.904719
0.270806
import time import json import pytest from suricate.configuration import config def test_publish_to_default_channel(component, scheduler, pubsub): """Publishing to the default channel `namespace/component/attribute""" job = scheduler.add_attribute_job(component, 'position', timer=0.01) scheduler.wait_unt...
tests/monitor/test_attribute.py
import time import json import pytest from suricate.configuration import config def test_publish_to_default_channel(component, scheduler, pubsub): """Publishing to the default channel `namespace/component/attribute""" job = scheduler.add_attribute_job(component, 'position', timer=0.01) scheduler.wait_unt...
0.631026
0.374791
import copy from collections import OrderedDict import pandas as pd import numpy as np __all__ = ( "DataMapper", "from_boolean_to_integers_map", "from_explanatory_to_integers", "from_integers_to_boolean_map", ) def from_explanatory_to_integers(series): return {v: i for i, v in enumerate(set(se...
dsmlt/preprocessing/data.py
import copy from collections import OrderedDict import pandas as pd import numpy as np __all__ = ( "DataMapper", "from_boolean_to_integers_map", "from_explanatory_to_integers", "from_integers_to_boolean_map", ) def from_explanatory_to_integers(series): return {v: i for i, v in enumerate(set(se...
0.713332
0.631197
from PyQt5.Qt import QStandardItemModel from PyQt5.Qt import Qt from PyQt5.Qt import QPixmap from PyQt5.Qt import QImage from PyQt5.Qt import QIcon from mc.tools.IconProvider import IconProvider from mc.common.models import HistoryDbModel from mc.common.globalvars import gVar class LocationCompleterModel(QStandardItem...
mc/navigation/completer/LocationCompleterModel.py
from PyQt5.Qt import QStandardItemModel from PyQt5.Qt import Qt from PyQt5.Qt import QPixmap from PyQt5.Qt import QImage from PyQt5.Qt import QIcon from mc.tools.IconProvider import IconProvider from mc.common.models import HistoryDbModel from mc.common.globalvars import gVar class LocationCompleterModel(QStandardItem...
0.535098
0.103522
def solveSimonSays(flashSequence, # List of strings: colors flashed numStrikes, bombSpecs): # Dictionary of bomb specs such as serial number last digit, parallel port, battery count, etc if bombSpecs['serialNumberVowel'] is True: if numStrikes == 0: f...
ModuleSolvers/SimonSays.py
def solveSimonSays(flashSequence, # List of strings: colors flashed numStrikes, bombSpecs): # Dictionary of bomb specs such as serial number last digit, parallel port, battery count, etc if bombSpecs['serialNumberVowel'] is True: if numStrikes == 0: f...
0.233619
0.411288
import numpy as np # Constants for the curation dict of presets MULTICELL_PRESET = '3MemSym' # ferro N_FERRO = 9 REFINE_W = True DIAG_W = True RANDOM_W = False # TODO care how this interacts with random W in singlecell_simsetup curated = { 'mutual_inhibition': {'XI': np.array([ [1, -1], # ...
singlecell/singlecell_simsetup_curated.py
import numpy as np # Constants for the curation dict of presets MULTICELL_PRESET = '3MemSym' # ferro N_FERRO = 9 REFINE_W = True DIAG_W = True RANDOM_W = False # TODO care how this interacts with random W in singlecell_simsetup curated = { 'mutual_inhibition': {'XI': np.array([ [1, -1], # ...
0.156781
0.685423
import requests import boto from cloudcarver.errors import HandlerError, AWSError from cloudcarver.message import ResponseMessage, RequestMessage import time import logging __author__ = 'jdenning' log = logging.getLogger("cloudcarver") def get_message_from_sqs(sqs_queue): """ Get message from sqs_queue, ...
cloudcarver/controller.py
import requests import boto from cloudcarver.errors import HandlerError, AWSError from cloudcarver.message import ResponseMessage, RequestMessage import time import logging __author__ = 'jdenning' log = logging.getLogger("cloudcarver") def get_message_from_sqs(sqs_queue): """ Get message from sqs_queue, ...
0.447219
0.082586
import requests import random import json from .Models.urlModel import ( SSO_URL, TEST_PASSWORD_URL, SERVICE_URL) from .Models.exceptionsModel import ( LoginError, UserDefunctError, UserNotFound, UserOrPassError, ArgError) from .Cores.student import Student def login_id(user_id: str, password: str) -> request...
zhixuewang/Zhixuewang.py
import requests import random import json from .Models.urlModel import ( SSO_URL, TEST_PASSWORD_URL, SERVICE_URL) from .Models.exceptionsModel import ( LoginError, UserDefunctError, UserNotFound, UserOrPassError, ArgError) from .Cores.student import Student def login_id(user_id: str, password: str) -> request...
0.241489
0.068569
import urllib import json import sqlite3 conn = sqlite3.connect('worldcat.sqlite') cur = conn.cursor() liblist = list() libraries = open('top5libraries.txt') for library in libraries: liblist.append(library) lib1 = liblist[0].strip() lib2 = liblist[1].strip() lib3 = liblist[2].strip() lib4 = libli...
worldcat2.py
import urllib import json import sqlite3 conn = sqlite3.connect('worldcat.sqlite') cur = conn.cursor() liblist = list() libraries = open('top5libraries.txt') for library in libraries: liblist.append(library) lib1 = liblist[0].strip() lib2 = liblist[1].strip() lib3 = liblist[2].strip() lib4 = libli...
0.189821
0.041037
from http.client import HTTPSConnection as httpc from xml.etree.ElementTree import tostring from xml.dom import minidom from pyquery import PyQuery as pq import html2text import re import bz2 import time conn = {} h = html2text.HTML2Text() h.ignore_links = True h.ignore_images = True h.ignore_emphasis = True h.body_w...
uol_redacoes_xml/crawler/commons.py
from http.client import HTTPSConnection as httpc from xml.etree.ElementTree import tostring from xml.dom import minidom from pyquery import PyQuery as pq import html2text import re import bz2 import time conn = {} h = html2text.HTML2Text() h.ignore_links = True h.ignore_images = True h.ignore_emphasis = True h.body_w...
0.243463
0.083479
import sys from sys import argv """Assigning the possible connectives to variables which can be further used to implement each module""" IFF = "iff" IMPLIES = "implies" AND = "and" OR = "or" NOT = "not" def is_positive_symbol(s): """ Function to find if s is a positive symbol by checking if its not a ...
CNF Converter/CNFConverter.py
import sys from sys import argv """Assigning the possible connectives to variables which can be further used to implement each module""" IFF = "iff" IMPLIES = "implies" AND = "and" OR = "or" NOT = "not" def is_positive_symbol(s): """ Function to find if s is a positive symbol by checking if its not a ...
0.181698
0.390825
from typing import Tuple import torch import pytorch_lightning as pl class UserEncoder(torch.nn.Module): def __init__(self, num_users: int, user_embedding_dim: int, num_ages: int, user_age_embedding_dim: int, num_genders: int, ...
src/model.py
from typing import Tuple import torch import pytorch_lightning as pl class UserEncoder(torch.nn.Module): def __init__(self, num_users: int, user_embedding_dim: int, num_ages: int, user_age_embedding_dim: int, num_genders: int, ...
0.961543
0.542015
import logging import threading from datetime import datetime from typing import Any, List, Optional from rx.disposable import Disposable from rx.core import typing from rx.concurrency import ScheduledItem from rx.internal.exceptions import DisposedException from rx.internal.priorityqueue import PriorityQueue from .s...
rx/concurrency/eventloopscheduler.py
import logging import threading from datetime import datetime from typing import Any, List, Optional from rx.disposable import Disposable from rx.core import typing from rx.concurrency import ScheduledItem from rx.internal.exceptions import DisposedException from rx.internal.priorityqueue import PriorityQueue from .s...
0.831793
0.152158
from poseidon.infrastructure.road_network_revised import RoadNetwork from poseidon.infrastructure.bernoulli import BernoulliRoadDamageModel from poseidon.disasters.earthquakes import GaussianEarthquake from poseidon.disasters.hurricanes import LinearHurricane from poseidon.metrics.graph_metrics import is_node_connected...
webapp/poseidon/orchestrators/single_disaster_road_risk_orchestrator.py
from poseidon.infrastructure.road_network_revised import RoadNetwork from poseidon.infrastructure.bernoulli import BernoulliRoadDamageModel from poseidon.disasters.earthquakes import GaussianEarthquake from poseidon.disasters.hurricanes import LinearHurricane from poseidon.metrics.graph_metrics import is_node_connected...
0.634204
0.347205
import sys import os import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.animation as animation import math import numpy as np from numpy.random import * from scipy.interpolate import interp1d # サンプリング周期[s] DT = 0.01 class Visualize: def __init__(self): self.r = 0.2 ...
scripts/robot_steering_sim.py
import sys import os import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.animation as animation import math import numpy as np from numpy.random import * from scipy.interpolate import interp1d # サンプリング周期[s] DT = 0.01 class Visualize: def __init__(self): self.r = 0.2 ...
0.364325
0.407392
import os from Toolbox.ColorTools import * import re from requests import * import sys def g_tk(p_skey): h = 5381 for c in p_skey: h += (h << 5) + ord(c) return h & 0x7fffffff def SendMsg(uin, skey, p_skey, msg): qq = re.findall(r'o0*(\S+)', uin)[0] with open('HackQzone.txt', 'r') as fp:...
Sniffer v3.0/Plugin/QzoneCookie.py
import os from Toolbox.ColorTools import * import re from requests import * import sys def g_tk(p_skey): h = 5381 for c in p_skey: h += (h << 5) + ord(c) return h & 0x7fffffff def SendMsg(uin, skey, p_skey, msg): qq = re.findall(r'o0*(\S+)', uin)[0] with open('HackQzone.txt', 'r') as fp:...
0.125668
0.103703
from django.db import models from django.contrib.auth.models import User, AbstractBaseUser, PermissionsMixin, BaseUserManager from django.utils.http import urlquote from django.utils.text import slugify import datetime import pytz # Create your models here. class AuthorManager(BaseUserManager): def _create_us...
core/models.py
from django.db import models from django.contrib.auth.models import User, AbstractBaseUser, PermissionsMixin, BaseUserManager from django.utils.http import urlquote from django.utils.text import slugify import datetime import pytz # Create your models here. class AuthorManager(BaseUserManager): def _create_us...
0.533397
0.124027
import re from typing import Any from .ctx import Context class ValidatorMetaclass(type): def __new__(cls, name, bases, classdict): error_code_map = {} error_messages = {} message_values = {} for base in reversed(bases): try: error_code_map.update(bas...
dirty_validators/basic.py
import re from typing import Any from .ctx import Context class ValidatorMetaclass(type): def __new__(cls, name, bases, classdict): error_code_map = {} error_messages = {} message_values = {} for base in reversed(bases): try: error_code_map.update(bas...
0.740174
0.2389
# pylint: skip-file from mock import patch from copy import deepcopy from cdk_constructs.adf_codepipeline import Action from aws_cdk import ( aws_codepipeline ) from adf_codepipeline_test_constants import BASE_MAP_PARAMS @patch('cdk_constructs.adf_codepipeline._codepipeline.CfnPipeline.ActionDeclarationProperty') @...
src/lambda_codebase/initial_commit/bootstrap_repository/adf-build/shared/cdk/cdk_constructs/tests/test_adf_codepipeline_output_artifacts.py
# pylint: skip-file from mock import patch from copy import deepcopy from cdk_constructs.adf_codepipeline import Action from aws_cdk import ( aws_codepipeline ) from adf_codepipeline_test_constants import BASE_MAP_PARAMS @patch('cdk_constructs.adf_codepipeline._codepipeline.CfnPipeline.ActionDeclarationProperty') @...
0.677367
0.153962
import logging import broadway_api.daos as daos from broadway_api.models.grading_job import GradingJobType from broadway_api.utils.run import continue_grading_run, fail_grading_run logger = logging.getLogger("job-callbacks") def job_update_callback(settings, grading_job_id, grading_run_id): job_dao = daos.Gradi...
broadway_api/callbacks/job.py
import logging import broadway_api.daos as daos from broadway_api.models.grading_job import GradingJobType from broadway_api.utils.run import continue_grading_run, fail_grading_run logger = logging.getLogger("job-callbacks") def job_update_callback(settings, grading_job_id, grading_run_id): job_dao = daos.Gradi...
0.348202
0.076511
import json # SBaaS from .stage02_isotopomer_fittedFluxSplits_query import stage02_isotopomer_fittedFluxSplits_query from SBaaS_base.sbaas_template_io import sbaas_template_io # Resources from io_utilities.base_importData import base_importData from io_utilities.base_exportData import base_exportData class stage02_iso...
SBaaS_MFA/stage02_isotopomer_fittedFluxSplits_io.py
import json # SBaaS from .stage02_isotopomer_fittedFluxSplits_query import stage02_isotopomer_fittedFluxSplits_query from SBaaS_base.sbaas_template_io import sbaas_template_io # Resources from io_utilities.base_importData import base_importData from io_utilities.base_exportData import base_exportData class stage02_iso...
0.378
0.359673
import os import pygame import unicodedata from pygame.locals import * pygame.init() FRAME_SIZE = (750, 560) FRAME_PADDING = (10, 10) mainFrame = pygame.display.set_mode(FRAME_SIZE) pygame.display.set_caption('Play Fair Cipher') SQUARE_SIZE = 100 SQUARE_MARGIN = 10 SQUARE_FONT = pygame.font.Font(None, 65) TEXT_FONT...
src/chiffreDePlayFair.py
import os import pygame import unicodedata from pygame.locals import * pygame.init() FRAME_SIZE = (750, 560) FRAME_PADDING = (10, 10) mainFrame = pygame.display.set_mode(FRAME_SIZE) pygame.display.set_caption('Play Fair Cipher') SQUARE_SIZE = 100 SQUARE_MARGIN = 10 SQUARE_FONT = pygame.font.Font(None, 65) TEXT_FONT...
0.174797
0.355411
import os import stat import subprocess def access_demo(): """ 检验权限模式 os.F_OK: 作为access()的mode参数,测试path是否存在。 os.R_OK: 包含在access()的mode参数中 , 测试path是否可读。 os.W_OK 包含在access()的mode参数中 , 测试path是否可写。 os.X_OK 包含在access()的mode参数中 ,测试path是否可执行 https://www.cnblogs.com/yuanqiangfei/p/8109991.html ...
language/python/modules/os/os_module.py
import os import stat import subprocess def access_demo(): """ 检验权限模式 os.F_OK: 作为access()的mode参数,测试path是否存在。 os.R_OK: 包含在access()的mode参数中 , 测试path是否可读。 os.W_OK 包含在access()的mode参数中 , 测试path是否可写。 os.X_OK 包含在access()的mode参数中 ,测试path是否可执行 https://www.cnblogs.com/yuanqiangfei/p/8109991.html ...
0.142411
0.161386
import numpy as np import sys import django import scipy.sparse from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVR from sklearn.linear_model import LinearRegression, Ridge, LogisticRegression, RidgeClassifier from scipy.spatial.distance import cosine from sklearn.metrics.pairwise import cosi...
recommender.py
import numpy as np import sys import django import scipy.sparse from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVR from sklearn.linear_model import LinearRegression, Ridge, LogisticRegression, RidgeClassifier from scipy.spatial.distance import cosine from sklearn.metrics.pairwise import cosi...
0.563858
0.232136
from typing import List, Optional import torch import torch.nn as nn from torch import Tensor class NeRF(nn.Module): def __init__(self, D: int=8, W: int=256, in_ch_pts: int=63, in_ch_dir: int=27, skips: List[int]=[4] ) -> None: """ NeRF's core MLP model, just the de...
accelRF/models/nerf.py
from typing import List, Optional import torch import torch.nn as nn from torch import Tensor class NeRF(nn.Module): def __init__(self, D: int=8, W: int=256, in_ch_pts: int=63, in_ch_dir: int=27, skips: List[int]=[4] ) -> None: """ NeRF's core MLP model, just the de...
0.951063
0.522933
import cards import time class Player: def __init__(self): self.hand = [] self.handVal = 0 def draw(self, deck, num = 1): pCards = deck.draw(num) for i in pCards: self.hand.append(i) self.handVal = self._calcHandValue() def _calcHandValue(self...
v0 2.5/blackjack.py
import cards import time class Player: def __init__(self): self.hand = [] self.handVal = 0 def draw(self, deck, num = 1): pCards = deck.draw(num) for i in pCards: self.hand.append(i) self.handVal = self._calcHandValue() def _calcHandValue(self...
0.055113
0.14259
from common import * from trezor.crypto import hashlib from trezor.messages.NEMAggregateModification import NEMAggregateModification from trezor.messages.NEMCosignatoryModification import NEMCosignatoryModification from trezor.messages.NEMSignTx import NEMSignTx from trezor.messages.NEMTransactionCommon import NEMTrans...
core/tests/test_apps.nem.multisig.aggregate_modification.py
from common import * from trezor.crypto import hashlib from trezor.messages.NEMAggregateModification import NEMAggregateModification from trezor.messages.NEMCosignatoryModification import NEMCosignatoryModification from trezor.messages.NEMSignTx import NEMSignTx from trezor.messages.NEMTransactionCommon import NEMTrans...
0.57069
0.230302
import matplotlib.pyplot as plt from matplotlib.colors import Normalize from matplotlib.gridspec import GridSpec from matplotlib.ticker import FixedLocator import numpy as np from os import listdir from os.path import join from lvxml2dict import Cluster from namegleaner import NameGleaner from transformer import Transf...
scmoplot/main.py
import matplotlib.pyplot as plt from matplotlib.colors import Normalize from matplotlib.gridspec import GridSpec from matplotlib.ticker import FixedLocator import numpy as np from os import listdir from os.path import join from lvxml2dict import Cluster from namegleaner import NameGleaner from transformer import Transf...
0.431824
0.397938
from netCDF4 import * import pyproj import ogr, osr import numpy as np import time import datetime as dtm def time_block_report(message,told): """ This routine is for reporting incremental timing of parts of the script""" tnew=time.time() diff = tnew - told print("%s : %s" % (message,diff)) retur...
schimpy/cencoos_download.py
from netCDF4 import * import pyproj import ogr, osr import numpy as np import time import datetime as dtm def time_block_report(message,told): """ This routine is for reporting incremental timing of parts of the script""" tnew=time.time() diff = tnew - told print("%s : %s" % (message,diff)) retur...
0.479747
0.256596
import numpy as np from matplotlib import pyplot ''' @author: <NAME> ''' i = 1 N = 20 domainMin = 0 domainMax = N domainSize = 600 def roots() : ''' @return a list of roots for the Wilkinson's polynomial described by i and N. ''' return range(i, N + 1) def domain() : ''' @return a list con...
Wilkinsons.py
import numpy as np from matplotlib import pyplot ''' @author: <NAME> ''' i = 1 N = 20 domainMin = 0 domainMax = N domainSize = 600 def roots() : ''' @return a list of roots for the Wilkinson's polynomial described by i and N. ''' return range(i, N + 1) def domain() : ''' @return a list con...
0.662578
0.605799
import lemoncheesecake.api as lcc from lemoncheesecake.matching import check_that, is_false, is_true, require_that, not_equal_to, equal_to from common.base_test import BaseTest from project import ROPSTEN SUITE = { "description": "Check for updating the list of active committee members" } # todo: test fails at ...
suites/Scenarios/ChangeActiveCommitteeMember.py
import lemoncheesecake.api as lcc from lemoncheesecake.matching import check_that, is_false, is_true, require_that, not_equal_to, equal_to from common.base_test import BaseTest from project import ROPSTEN SUITE = { "description": "Check for updating the list of active committee members" } # todo: test fails at ...
0.205137
0.079854
from dsmtoolkit.load_models import load_model from dsmtoolkit.load_models import represent from dsmtoolkit.load_models import get_nearest_neighbors import sys import os import glob def nn_ranks_to_file(model_paths, year_model, target_word, n): results_dir = f'results/{year_model}_ranks' if not os.path.isdi...
projects/neighbor_stability/nearest_neighbors_ranks.py
from dsmtoolkit.load_models import load_model from dsmtoolkit.load_models import represent from dsmtoolkit.load_models import get_nearest_neighbors import sys import os import glob def nn_ranks_to_file(model_paths, year_model, target_word, n): results_dir = f'results/{year_model}_ranks' if not os.path.isdi...
0.241132
0.141104
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_ScreenLogin(QtWidgets.QWidget): def __init__(self): super().__init__() self.resize(340, 283) self.setStyleSheet("QLabel{color:white;}QRadioButton{color:White;}QPushButton{border:1px solid;border-color:White;color:White;} QPushButton:hover...
Design/login.py
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_ScreenLogin(QtWidgets.QWidget): def __init__(self): super().__init__() self.resize(340, 283) self.setStyleSheet("QLabel{color:white;}QRadioButton{color:White;}QPushButton{border:1px solid;border-color:White;color:White;} QPushButton:hover...
0.293607
0.071267
import logging import os import hashlib from functools import wraps from taskflow import engines import sys sys.path.append('../recovery') from base import AnsibleTask, ShellTask, LinearFlowCreator, UnorderedFlowCreator sys.path.append("../db") from db_Dao import DRGlanceDao, DRNovaDao def task_list(fn): @wraps(...
drcontroller/test/recovery_rollback.py
import logging import os import hashlib from functools import wraps from taskflow import engines import sys sys.path.append('../recovery') from base import AnsibleTask, ShellTask, LinearFlowCreator, UnorderedFlowCreator sys.path.append("../db") from db_Dao import DRGlanceDao, DRNovaDao def task_list(fn): @wraps(...
0.292797
0.081374
# This file contains basic tests for synther library import pytest def test_c_api_buffer_not_found(): import synther synther.set_log_level(synther.LogLvl.VERBOSE) with pytest.raises(Exception, match="Buffer"): synther.get_buffer_bytes(500) with pytest.raises(Exception, match="Buffer"): synther.pro...
tests/synther_test.py
# This file contains basic tests for synther library import pytest def test_c_api_buffer_not_found(): import synther synther.set_log_level(synther.LogLvl.VERBOSE) with pytest.raises(Exception, match="Buffer"): synther.get_buffer_bytes(500) with pytest.raises(Exception, match="Buffer"): synther.pro...
0.469763
0.366165
import torch.nn as nn import torch import numpy as np from time import time from ..utils import * class Griffin_Lim(nn.Module): """ Converting Magnitude spectrograms back to waveforms based on the "fast Griffin-Lim"[1]. This Griffin Lim is a direct clone from librosa.griffinlim. [1] <NAME>., <NAME>.,...
Installation/nnAudio/features/griffin_lim.py
import torch.nn as nn import torch import numpy as np from time import time from ..utils import * class Griffin_Lim(nn.Module): """ Converting Magnitude spectrograms back to waveforms based on the "fast Griffin-Lim"[1]. This Griffin Lim is a direct clone from librosa.griffinlim. [1] <NAME>., <NAME>.,...
0.949619
0.598518
from collections import defaultdict, deque, Counter from itertools import count from pprint import pprint from day import Day, util import numpy as np OCCUPIED = '#' EMPTY = 'L' FLOOR = '.' class Day11Part2(Day): day = 11 part = 2 OFFSETS = ( (0, -1), (0, 1), # left/right (-1, 0), (1, ...
days/day11_part2.py
from collections import defaultdict, deque, Counter from itertools import count from pprint import pprint from day import Day, util import numpy as np OCCUPIED = '#' EMPTY = 'L' FLOOR = '.' class Day11Part2(Day): day = 11 part = 2 OFFSETS = ( (0, -1), (0, 1), # left/right (-1, 0), (1, ...
0.434221
0.145692
import numpy as np class Splitter: """ Train test split Class. """ def __init__(self): """ Constructor for Splitter Class. """ self.x = None self.y = None def fit(self, x: np.ndarray, y: np.ndarray): """ Fits the data to the Splitter object...
src/neural_network/preprocessing/Splitter.py
import numpy as np class Splitter: """ Train test split Class. """ def __init__(self): """ Constructor for Splitter Class. """ self.x = None self.y = None def fit(self, x: np.ndarray, y: np.ndarray): """ Fits the data to the Splitter object...
0.905063
0.84137
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Coupon', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize...
inventory_manager/api/migrations/0001_initial.py
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Coupon', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize...
0.581303
0.173218
from django.db import models from django.utils import timezone from .person import Person from django.utils.translation import gettext_lazy as _ class Order(models.Model): NEW = 'NEW' PENDING = 'PENDING' APPROVED = 'APPROVED' STATE_CHOICES = ( (NEW, 'new'), (PENDING, 'pending'), ...
order/models/order.py
from django.db import models from django.utils import timezone from .person import Person from django.utils.translation import gettext_lazy as _ class Order(models.Model): NEW = 'NEW' PENDING = 'PENDING' APPROVED = 'APPROVED' STATE_CHOICES = ( (NEW, 'new'), (PENDING, 'pending'), ...
0.379838
0.090695
import logging import os from aiohttp.client_exceptions import ClientConnectorError, ClientResponseError import voluptuous as vol from aioautomower import GetAccessToken, GetMowerData, TokenError from homeassistant import data_entry_flow, config_entries from homeassistant.const import ( ATTR_CREDENTIALS, CO...
custom_components/husqvarna_automower/config_flow.py
import logging import os from aiohttp.client_exceptions import ClientConnectorError, ClientResponseError import voluptuous as vol from aioautomower import GetAccessToken, GetMowerData, TokenError from homeassistant import data_entry_flow, config_entries from homeassistant.const import ( ATTR_CREDENTIALS, CO...
0.60743
0.112283
from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import tensorflow as tf import numpy as np import utils import train_data # Some configs num_features = 13 epoch_save_step = 100 # save the checkpoint every # Accounting the 0th indice + space + ...
ctc_tensorflow_multidata_example.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import tensorflow as tf import numpy as np import utils import train_data # Some configs num_features = 13 epoch_save_step = 100 # save the checkpoint every # Accounting the 0th indice + space + ...
0.810479
0.407569
import math import numpy as np import jittor as jt def simple_presum(x): src = ''' __inline_static__ @python.jittor.auto_parallel(1) void kernel(int n0, int i0, in0_type* x, in0_type* out, int nl) { out[i0*(nl+1)] = 0; for (int i=0; i<nl; i++) out[i0*(nl+1)+i+1] = out[i0*(nl+1)+i] + x[i0*nl+i]; } k...
python/jittor/distributions.py
import math import numpy as np import jittor as jt def simple_presum(x): src = ''' __inline_static__ @python.jittor.auto_parallel(1) void kernel(int n0, int i0, in0_type* x, in0_type* out, int nl) { out[i0*(nl+1)] = 0; for (int i=0; i<nl; i++) out[i0*(nl+1)+i+1] = out[i0*(nl+1)+i] + x[i0*nl+i]; } k...
0.390476
0.354712
import pandas def k_nearest_for_query(df,query,k=5): """ 参数:查询字符串query 返回值:满足query中的每一词项都相邻不超过k的文档列表 """ # query = query.lower().split(" ") query = query.split(" ") length=len(query) if(length<=1): print("Error:k_nearest_search need at least two words!") return [] i...
miniSearchEngine/construct_engine/k_nearest_neighbors.py
import pandas def k_nearest_for_query(df,query,k=5): """ 参数:查询字符串query 返回值:满足query中的每一词项都相邻不超过k的文档列表 """ # query = query.lower().split(" ") query = query.split(" ") length=len(query) if(length<=1): print("Error:k_nearest_search need at least two words!") return [] i...
0.071737
0.33039
from app.legal import bp from flask import render_template, flash, redirect, url_for, request, send_from_directory from app import db from app.legal.forms import GenerateIcaForm from app.models import Domain, User, Sentry, Sale, Partner #CountryLead, RegionLead, TeamLead, Sale from flask_login import current_user, logi...
app/legal/routes.py
from app.legal import bp from flask import render_template, flash, redirect, url_for, request, send_from_directory from app import db from app.legal.forms import GenerateIcaForm from app.models import Domain, User, Sentry, Sale, Partner #CountryLead, RegionLead, TeamLead, Sale from flask_login import current_user, logi...
0.35421
0.043978
from abc import ABCMeta, abstractmethod from collections import defaultdict from operator import eq, or_ from toolz.functoolz import curry, flip from itertools import chain from six.moves import reduce class Selector(object): __metaclass__ = ABCMeta @abstractmethod def __eq__(self, other): raise No...
clinvoc/code_collections.py
from abc import ABCMeta, abstractmethod from collections import defaultdict from operator import eq, or_ from toolz.functoolz import curry, flip from itertools import chain from six.moves import reduce class Selector(object): __metaclass__ = ABCMeta @abstractmethod def __eq__(self, other): raise No...
0.781038
0.169509
from flask import Flask, url_for, render_template, Markup import httplib import re from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter app = Flask(__name__) app.config.from_pyfile('application.cfg') base_url = app.config['BASE_URL'] base_path = ap...
log_highlighter.py
from flask import Flask, url_for, render_template, Markup import httplib import re from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter app = Flask(__name__) app.config.from_pyfile('application.cfg') base_url = app.config['BASE_URL'] base_path = ap...
0.487551
0.04597
import datetime from typing import Tuple from django.conf.urls import url from django.test import TestCase from pip._vendor import requests import random import json from rest_framework import status # Create your tests here. class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN ...
sflcontrol/sflc/Tests/transaction.py
import datetime from typing import Tuple from django.conf.urls import url from django.test import TestCase from pip._vendor import requests import random import json from rest_framework import status # Create your tests here. class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN ...
0.31363
0.093471
from __future__ import print_function import filecmp import os import stat import shutil import llnl.util.tty as tty from llnl.util.filesystem import mkdirp, touch, traverse_tree __all__ = ['LinkTree'] empty_file_name = '.spack-empty' def remove_link(src, dest): if not os.path.islink(dest): raise Valu...
lib/spack/llnl/util/link_tree.py
from __future__ import print_function import filecmp import os import stat import shutil import llnl.util.tty as tty from llnl.util.filesystem import mkdirp, touch, traverse_tree __all__ = ['LinkTree'] empty_file_name = '.spack-empty' def remove_link(src, dest): if not os.path.islink(dest): raise Valu...
0.394901
0.121009
import unittest from nebulizer.tools import Tool from nebulizer.tools import Repository from nebulizer.tools import ToolPanelSection from nebulizer.tools import handle_repository_spec from nebulizer.tools import normalise_toolshed_url class TestTool(unittest.TestCase): """ Tests for the 'Tool' class """ ...
test/test_tools.py
import unittest from nebulizer.tools import Tool from nebulizer.tools import Repository from nebulizer.tools import ToolPanelSection from nebulizer.tools import handle_repository_spec from nebulizer.tools import normalise_toolshed_url class TestTool(unittest.TestCase): """ Tests for the 'Tool' class """ ...
0.441553
0.357652
import cidc_api from datetime import datetime import json import os import pytest from unittest.mock import MagicMock from cidc_api.models.models import ( TrialMetadata, UploadJobs, Users, ) from cidc_api.models.templates import ClinicalTrial from cidc_api.models.templates.sync_schemas import ( _make_s...
tests/models/templates/test_sync_schemas.py
import cidc_api from datetime import datetime import json import os import pytest from unittest.mock import MagicMock from cidc_api.models.models import ( TrialMetadata, UploadJobs, Users, ) from cidc_api.models.templates import ClinicalTrial from cidc_api.models.templates.sync_schemas import ( _make_s...
0.323594
0.220217
import shutil from typing import List import typer from wasabi import msg from pytoil.cli import utils from pytoil.config import Config app = typer.Typer() @app.command() def remove( projects: List[str] = typer.Argument( None, help="Name of the project(s) to delete.", show_default=False...
pytoil/cli/remove.py
import shutil from typing import List import typer from wasabi import msg from pytoil.cli import utils from pytoil.config import Config app = typer.Typer() @app.command() def remove( projects: List[str] = typer.Argument( None, help="Name of the project(s) to delete.", show_default=False...
0.526343
0.328381
import os from slugify import slugify services = [ { 'service': 'pumpwood-frontend', 'endpoint': [ '/gui/', ] }, { 'service': 'pumpwood-auth-app', 'health-check': True, 'admin': True, 'endpoint': [ '/rest/registration/', ...
build/lib/pumpwood_deploy/endpoint_services/endpoint_services.py
import os from slugify import slugify services = [ { 'service': 'pumpwood-frontend', 'endpoint': [ '/gui/', ] }, { 'service': 'pumpwood-auth-app', 'health-check': True, 'admin': True, 'endpoint': [ '/rest/registration/', ...
0.36727
0.066539
symbols = [ "!", "#!#", "#?#", "$", "$_goal_$", "%", "%%", "*", "*_c", "+", "++", "+_c", ",", "-", "--->", "-->", "..", "////", "/\\", "<", "<<", "<<<", "<=", "<=_c", "<_c", "=", "==", "==>", "=_c", "...
symbols.py
symbols = [ "!", "#!#", "#?#", "$", "$_goal_$", "%", "%%", "*", "*_c", "+", "++", "+_c", ",", "-", "--->", "-->", "..", "////", "/\\", "<", "<<", "<<<", "<=", "<=_c", "<_c", "=", "==", "==>", "=_c", "...
0.221856
0.429549
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Component", fields=[ ( "id", models.AutoField( ...
web/system/migrations/0001_initial.py
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Component", fields=[ ( "id", models.AutoField( ...
0.695338
0.231093
import json import requests import pykintone.structure as ps from pykintone.application_settings.base_administration_api import BaseAdministrationAPI import pykintone.application_settings.setting_result as sr class Administrator(BaseAdministrationAPI): def __init__(self, account, api_token="", requests_options=(...
pykintone/application_settings/administrator.py
import json import requests import pykintone.structure as ps from pykintone.application_settings.base_administration_api import BaseAdministrationAPI import pykintone.application_settings.setting_result as sr class Administrator(BaseAdministrationAPI): def __init__(self, account, api_token="", requests_options=(...
0.368974
0.113309
import pytz import datetime import time import yaml import argparse from pathlib import Path import datetime from disneyScrayper import DisneyScraper from reserveInfo import get_reserveInfo, get_ticketInfo from alertSystem import AlertReserveStatus from config import ConfigInfo def get_argument(): parser = argpa...
main.py
import pytz import datetime import time import yaml import argparse from pathlib import Path import datetime from disneyScrayper import DisneyScraper from reserveInfo import get_reserveInfo, get_ticketInfo from alertSystem import AlertReserveStatus from config import ConfigInfo def get_argument(): parser = argpa...
0.309024
0.086323
import atexit import logging import os import smtplib import sys from datetime import datetime from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import durationpy import yaml from apscheduler.schedulers.blocking import BlockingScheduler from requ...
app.py
import atexit import logging import os import smtplib import sys from datetime import datetime from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import durationpy import yaml from apscheduler.schedulers.blocking import BlockingScheduler from requ...
0.175326
0.063861
from collections import OrderedDict from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64 from ydk.filters import YFilter from ydk.errors import YError, YModelError from ydk.errors.error_handler import handle_type_error as _handle_type_error cl...
cisco-ios-xe/ydk/models/cisco_ios_xe/Cisco_IOS_XE_ntp_oper.py
from collections import OrderedDict from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64 from ydk.filters import YFilter from ydk.errors import YError, YModelError from ydk.errors.error_handler import handle_type_error as _handle_type_error cl...
0.63443
0.510924
import tkinter as tk import tkinter.scrolledtext as st import json import os selectedItem = [] project = [['new item', "description", ['tags'], 'white', 'more information']] selectedIndex = 0 bg = '#C5C5C5' def loadProject(filename='data.json'): if not os.path.exists(filename): json.dump(project, open(...
session5/ibox.py
import tkinter as tk import tkinter.scrolledtext as st import json import os selectedItem = [] project = [['new item', "description", ['tags'], 'white', 'more information']] selectedIndex = 0 bg = '#C5C5C5' def loadProject(filename='data.json'): if not os.path.exists(filename): json.dump(project, open(...
0.209631
0.074736
import argparse import os import os.path as osp import torch from vedacore.misc import Config, load_weights, ProgressBar, mkdir_or_exist from configs.trainval.tinaface.test_widerface import prepare import matplotlib.pyplot as plt def parse_args(): parser = argparse.ArgumentParser(description='Train a detector') ...
configs/trainval/tinaface_masked/test_mafa.py
import argparse import os import os.path as osp import torch from vedacore.misc import Config, load_weights, ProgressBar, mkdir_or_exist from configs.trainval.tinaface.test_widerface import prepare import matplotlib.pyplot as plt def parse_args(): parser = argparse.ArgumentParser(description='Train a detector') ...
0.442877
0.209551
import os, unittest from State import State from model import regression states = ['Alaska','Alabama','Arkansas', 'Arizona','California','Colorado', 'Connecticut','Delaware','Florida','Georgia','Hawaii','Iowa','Idaho', 'Illinois','Indiana','Kansas','Kentucky','Louisiana','Massachusetts','Maryland', 'Maine','Mich...
artifacts/tests/backend_tests/test-U029.py
import os, unittest from State import State from model import regression states = ['Alaska','Alabama','Arkansas', 'Arizona','California','Colorado', 'Connecticut','Delaware','Florida','Georgia','Hawaii','Iowa','Idaho', 'Illinois','Indiana','Kansas','Kentucky','Louisiana','Massachusetts','Maryland', 'Maine','Mich...
0.28897
0.388792
from pythonian import * import logging import time logger = logging.getLogger('TestAgent') class TestAgent(Pythonian): name = "TestAgent" # This is the name of the agent to register with def __init__(self, **kwargs): super(TestAgent, self).__init__(**kwargs) self.add_ask('test_ask_return_list...
archive/test_agent_old.py
from pythonian import * import logging import time logger = logging.getLogger('TestAgent') class TestAgent(Pythonian): name = "TestAgent" # This is the name of the agent to register with def __init__(self, **kwargs): super(TestAgent, self).__init__(**kwargs) self.add_ask('test_ask_return_list...
0.412767
0.340156
from __future__ import annotations from typing import Any from typing import Dict from typing import List from typing import NamedTuple from typing import Optional import peony.exceptions from peony import PeonyClient class ClientException(Exception): pass class UserNotFound(ClientException): def __init__...
tothc/clients/twitter.py
from __future__ import annotations from typing import Any from typing import Dict from typing import List from typing import NamedTuple from typing import Optional import peony.exceptions from peony import PeonyClient class ClientException(Exception): pass class UserNotFound(ClientException): def __init__...
0.838696
0.116663
import numpy as np import json import matplotlib.pyplot as plt from PIL import Image import seaborn as sns sns.set(font_scale=1.5, style='white') from sklearn.utils import compute_class_weight from sklearn.metrics import classification_report, confusion_matrix, roc_curve, roc_auc_score, precision_recall_curve, auc, f1...
covid/metrics.py
import numpy as np import json import matplotlib.pyplot as plt from PIL import Image import seaborn as sns sns.set(font_scale=1.5, style='white') from sklearn.utils import compute_class_weight from sklearn.metrics import classification_report, confusion_matrix, roc_curve, roc_auc_score, precision_recall_curve, auc, f1...
0.697506
0.446676
import matplotlib.pyplot as plt import seaborn as sns sns.set_style('dark') #SCN modules import functions.statistical_functions as Sfun def distro_plots(data): ''' Wrapper function around sns.histplots to plot the distibution of clustering, shortest_path, assortativity, modularity and efficiency. ...
functions/plotting_functions.py
import matplotlib.pyplot as plt import seaborn as sns sns.set_style('dark') #SCN modules import functions.statistical_functions as Sfun def distro_plots(data): ''' Wrapper function around sns.histplots to plot the distibution of clustering, shortest_path, assortativity, modularity and efficiency. ...
0.824144
0.702908
import os import json from argparse import ArgumentParser from cbm3_aws import log_helper from cbm3_aws.namespace import Namespace from cbm3_aws.aws import execution def main(): parser = ArgumentParser( description="Starts an execution on a cbm3_aws cluster") parser.add_argument( "--resource...
cbm3_aws/scripts/start_execution.py
import os import json from argparse import ArgumentParser from cbm3_aws import log_helper from cbm3_aws.namespace import Namespace from cbm3_aws.aws import execution def main(): parser = ArgumentParser( description="Starts an execution on a cbm3_aws cluster") parser.add_argument( "--resource...
0.465387
0.105073
import os import json import codecs # NER def struct_to_bio(args): struct_ann_path = args.struct_ann_path output_dir = args.output_dir oversampling_rate = args.oversampling_rate separate_docs = args.separate_docs bio_dict = struct_to_bio_dict(struct_ann_path, oversampling_rate) if not os.pa...
medtrialextractor/formatting/struct_to_bio.py
import os import json import codecs # NER def struct_to_bio(args): struct_ann_path = args.struct_ann_path output_dir = args.output_dir oversampling_rate = args.oversampling_rate separate_docs = args.separate_docs bio_dict = struct_to_bio_dict(struct_ann_path, oversampling_rate) if not os.pa...
0.269614
0.197328
import os import sys from functools import partial import numpy as np import torch from torch.distributions import Normal base_path = os.path.join(os.path.dirname(__file__), "..") if not base_path in sys.path: sys.path.append(base_path) from gptorch.model import Model from gptorch.param import Param from gptorch...
test/test_model.py
import os import sys from functools import partial import numpy as np import torch from torch.distributions import Normal base_path = os.path.join(os.path.dirname(__file__), "..") if not base_path in sys.path: sys.path.append(base_path) from gptorch.model import Model from gptorch.param import Param from gptorch...
0.609989
0.349227
from random import randrange import json import glob import os def import_quizlet_lineskip_fix(filepath, fbsep="\t", cardsep="\n"): """ Take a Quizlet flashcard export either that by default uses tab for card front and back, and linebreak for new card, or a custom export that uses custom characters to separat...
Flashcards_0.3.py
from random import randrange import json import glob import os def import_quizlet_lineskip_fix(filepath, fbsep="\t", cardsep="\n"): """ Take a Quizlet flashcard export either that by default uses tab for card front and back, and linebreak for new card, or a custom export that uses custom characters to separat...
0.455441
0.283135
import math from collections.abc import Iterable class Welford(): """Accumulator object for Welfords online variance algorithm.""" def __init__(self, data=None): """Initialize with an optional data. Data can be a scalar value or an iterable of values.""" self.__count = 0 self.__m1 = 0....
welford.py
import math from collections.abc import Iterable class Welford(): """Accumulator object for Welfords online variance algorithm.""" def __init__(self, data=None): """Initialize with an optional data. Data can be a scalar value or an iterable of values.""" self.__count = 0 self.__m1 = 0....
0.907758
0.534127
import unittest from solumdashboard.common import workflow_parsers MISTRAL_DSL = { "Namespaces": { "Nova": { "actions": "random data" } }, "Workflow": { "tasks": { "createVM": { "action": "Nova.createVM", "parameters": { ...
solumdashboard/tests/common/test_workflow_parsers.py
import unittest from solumdashboard.common import workflow_parsers MISTRAL_DSL = { "Namespaces": { "Nova": { "actions": "random data" } }, "Workflow": { "tasks": { "createVM": { "action": "Nova.createVM", "parameters": { ...
0.665519
0.477981
from shapenet.layer.homogeneous_transform_layer import \ HomogeneousTransformationLayer, \ _HomogeneousTransformationLayerCpp, \ _HomogeneousTransformationLayerPy import torch def test_homogeneous_transform_layer(): shapes_2d = torch.rand(10, 68, 2, requires_grad=True) rotation_params_2d = torch.r...
tests/layer/test_homogeneous_transform_layer.py
from shapenet.layer.homogeneous_transform_layer import \ HomogeneousTransformationLayer, \ _HomogeneousTransformationLayerCpp, \ _HomogeneousTransformationLayerPy import torch def test_homogeneous_transform_layer(): shapes_2d = torch.rand(10, 68, 2, requires_grad=True) rotation_params_2d = torch.r...
0.725843
0.682005
import numpy as np import pytest import pyccl as ccl COSMO = ccl.Cosmology( Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96, transfer_function='bbks', matter_power_spectrum='linear') COSMO_NU = ccl.Cosmology( Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96, transfer_function='bbks...
pyccl/tests/test_background.py
import numpy as np import pytest import pyccl as ccl COSMO = ccl.Cosmology( Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96, transfer_function='bbks', matter_power_spectrum='linear') COSMO_NU = ccl.Cosmology( Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96, transfer_function='bbks...
0.543833
0.385375
from datetime import datetime from django.http import HttpResponse from django.http import HttpResponseRedirect from django.http import HttpResponseServerError from django.shortcuts import render from django.urls import reverse from django.views import View from leancloud import Object from leancloud import Query fro...
views.py
from datetime import datetime from django.http import HttpResponse from django.http import HttpResponseRedirect from django.http import HttpResponseServerError from django.shortcuts import render from django.urls import reverse from django.views import View from leancloud import Object from leancloud import Query fro...
0.412648
0.073863
"""Kernel Density Estimation (KDE) for Unsupervised Outlier Detection. """ # Author: <NAME> <<EMAIL>> # License: BSD 2 clause from __future__ import division, print_function from warnings import warn from sklearn.neighbors import KernelDensity from sklearn.utils import check_array from sklearn.utils.validation impor...
pyod/models/kde.py
"""Kernel Density Estimation (KDE) for Unsupervised Outlier Detection. """ # Author: <NAME> <<EMAIL>> # License: BSD 2 clause from __future__ import division, print_function from warnings import warn from sklearn.neighbors import KernelDensity from sklearn.utils import check_array from sklearn.utils.validation impor...
0.969685
0.808294
import unittest import os from tests.setup_scripts import ring_road_exp_setup from flow.core.params import EnvParams from flow.core.vehicles import Vehicles from flow.core.rewards import average_velocity, total_velocity, \ desired_velocity os.environ["TEST_FLAG"] = "True" class TestRewards(unittest.TestCase): ...
tests/fast_tests/test_rewards.py
import unittest import os from tests.setup_scripts import ring_road_exp_setup from flow.core.params import EnvParams from flow.core.vehicles import Vehicles from flow.core.rewards import average_velocity, total_velocity, \ desired_velocity os.environ["TEST_FLAG"] = "True" class TestRewards(unittest.TestCase): ...
0.794505
0.622
from queue import Queue import numpy as np import pandas as pd from .problem import Problem class Solver: def __init__(self): pass def solve(self, problem: Problem): # 初期化 cells = problem.cells.copy() H, W = cells.shape sy, sx = -1, -1 n_foods = 0 fo...
problem/solve.py
from queue import Queue import numpy as np import pandas as pd from .problem import Problem class Solver: def __init__(self): pass def solve(self, problem: Problem): # 初期化 cells = problem.cells.copy() H, W = cells.shape sy, sx = -1, -1 n_foods = 0 fo...
0.338296
0.371308
import inspect from functools import partial from numba.experimental import structref from numba.core import types from africanus.experimental.rime.fused.error import InvalidSignature @structref.register class StateStructRef(types.StructRef): def preprocess_fields(self, fields): """ Disallow literal typ...
africanus/experimental/rime/fused/terms/core.py
import inspect from functools import partial from numba.experimental import structref from numba.core import types from africanus.experimental.rime.fused.error import InvalidSignature @structref.register class StateStructRef(types.StructRef): def preprocess_fields(self, fields): """ Disallow literal typ...
0.786541
0.466238
from scs_host.bus.i2c import I2C from scs_psu.psu.opcube_v1.psu_status import ChargerStatus # -------------------------------------------------------------------------------------------------------------------- class PCA9534(object): """ Texas Instruments PCA9534A remote 8-bit I/O expander """ DEFA...
src/scs_psu/psu/opcube_v1/pca9534.py
from scs_host.bus.i2c import I2C from scs_psu.psu.opcube_v1.psu_status import ChargerStatus # -------------------------------------------------------------------------------------------------------------------- class PCA9534(object): """ Texas Instruments PCA9534A remote 8-bit I/O expander """ DEFA...
0.326057
0.12749
from pprint import pformat from six import iteritems import re class Traveler(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name ...
travel/docs/Amadeus-master/pactravel-master/swagger_client/models/traveler.py
from pprint import pformat from six import iteritems import re class Traveler(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name ...
0.73412
0.210178
import django.contrib.auth.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( ...
backend/backadmin/migrations/0001_initial.py
import django.contrib.auth.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( ...
0.497559
0.268216
import tensorflow as tf from tensorflow import keras print(tf.VERSION) print(tf.keras.__version__) from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.inception_v3 import preprocess_input from tensorflow.keras.models import Model from tensorflow.keras import backend as K import matplo...
predict.py
import tensorflow as tf from tensorflow import keras print(tf.VERSION) print(tf.keras.__version__) from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.inception_v3 import preprocess_input from tensorflow.keras.models import Model from tensorflow.keras import backend as K import matplo...
0.292292
0.205595
import shutil import unittest from pysp.sbasic import SFile from pysp.serror import SDebug from pysp.sconf import SConfig class Expected: default_vehicle = ''' car: sedan: SM6: transmission: cvt suv: QM6: transmission: cvt '''.strip() user_vehicle = ''' car: ...
test/test_sconf_sconfig.py
import shutil import unittest from pysp.sbasic import SFile from pysp.serror import SDebug from pysp.sconf import SConfig class Expected: default_vehicle = ''' car: sedan: SM6: transmission: cvt suv: QM6: transmission: cvt '''.strip() user_vehicle = ''' car: ...
0.335351
0.304287
from unittest import mock import cv2 import pytest from ..utils import is_valid_rtsp, normalize_rtsp, verify_rtsp @pytest.mark.parametrize( "rtsp_str, output", [ [0, True], ["0", True], [1, True], ["1", True], [2, False], ["2", False], ["RTSP://QQ", Tr...
factory-ai-vision/EdgeSolution/modules/WebModule/backend/vision_on_edge/cameras/tests/test_utils.py
from unittest import mock import cv2 import pytest from ..utils import is_valid_rtsp, normalize_rtsp, verify_rtsp @pytest.mark.parametrize( "rtsp_str, output", [ [0, True], ["0", True], [1, True], ["1", True], [2, False], ["2", False], ["RTSP://QQ", Tr...
0.712132
0.553988
import json from django.contrib.auth.decorators import login_required from django.core import serializers from django.http import HttpResponse, JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from core.models import Subject, Students, SessionYear, Attendance, Atte...
core/views_staff.py
import json from django.contrib.auth.decorators import login_required from django.core import serializers from django.http import HttpResponse, JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from core.models import Subject, Students, SessionYear, Attendance, Atte...
0.359477
0.075414
import numpy as np def check_images(fusioned, original): assert len(fusioned) == len(original), "Supplied images have different sizes " + \ str(fusioned.shape) + " and " + str(original.shape) if(len(fusioned.shape) == len(original.shape)): estado = 'mtom' if(len(fusioned.shape) == 2): ...
sallfus/measures.py
import numpy as np def check_images(fusioned, original): assert len(fusioned) == len(original), "Supplied images have different sizes " + \ str(fusioned.shape) + " and " + str(original.shape) if(len(fusioned.shape) == len(original.shape)): estado = 'mtom' if(len(fusioned.shape) == 2): ...
0.442637
0.797537
import os import datetime from abc import ABC from collections import OrderedDict, namedtuple from contextlib import contextmanager import sqlite3 from .datatypes import DerivedKeySetup ProjectInfo = namedtuple('ProjectInfo', 'name base_path num_files') class Constraint: def __init__(self, this_column, other_t...
aws_glacier_manager/database.py
import os import datetime from abc import ABC from collections import OrderedDict, namedtuple from contextlib import contextmanager import sqlite3 from .datatypes import DerivedKeySetup ProjectInfo = namedtuple('ProjectInfo', 'name base_path num_files') class Constraint: def __init__(self, this_column, other_t...
0.622345
0.102394
import os import pickle from argparse import ArgumentParser import compress_pickle def absolute_file_paths(directory: str): """ Function to get all the absolute path of files into a directory. :param directory: The directory to yield all the absolute file paths from. :return: Yield all the path in ...
lzma_decompress.py
import os import pickle from argparse import ArgumentParser import compress_pickle def absolute_file_paths(directory: str): """ Function to get all the absolute path of files into a directory. :param directory: The directory to yield all the absolute file paths from. :return: Yield all the path in ...
0.611962
0.16378
from functools import wraps from flask import abort from flask import Blueprint from flask import current_app from flask_restful import Api from flask_restful import Resource from flask_restful import reqparse import itsdangerous from sqlalchemy.orm.exc import NoResultFound from werkzeug.datastructures import FileStor...
flask_pblog/resources.py
from functools import wraps from flask import abort from flask import Blueprint from flask import current_app from flask_restful import Api from flask_restful import Resource from flask_restful import reqparse import itsdangerous from sqlalchemy.orm.exc import NoResultFound from werkzeug.datastructures import FileStor...
0.619471
0.09472
import imageio import torch import time from tqdm import tqdm from animate import normalize_kp from demo import load_checkpoints import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from skimage import img_as_ubyte from skimage.transform import resize import cv2 import os import a...
src/renderer/python/image_animation.py
import imageio import torch import time from tqdm import tqdm from animate import normalize_kp from demo import load_checkpoints import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from skimage import img_as_ubyte from skimage.transform import resize import cv2 import os import a...
0.225331
0.119126
import os import pandas as pd import requests from typing import Dict import requests import json from dotenv import load_dotenv load_dotenv() URL = 'https://www.googleapis.com/youtube/v3/' API_KEY = os.getenv('API_KEY') PLAYLIST_ID = os.getenv('PLAYLIST_ID') # 1つ目の動画のコメント情報を取得 # VIDEO_ID = '1vAUY1qNF1Q' # CHANNEL_...
main.py
import os import pandas as pd import requests from typing import Dict import requests import json from dotenv import load_dotenv load_dotenv() URL = 'https://www.googleapis.com/youtube/v3/' API_KEY = os.getenv('API_KEY') PLAYLIST_ID = os.getenv('PLAYLIST_ID') # 1つ目の動画のコメント情報を取得 # VIDEO_ID = '1vAUY1qNF1Q' # CHANNEL_...
0.129306
0.060169
import werkzeug.security from werkzeug.utils import secure_filename from flask import render_template, redirect, url_for, flash, request from flask_login import LoginManager, current_user, login_required, logout_user, login_user from flask_bootstrap import Bootstrap from gallery import app, db, models from gallery.form...
gallery/views.py
import werkzeug.security from werkzeug.utils import secure_filename from flask import render_template, redirect, url_for, flash, request from flask_login import LoginManager, current_user, login_required, logout_user, login_user from flask_bootstrap import Bootstrap from gallery import app, db, models from gallery.form...
0.240239
0.074097
import sys import torch import torch.nn.functional as F import os import argparse import copy import nibabel as nib import numpy as np import math from models.segtran_modified.code.networks.segtran3d import Segtran3d, set_segtran3d_config, CONFIG from models.gan_based_unet.multiscale_generator import MultiscaleGenerat...
app/model_controller/model_loader.py
import sys import torch import torch.nn.functional as F import os import argparse import copy import nibabel as nib import numpy as np import math from models.segtran_modified.code.networks.segtran3d import Segtran3d, set_segtran3d_config, CONFIG from models.gan_based_unet.multiscale_generator import MultiscaleGenerat...
0.35209
0.173656
from logging import Logger import numpy as np import os import time from typing_extensions import Literal # noinspection PyPackageRequirements from tap import Tap from tqdm import tqdm from conformation.funnel_sampler import funnel_pdf, funnel_sample from conformation.gmm_sampler import gmm_pdf, gmm_sample...
conformation/basic_metropolis.py
from logging import Logger import numpy as np import os import time from typing_extensions import Literal # noinspection PyPackageRequirements from tap import Tap from tqdm import tqdm from conformation.funnel_sampler import funnel_pdf, funnel_sample from conformation.gmm_sampler import gmm_pdf, gmm_sample...
0.717903
0.185652
class ConsoleColors: """Console colors and formats""" ResetAll = "\033[0m" Bold = "\033[1m" Dim = "\033[2m" Underlined = "\033[4m" Blink = "\033[5m" Reverse = "\033[7m" Hidden = "\033[8m" ResetBold = "\033[21m" ResetDim = "\033[22m" ResetUnderlined = "\033[24m" Re...
console.py
class ConsoleColors: """Console colors and formats""" ResetAll = "\033[0m" Bold = "\033[1m" Dim = "\033[2m" Underlined = "\033[4m" Blink = "\033[5m" Reverse = "\033[7m" Hidden = "\033[8m" ResetBold = "\033[21m" ResetDim = "\033[22m" ResetUnderlined = "\033[24m" Re...
0.588534
0.095941
import textwrap import pickle import re def process_body(doc_pickle_file, output_file): document_body = None with open(doc_pickle_file, 'rb') as body_pickle: document_body = pickle.load(body_pickle) with open(output_file, 'w') as output: MarkdownConverter(document_body, output) c...
converters/markdown.py
import textwrap import pickle import re def process_body(doc_pickle_file, output_file): document_body = None with open(doc_pickle_file, 'rb') as body_pickle: document_body = pickle.load(body_pickle) with open(output_file, 'w') as output: MarkdownConverter(document_body, output) c...
0.155174
0.055566
import pickle import h5py import numpy as np import sklearn import sklearn.decomposition import sklearn.linear_model import sklearn.preprocessing from fastprogress.fastprogress import force_console_behavior import mabe import mabe.config import mabe.loss import mabe.model import mabe.ringbuffer # %% num_splits = 32 ...
hydrogen/create_splits.py
import pickle import h5py import numpy as np import sklearn import sklearn.decomposition import sklearn.linear_model import sklearn.preprocessing from fastprogress.fastprogress import force_console_behavior import mabe import mabe.config import mabe.loss import mabe.model import mabe.ringbuffer # %% num_splits = 32 ...
0.386532
0.291422