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 mxnet as mx
from mxnet import gluon,nd,ndarray
from mxnet.gluon import nn
def _reshape_like(F, x, y):
"""Reshapes x to the same shape as y."""
return x.reshape(y.shape) if F is ndarray else F.reshape_like(x, y)
def _apply_weighting(F, loss, weight=None, sample_weight=None):
if sample_weight is no... | DeepTCN/electricity/NewTCNQuantile/nnModels.py |
import mxnet as mx
from mxnet import gluon,nd,ndarray
from mxnet.gluon import nn
def _reshape_like(F, x, y):
"""Reshapes x to the same shape as y."""
return x.reshape(y.shape) if F is ndarray else F.reshape_like(x, y)
def _apply_weighting(F, loss, weight=None, sample_weight=None):
if sample_weight is no... | 0.902563 | 0.495606 |
# ---------------------------------------------------------------------------
# Copyright 2017-2018 OMRON Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://w... | p2def.py | # ---------------------------------------------------------------------------
# Copyright 2017-2018 OMRON Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://w... | 0.603231 | 0.072308 |
import argparse
import os
# - Inputs
# * API Key
# * Extractor Id
# * Output directory
# * file naming format
# - Outputs
# * File in file system
class AdBase(object):
def __init__(self):
self._parser = argparse.ArgumentParser(description=self.cli_description())
self._args = None
... | importio2/commands/ad_base.py |
import argparse
import os
# - Inputs
# * API Key
# * Extractor Id
# * Output directory
# * file naming format
# - Outputs
# * File in file system
class AdBase(object):
def __init__(self):
self._parser = argparse.ArgumentParser(description=self.cli_description())
self._args = None
... | 0.587707 | 0.061087 |
from traceback import print_exc
class TestException(Exception):
pass
def check_raises(*args, **kwargs):
"""
check_raises(exception_type, function, ...)
Calls function, passing in the rest of the positional arguments and keyword
arguments. If the function does not raise an exception, check_ra... | notifier/parcon/testframework.py | from traceback import print_exc
class TestException(Exception):
pass
def check_raises(*args, **kwargs):
"""
check_raises(exception_type, function, ...)
Calls function, passing in the rest of the positional arguments and keyword
arguments. If the function does not raise an exception, check_ra... | 0.572962 | 0.317704 |
import os
import boto3
import pytest
from assertpy import assert_that
from pcluster.cli_commands.compute_fleet_status_manager import ComputeFleetStatus, ComputeFleetStatusManager
class TestComputeFleetStatusManager:
@pytest.fixture
def compute_fleet_status_manager(self, mocker):
if "AWS_DEFAULT_REGI... | cli/tests/pcluster/cli_commands/test_compute_fleet_status_manager.py | import os
import boto3
import pytest
from assertpy import assert_that
from pcluster.cli_commands.compute_fleet_status_manager import ComputeFleetStatus, ComputeFleetStatusManager
class TestComputeFleetStatusManager:
@pytest.fixture
def compute_fleet_status_manager(self, mocker):
if "AWS_DEFAULT_REGI... | 0.438304 | 0.235438 |
import os
class PexData:
offset: int
data: bytes
value: object
class PexInt(PexData):
value: int
class PexStr(PexData):
value: str
class PexHeader:
magic: PexInt = PexInt()
major_version: PexInt = PexInt()
minor_version: PexInt = PexInt()
game_id: PexInt ... | pyro/PexReader.py | import os
class PexData:
offset: int
data: bytes
value: object
class PexInt(PexData):
value: int
class PexStr(PexData):
value: str
class PexHeader:
magic: PexInt = PexInt()
major_version: PexInt = PexInt()
minor_version: PexInt = PexInt()
game_id: PexInt ... | 0.248899 | 0.285335 |
import copy
import operator
import unittest
from pykit import dictutil
from pykit import ututil
dd = ututil.dd
class TestDictDeepIter(unittest.TestCase):
def test_depth_iter_default(self):
cases = (
({}, []),
({'k1': 'v1'},
[(['k1'], 'v1')]
),
... | dictutil/test/test_dictutil.py |
import copy
import operator
import unittest
from pykit import dictutil
from pykit import ututil
dd = ututil.dd
class TestDictDeepIter(unittest.TestCase):
def test_depth_iter_default(self):
cases = (
({}, []),
({'k1': 'v1'},
[(['k1'], 'v1')]
),
... | 0.565779 | 0.372905 |
import requests
from bs4 import BeautifulSoup
import datetime
import pandas as pd
import urllib
import csv
HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',
'Host': 's.weibo.com',
#"Cookie": "_T_WM=0364d13... | WeiboSpider/GetURL.py | import requests
from bs4 import BeautifulSoup
import datetime
import pandas as pd
import urllib
import csv
HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',
'Host': 's.weibo.com',
#"Cookie": "_T_WM=0364d13... | 0.120918 | 0.068351 |
import numpy as np
from data.const import NONE
def build_vocab(labels, PAD, BIO_tagging=True, padding=True):
""" build vocabulary for labels """
if padding:
all_labels = [PAD, NONE]
else:
all_labels = []
for label in labels:
if BIO_tagging:
all_labels.appen... | utils/helper_functions.py | import numpy as np
from data.const import NONE
def build_vocab(labels, PAD, BIO_tagging=True, padding=True):
""" build vocabulary for labels """
if padding:
all_labels = [PAD, NONE]
else:
all_labels = []
for label in labels:
if BIO_tagging:
all_labels.appen... | 0.387574 | 0.402598 |
"""Local CPU benchmarks for collective ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session
from tensorflow.python.framework imp... | tensorflow/python/ops/collective_ops_benchmark.py | """Local CPU benchmarks for collective ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session
from tensorflow.python.framework imp... | 0.876714 | 0.189972 |
import datetime
import decimal
import logging
import uuid
import warnings
from django.conf import settings
from django.db.backends.base.base import BaseDatabaseWrapper
from django.db.backends.base.client import BaseDatabaseClient
from django.db.backends.base.creation import BaseDatabaseCreation
from django.db.backends... | djangae/db/backends/appengine/base.py | import datetime
import decimal
import logging
import uuid
import warnings
from django.conf import settings
from django.db.backends.base.base import BaseDatabaseWrapper
from django.db.backends.base.client import BaseDatabaseClient
from django.db.backends.base.creation import BaseDatabaseCreation
from django.db.backends... | 0.480235 | 0.060696 |
import numpy as np
import os
import argparse
import cv2
import numpy as np
from src.base import Base
from src.load_config import load_yml
from src.misc_utils import attach_file_suffix, f1, f2, binaryzation
import skimage
if skimage.__version__.startswith('0.16'):
from skimage.metrics import peak_signal_noise_rat... | src/evaluate.py |
import numpy as np
import os
import argparse
import cv2
import numpy as np
from src.base import Base
from src.load_config import load_yml
from src.misc_utils import attach_file_suffix, f1, f2, binaryzation
import skimage
if skimage.__version__.startswith('0.16'):
from skimage.metrics import peak_signal_noise_rat... | 0.465873 | 0.157428 |
import os
import dj_database_url
import django_heroku
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# Quick-start development settings - unsuitable for production... | mysite/settings.py | import os
import dj_database_url
import django_heroku
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# Quick-start development settings - unsuitable for production... | 0.433981 | 0.093182 |
import os
import glob
import random
from PIL import Image
import numpy as np
import torch.utils.data as tud
from utils import depthmap_utils
class DeMoNDataset(tud.Dataset):
"""Dataset class for DeMoN data based on the implementation in DPSNet.
Assumes data is organized as follows:
root/scene_1/000... | datasets/demon_dataset.py |
import os
import glob
import random
from PIL import Image
import numpy as np
import torch.utils.data as tud
from utils import depthmap_utils
class DeMoNDataset(tud.Dataset):
"""Dataset class for DeMoN data based on the implementation in DPSNet.
Assumes data is organized as follows:
root/scene_1/000... | 0.627951 | 0.590012 |
from django.core import paginator
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView
from django.core.paginator import Paginator, EmptyPage,\
PageNotAnInteger
from .forms import EmailPostForm, CommentForm
from django.core.mail import send_m... | blog/views.py | from django.core import paginator
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView
from django.core.paginator import Paginator, EmptyPage,\
PageNotAnInteger
from .forms import EmailPostForm, CommentForm
from django.core.mail import send_m... | 0.342132 | 0.071559 |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_in... | pipelinerunner/execute_pb2.py |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_in... | 0.151498 | 0.094594 |
import os
def preproc(sheet_list, CWD):
"""
Предобработка таблицы данных
"""
# Чёткое очерчивание границ таблицы:
col_num = 0
while col_num < len( sheet_list[0] ):
if sheet_list[0][col_num].strip() == "":
for row_num in range( len( sheet_list ) ):
del sh... | pathway_handlers.py | import os
def preproc(sheet_list, CWD):
"""
Предобработка таблицы данных
"""
# Чёткое очерчивание границ таблицы:
col_num = 0
while col_num < len( sheet_list[0] ):
if sheet_list[0][col_num].strip() == "":
for row_num in range( len( sheet_list ) ):
del sh... | 0.056191 | 0.377713 |
from processors.multi_rc import MultiRCProcessor, MultiRCSentenceProcessor
from .race import RACEProcessor
from .race_sent import RACEProcessor as RACESentenceProcessor
from .wiki_pre_train import WikiPreTrainProcessor
from .wiki_pre_train_ent import WikiEntityPreTrainProcessor
from .wiki_pre_train_ent_ar import W... | processors/__init__.py | from processors.multi_rc import MultiRCProcessor, MultiRCSentenceProcessor
from .race import RACEProcessor
from .race_sent import RACEProcessor as RACESentenceProcessor
from .wiki_pre_train import WikiPreTrainProcessor
from .wiki_pre_train_ent import WikiEntityPreTrainProcessor
from .wiki_pre_train_ent_ar import W... | 0.55929 | 0.094385 |
import math
import numpy as np
import jax
import jax.numpy as jnp
from jax import config
import tensorflow as tf
import torch
import pytest
import tensornetwork
from tensornetwork.backends import abstract_backend
from tensornetwork import backends, backend_contextmanager
from tensornetwork.tests import testing_utils
... | tensornetwork/tests/tensor_test.py |
import math
import numpy as np
import jax
import jax.numpy as jnp
from jax import config
import tensorflow as tf
import torch
import pytest
import tensornetwork
from tensornetwork.backends import abstract_backend
from tensornetwork import backends, backend_contextmanager
from tensornetwork.tests import testing_utils
... | 0.658857 | 0.463748 |
import pandas as pd
import numpy as np
import nltk
import matplotlib.pyplot as plt
import seaborn as sns
from nltk.corpus import stopwords
from nltk import word_tokenize
from nltk.data import load
from nltk.stem import SnowballStemmer
from string import punctuation
from sklearn.feature_extraction.text import CountVe... | twitter_sentanal.py | import pandas as pd
import numpy as np
import nltk
import matplotlib.pyplot as plt
import seaborn as sns
from nltk.corpus import stopwords
from nltk import word_tokenize
from nltk.data import load
from nltk.stem import SnowballStemmer
from string import punctuation
from sklearn.feature_extraction.text import CountVe... | 0.87362 | 0.302623 |
import cmd
import exceptions
import sys
import time
import shlex
import redwood.filters
import redwood.helpers.core as core
from redwood.filters import filter_list
from redwood.foundation.aggregator import Aggregator
from redwood.foundation.report import Report
class SubInterpreterDiscover(cmd.Cmd):
def __ini... | redwood/shell/modes.py | import cmd
import exceptions
import sys
import time
import shlex
import redwood.filters
import redwood.helpers.core as core
from redwood.filters import filter_list
from redwood.foundation.aggregator import Aggregator
from redwood.foundation.report import Report
class SubInterpreterDiscover(cmd.Cmd):
def __ini... | 0.268654 | 0.075995 |
import _plotly_utils.basevalidators
class YsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="ysrc", parent_name="histogram", **kwargs):
super(YsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_typ... | packages/python/plotly/plotly/validators/histogram/__init__.py | import _plotly_utils.basevalidators
class YsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="ysrc", parent_name="histogram", **kwargs):
super(YsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_typ... | 0.879263 | 0.453746 |
from testflows.core import *
from testflows.asserts import error
from rbac.requirements import *
from rbac.helper.common import *
import rbac.helper.errors as errors
@TestSuite
def create_user_granted_directly(self, node=None):
"""Check that a user is able to execute `CREATE USER` with privileges are granted dire... | tests/testflows/rbac/tests/privileges/create/create_user.py | from testflows.core import *
from testflows.asserts import error
from rbac.requirements import *
from rbac.helper.common import *
import rbac.helper.errors as errors
@TestSuite
def create_user_granted_directly(self, node=None):
"""Check that a user is able to execute `CREATE USER` with privileges are granted dire... | 0.603465 | 0.284582 |
import os
import subprocess
import numpy as np
import pandas as pd
from utils.combine import merge_by_subject
from utils.save_data import write_csv
def load_data():
root = r'C:\Users\User\GitHub\WebET_Analysis'
path = os.path.join(root, 'not_prolific', 'amasino', 'source')
# x, y starts at top-left (0,... | not_prolific/amasino/prep_data_trial.py | import os
import subprocess
import numpy as np
import pandas as pd
from utils.combine import merge_by_subject
from utils.save_data import write_csv
def load_data():
root = r'C:\Users\User\GitHub\WebET_Analysis'
path = os.path.join(root, 'not_prolific', 'amasino', 'source')
# x, y starts at top-left (0,... | 0.310381 | 0.16807 |
from __future__ import print_function
import re
from subprocess import Popen, PIPE
def run_subprocess(cmd):
cmd = cmd.encode("ascii")
args = cmd.split()
return Popen(args, stdout=PIPE, stderr=PIPE)
TOUCHPAD_NAME = "Synaptics TouchPad"
ID_PATTERN = re.compile("id=\d{1,3}")
EN_PATTERN = re.compile("Devic... | fuckpad.py | from __future__ import print_function
import re
from subprocess import Popen, PIPE
def run_subprocess(cmd):
cmd = cmd.encode("ascii")
args = cmd.split()
return Popen(args, stdout=PIPE, stderr=PIPE)
TOUCHPAD_NAME = "Synaptics TouchPad"
ID_PATTERN = re.compile("id=\d{1,3}")
EN_PATTERN = re.compile("Devic... | 0.456168 | 0.110375 |
import time
from oslo_log import log
from six.moves import http_client
from six.moves import urllib
from cinder import exception
from cinder.i18n import _, _LE
LOG = log.getLogger(__name__)
bad_gateway_err = _('Check the state of the http service. Also ensure that '
'the https port number is the... | cinder/volume/drivers/zfssa/webdavclient.py | import time
from oslo_log import log
from six.moves import http_client
from six.moves import urllib
from cinder import exception
from cinder.i18n import _, _LE
LOG = log.getLogger(__name__)
bad_gateway_err = _('Check the state of the http service. Also ensure that '
'the https port number is the... | 0.372619 | 0.073297 |
import sys
import argparse
from opentotp import OpenTOTP, __version__
__all__ = ["main"]
def cmd_generate(otp: OpenTOTP,
args: argparse.Namespace) -> int:
"""Sub-command to generate OTP"""
if not args.quiet:
param_use_verbose_mode(otp, args)
print("One-time password: ", end... | opentotp/__main__.py |
import sys
import argparse
from opentotp import OpenTOTP, __version__
__all__ = ["main"]
def cmd_generate(otp: OpenTOTP,
args: argparse.Namespace) -> int:
"""Sub-command to generate OTP"""
if not args.quiet:
param_use_verbose_mode(otp, args)
print("One-time password: ", end... | 0.341912 | 0.168173 |
import sys
import os
import subprocess
import getopt
import re
def print_help():
print("")
print("\tformat_results.py -d (experiment directory)\n")
print("")
sys.exit(1)
print("")
try:
opts,args = getopt.getopt(sys.argv[1:],"d:",["d="])
except getopt.GetoptError:
print_help()
dir = ""
... | workloads/bit/hpl/format_results.py |
import sys
import os
import subprocess
import getopt
import re
def print_help():
print("")
print("\tformat_results.py -d (experiment directory)\n")
print("")
sys.exit(1)
print("")
try:
opts,args = getopt.getopt(sys.argv[1:],"d:",["d="])
except getopt.GetoptError:
print_help()
dir = ""
... | 0.12408 | 0.056262 |
# Test whether a bridge can cope with an unknown PUBACK
from mosq_test_helper import *
def write_config(filename, port1, port2, protocol_version):
with open(filename, 'w') as f:
f.write("port %d\n" % (port2))
f.write("\n")
f.write("connection bridge-u-test\n")
f.write("remote_clie... | eclipse-mosquitto/test/broker/06-bridge-fail-persist-resend-qos1.py |
# Test whether a bridge can cope with an unknown PUBACK
from mosq_test_helper import *
def write_config(filename, port1, port2, protocol_version):
with open(filename, 'w') as f:
f.write("port %d\n" % (port2))
f.write("\n")
f.write("connection bridge-u-test\n")
f.write("remote_clie... | 0.327883 | 0.215 |
import unittest
import numpy as np
from iris.coords import DimCoord
from iris.cube import Cube
from iris.tests import IrisTest
from improver.utilities.ancillary_creation import OrographicSmoothingCoefficients
from improver.utilities.spatial import DifferenceBetweenAdjacentGridSquares
def set_up_cube():
"""Set u... | improver_tests/utilities/test_OrographicSmoothingCoefficients.py | import unittest
import numpy as np
from iris.coords import DimCoord
from iris.cube import Cube
from iris.tests import IrisTest
from improver.utilities.ancillary_creation import OrographicSmoothingCoefficients
from improver.utilities.spatial import DifferenceBetweenAdjacentGridSquares
def set_up_cube():
"""Set u... | 0.783575 | 0.741159 |
import os
from subprocess import Popen
from subprocess import PIPE
from subprocess import STDOUT
from funtoo.boot.extension import Extension
def getExtension(config):
return LILOExtension(config)
class LILOExtension(Extension):
def __init__(self,config):
Extension.__init__(self,config)
self.fn = self.confi... | python/modules/funtoo/boot/extensions/lilo.py |
import os
from subprocess import Popen
from subprocess import PIPE
from subprocess import STDOUT
from funtoo.boot.extension import Extension
def getExtension(config):
return LILOExtension(config)
class LILOExtension(Extension):
def __init__(self,config):
Extension.__init__(self,config)
self.fn = self.confi... | 0.257485 | 0.103567 |
from celest.encounter._encounter_math_utils import _analytical_encounter_ind
from celest.satellite.coordinate import Coordinate
from celest.satellite.time import Time
from typing import Any, Literal
from jplephem.spk import SPK
import numpy as np
import pkg_resources
def _sun_itrs(julian: np.ndarray) -> np.ndarray:
... | celest/encounter/_window_utils.py | from celest.encounter._encounter_math_utils import _analytical_encounter_ind
from celest.satellite.coordinate import Coordinate
from celest.satellite.time import Time
from typing import Any, Literal
from jplephem.spk import SPK
import numpy as np
import pkg_resources
def _sun_itrs(julian: np.ndarray) -> np.ndarray:
... | 0.926003 | 0.692168 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from args import *
from utils import linear
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_planes, plane... | resnet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from args import *
from utils import linear
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_planes, plane... | 0.907942 | 0.390214 |
import unittest
import numpy
from cqcpy.ov_blocks import one_e_blocks
from cqcpy import test_utils
from kelvin import ft_cc_energy
from kelvin import ft_cc_equations
from kelvin import quadrature
def evalL(T1f, T1b, T1i, T2f, T2b, T2i,
L1f, L1b, L1i, L2f, L2b, L2i,
Ff, Fb, F, I, D1, D2, tir, tii,
... | kelvin/tests/test_neq_lambda_equation.py | import unittest
import numpy
from cqcpy.ov_blocks import one_e_blocks
from cqcpy import test_utils
from kelvin import ft_cc_energy
from kelvin import ft_cc_equations
from kelvin import quadrature
def evalL(T1f, T1b, T1i, T2f, T2b, T2i,
L1f, L1b, L1i, L2f, L2b, L2i,
Ff, Fb, F, I, D1, D2, tir, tii,
... | 0.319758 | 0.415077 |
import bpy
from .main import ToolPanel
from .. import globs
from ..tools import common as Common
from ..tools import supporter as Supporter
from ..tools import armature_bones as Armature_bones
from ..tools import armature_custom as Armature_custom
from ..tools.register import register_wrap
@register_wrap
class Custo... | ui/custom.py | import bpy
from .main import ToolPanel
from .. import globs
from ..tools import common as Common
from ..tools import supporter as Supporter
from ..tools import armature_bones as Armature_bones
from ..tools import armature_custom as Armature_custom
from ..tools.register import register_wrap
@register_wrap
class Custo... | 0.439747 | 0.195402 |
import torch
import logging
def get_device(args):
if args.training_type == "simulation" and args.backend == "single_process":
if args.using_gpu:
device = torch.device(
"cuda:" + str(args.gpu_id) if torch.cuda.is_available() else "cpu"
)
else:
de... | python/fedml/device/device.py | import torch
import logging
def get_device(args):
if args.training_type == "simulation" and args.backend == "single_process":
if args.using_gpu:
device = torch.device(
"cuda:" + str(args.gpu_id) if torch.cuda.is_available() else "cpu"
)
else:
de... | 0.373419 | 0.296438 |
import sys
from PyQt5.QtWidgets import *
from login import authenticate_login
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon, QColor, QPixmap
class Login(QWidget):
def __init__(self, queue, connection):
super().__init__()
try:
# Sets window title
self.setWindowTitle('BitsOJ v1.0.1 [ LOGIN ]')
... | Client_Linux/interface_package/login_interface.py | import sys
from PyQt5.QtWidgets import *
from login import authenticate_login
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon, QColor, QPixmap
class Login(QWidget):
def __init__(self, queue, connection):
super().__init__()
try:
# Sets window title
self.setWindowTitle('BitsOJ v1.0.1 [ LOGIN ]')
... | 0.219756 | 0.117167 |
from ..qt import QtGui
from ..widgets.glassure import GlassureWidget
from ..model.glassure import GlassureModel
class ConfigurationController(object):
def __init__(self, main_widget, glassure_model):
"""
:param main_widget:
:type main_widget: GlassureWidget
:param glassure_model:... | glassure/gui/controller/configuration.py |
from ..qt import QtGui
from ..widgets.glassure import GlassureWidget
from ..model.glassure import GlassureModel
class ConfigurationController(object):
def __init__(self, main_widget, glassure_model):
"""
:param main_widget:
:type main_widget: GlassureWidget
:param glassure_model:... | 0.589835 | 0.106412 |
import idfpy
import numpy as np
import pytest
import shutil
import os
@pytest.fixture
def sourcefile(tmpdir):
datadir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
sourcefilename = r'bxk1-d-ck.idf'
sourcefile = os.path.join(datadir, sourcefilename)
testfile = tmpdir.join(source... | idfpy/tests/test_idf.py |
import idfpy
import numpy as np
import pytest
import shutil
import os
@pytest.fixture
def sourcefile(tmpdir):
datadir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
sourcefilename = r'bxk1-d-ck.idf'
sourcefile = os.path.join(datadir, sourcefilename)
testfile = tmpdir.join(source... | 0.486575 | 0.497253 |
import numpy as np
from abc import ABC, abstractmethod
from typing import List, Union, Dict, Tuple
from ortools.linear_solver.pywraplp import Variable
from hadar import Study
from hadar.optimizer.utils import JSON
class JSONLP(JSON, ABC):
def to_json(self):
def copy(v):
if isinstance(v, Var... | hadar/optimizer/lp/domain.py | import numpy as np
from abc import ABC, abstractmethod
from typing import List, Union, Dict, Tuple
from ortools.linear_solver.pywraplp import Variable
from hadar import Study
from hadar.optimizer.utils import JSON
class JSONLP(JSON, ABC):
def to_json(self):
def copy(v):
if isinstance(v, Var... | 0.898961 | 0.394872 |
import glob
import os
import shutil
import subprocess
import time
import numpy as np
import pandas as pd
import yaml
def compute_accuracy(gt_labels, pred_fname):
nb_classes = len(set(gt_labels))
probs = np.fromfile(pred_fname, dtype=np.float32).reshape((-1, nb_classes))
probs = probs[0:len(gt_labels)]
... | e2e/runner/runner.py | import glob
import os
import shutil
import subprocess
import time
import numpy as np
import pandas as pd
import yaml
def compute_accuracy(gt_labels, pred_fname):
nb_classes = len(set(gt_labels))
probs = np.fromfile(pred_fname, dtype=np.float32).reshape((-1, nb_classes))
probs = probs[0:len(gt_labels)]
... | 0.290578 | 0.138345 |
import pytest
from webdriver.error import NoSuchAlertException
from tests.support.asserts import assert_error, assert_success
from tests.support.helpers import wait_for_new_handle
from tests.support.sync import Poll
def accept_alert(session):
return session.transport.send(
"POST", "session/{session_id}/... | webdriver/tests/accept_alert/accept.py | import pytest
from webdriver.error import NoSuchAlertException
from tests.support.asserts import assert_error, assert_success
from tests.support.helpers import wait_for_new_handle
from tests.support.sync import Poll
def accept_alert(session):
return session.transport.send(
"POST", "session/{session_id}/... | 0.481698 | 0.363195 |
import struct
import logging
from math import ceil
from scapy.all import *
from twisted.internet import defer
from threading import Thread
import json
import netifaces
logging.basicConfig(level=logging.DEBUG,format='%(message)s')
VALUE_SIZE = 64
PHASE_1A = 1
PHASE_1B = 2
PHASE_2A = 3
PHASE_2B = 4
class PaxosMessage(... | bmv2/scripts/paxoscore/learner.py |
import struct
import logging
from math import ceil
from scapy.all import *
from twisted.internet import defer
from threading import Thread
import json
import netifaces
logging.basicConfig(level=logging.DEBUG,format='%(message)s')
VALUE_SIZE = 64
PHASE_1A = 1
PHASE_1B = 2
PHASE_2A = 3
PHASE_2B = 4
class PaxosMessage(... | 0.47171 | 0.186465 |
__author__ = 'schubert'
import unittest
# Variants and Generator
from epytope.Core import Allele
from epytope.Core import Peptide
# Predictions
from epytope.EpitopePrediction import EpitopePredictorFactory, AExternalEpitopePrediction
class TestCaseEpitopePrediction(unittest.TestCase):
def setUp(self):
... | epytope/test/TestEpitopePrediction.py | __author__ = 'schubert'
import unittest
# Variants and Generator
from epytope.Core import Allele
from epytope.Core import Peptide
# Predictions
from epytope.EpitopePrediction import EpitopePredictorFactory, AExternalEpitopePrediction
class TestCaseEpitopePrediction(unittest.TestCase):
def setUp(self):
... | 0.57332 | 0.203787 |
from __future__ import with_statement, print_function
import sys
import time
import eventlet
import py
import pytest
from eventlet.green.subprocess import Popen
from textwrap import dedent as d
from detox.proc import Detox
from detox.cli import main as detox_main, tox_prepare
pytest_plugins = "pytester"
def creat... | tests/conftest.py | from __future__ import with_statement, print_function
import sys
import time
import eventlet
import py
import pytest
from eventlet.green.subprocess import Popen
from textwrap import dedent as d
from detox.proc import Detox
from detox.cli import main as detox_main, tox_prepare
pytest_plugins = "pytester"
def creat... | 0.267408 | 0.275506 |
from pathlib import Path
import subprocess
import logging
import sys
import torch
import torchvision.transforms as tvf
from ..utils.base_model import BaseModel
logger = logging.getLogger(__name__)
fire_path = Path(__file__).parent / '../../third_party/fire'
sys.path.append(str(fire_path))
import fire_network
cl... | hloc/extractors/fire.py | from pathlib import Path
import subprocess
import logging
import sys
import torch
import torchvision.transforms as tvf
from ..utils.base_model import BaseModel
logger = logging.getLogger(__name__)
fire_path = Path(__file__).parent / '../../third_party/fire'
sys.path.append(str(fire_path))
import fire_network
cl... | 0.488039 | 0.14734 |
import os
import pytest
from numpy.testing import assert_allclose
from numpy import ones, zeros, float64, array, append, genfromtxt
from numpy.linalg import LinAlgError
from touvlo.lin_rg import (normal_eqn, cost_func, reg_cost_func, grad,
reg_grad, predict, h, LinearRegression,
... | tests/test_lin_rg.py | import os
import pytest
from numpy.testing import assert_allclose
from numpy import ones, zeros, float64, array, append, genfromtxt
from numpy.linalg import LinAlgError
from touvlo.lin_rg import (normal_eqn, cost_func, reg_cost_func, grad,
reg_grad, predict, h, LinearRegression,
... | 0.524395 | 0.69643 |
import re
from datetime import datetime
import discord
from d4dj_utils.master.login_bonus_master import LoginBonusMaster
from fluent.runtime.types import fluent_date
from miyu_bot.bot.bot import PrefContext
from miyu_bot.commands.common.asset_paths import get_asset_filename
from miyu_bot.commands.common.formatting im... | miyu_bot/commands/master_filter/login_bonus_filter.py | import re
from datetime import datetime
import discord
from d4dj_utils.master.login_bonus_master import LoginBonusMaster
from fluent.runtime.types import fluent_date
from miyu_bot.bot.bot import PrefContext
from miyu_bot.commands.common.asset_paths import get_asset_filename
from miyu_bot.commands.common.formatting im... | 0.394201 | 0.229784 |
from ..spaces import Space, Cylindrical
from ..cat import WHITES
from ..gamut.bounds import GamutBound, FLG_ANGLE, FLG_OPT_PERCENT
from .lch import ACHROMATIC_THRESHOLD
from .lab import EPSILON, KAPPA
from .srgb_linear import XYZ_TO_RGB
import math
from .. import util
from .. import algebra as alg
from ..types import V... | lib/coloraide/spaces/hsluv.py | from ..spaces import Space, Cylindrical
from ..cat import WHITES
from ..gamut.bounds import GamutBound, FLG_ANGLE, FLG_OPT_PERCENT
from .lch import ACHROMATIC_THRESHOLD
from .lab import EPSILON, KAPPA
from .srgb_linear import XYZ_TO_RGB
import math
from .. import util
from .. import algebra as alg
from ..types import V... | 0.864038 | 0.33463 |
class PieceTable(object):
def __init__(self, fulltext):
assert isinstance(fulltext, bytes)
self.fulltext = fulltext # The original text file.
self.addtext = b"" # Text added to the original file.
self.pieces = [ # Pieces of the piece table.
(0, len(fulltext... | wp_pyqt5/piecetable.py | class PieceTable(object):
def __init__(self, fulltext):
assert isinstance(fulltext, bytes)
self.fulltext = fulltext # The original text file.
self.addtext = b"" # Text added to the original file.
self.pieces = [ # Pieces of the piece table.
(0, len(fulltext... | 0.663887 | 0.540136 |
from typing import Any, List, Optional
import torch
from gym import Space
from gym.spaces import Box
from torch import Tensor
from rl.spaces.base import TensorSpace
__all__ = ['TensorBox']
class TensorBox(TensorSpace):
"""Tensor space variant of :class:`gym.spaces.Box`.
Arguments:
low (Tensor): A ... | rl/spaces/tensor_box.py | from typing import Any, List, Optional
import torch
from gym import Space
from gym.spaces import Box
from torch import Tensor
from rl.spaces.base import TensorSpace
__all__ = ['TensorBox']
class TensorBox(TensorSpace):
"""Tensor space variant of :class:`gym.spaces.Box`.
Arguments:
low (Tensor): A ... | 0.92924 | 0.752899 |
from __future__ import unicode_literals
import unittest
import mock
from hamcrest import assert_that, equal_to
from storops.connection import connector
class UnityRESTConnectorTest(unittest.TestCase):
@mock.patch('storops.connection.client.HTTPClient')
def test_new_connector_verify_false(self, mocked_htt... | storops_test/connection/test_connector.py |
from __future__ import unicode_literals
import unittest
import mock
from hamcrest import assert_that, equal_to
from storops.connection import connector
class UnityRESTConnectorTest(unittest.TestCase):
@mock.patch('storops.connection.client.HTTPClient')
def test_new_connector_verify_false(self, mocked_htt... | 0.665628 | 0.150403 |
import argparse
import mock
import requests
from cloud_info_provider.providers import ooi as ooi_provider
from cloud_info_provider.providers import openstack as os_provider
from cloud_info_provider.tests import base, data
from cloud_info_provider.tests import utils as utils
from six.moves.urllib.parse import urljoin
... | cloud_info_provider/tests/test_openstack.py | import argparse
import mock
import requests
from cloud_info_provider.providers import ooi as ooi_provider
from cloud_info_provider.providers import openstack as os_provider
from cloud_info_provider.tests import base, data
from cloud_info_provider.tests import utils as utils
from six.moves.urllib.parse import urljoin
... | 0.578567 | 0.191857 |
#%%
# 9.2.2項で利用するライブラリ
import numpy as np
from scipy.stats import multivariate_normal # 多次元ガウス分布
import matplotlib.pyplot as plt
#%%
## 真の分布の設定
# 次元数を設定:(固定)
D = 2
# クラスタ数を指定
K = 3
# K個の真の平均を指定
mu_truth_kd = np.array(
[[5.0, 35.0],
[-20.0, -10.0],
[30.0, -20.0]]
)
# K個の真の共分散行列を指定
sigma2_truth_kd... | Code_Python/ch9_2_2.py |
#%%
# 9.2.2項で利用するライブラリ
import numpy as np
from scipy.stats import multivariate_normal # 多次元ガウス分布
import matplotlib.pyplot as plt
#%%
## 真の分布の設定
# 次元数を設定:(固定)
D = 2
# クラスタ数を指定
K = 3
# K個の真の平均を指定
mu_truth_kd = np.array(
[[5.0, 35.0],
[-20.0, -10.0],
[30.0, -20.0]]
)
# K個の真の共分散行列を指定
sigma2_truth_kd... | 0.360039 | 0.684992 |
from tkinter import *
class TooltipBase(object):
"""abstract base class for tooltips"""
def __init__(self, anchor_widget):
"""Create a tooltip.
anchor_widget: the widget next to which the tooltip will be shown
Note that a widget will only be shown when showtip() is called... | toolchain/riscv/MSYS/python/Lib/idlelib/tooltip.py | from tkinter import *
class TooltipBase(object):
"""abstract base class for tooltips"""
def __init__(self, anchor_widget):
"""Create a tooltip.
anchor_widget: the widget next to which the tooltip will be shown
Note that a widget will only be shown when showtip() is called... | 0.696475 | 0.134037 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from pointnet2_lib.pointnet2.pointnet2_modules import PointnetSAModule
from lib.rpn.proposal_target_layer import ProposalTargetLayer
from lib.net.rcnn_net import RCNNNet
import pointnet2_lib.pointnet2.pytorch_utils as pt_utils
import lib.utils.loss_util... | lib/net/cascade.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from pointnet2_lib.pointnet2.pointnet2_modules import PointnetSAModule
from lib.rpn.proposal_target_layer import ProposalTargetLayer
from lib.net.rcnn_net import RCNNNet
import pointnet2_lib.pointnet2.pytorch_utils as pt_utils
import lib.utils.loss_util... | 0.781539 | 0.129843 |
import sys
import os
import re
import pytest
import glob
import time
def start_server():
import tempfile
from conftest import AppFileHandler
from experimentum.Experiments import App
from experimentum.WebGUI import Server
# App Container
class WebAppContainer(App):
config_path = tempfi... | tests/functional/test_webgui.py | import sys
import os
import re
import pytest
import glob
import time
def start_server():
import tempfile
from conftest import AppFileHandler
from experimentum.Experiments import App
from experimentum.WebGUI import Server
# App Container
class WebAppContainer(App):
config_path = tempfi... | 0.343342 | 0.156362 |
from functools import partial
from testtools import TestCase
from testtools.matchers import MatchesException, raises
from ._base import Effect
from ._sync import NotSynchronousError, sync_perform, sync_performer
def func_dispatcher(intent):
def performer(dispatcher, intent, box):
intent(box)
return ... | effect/test_sync.py | from functools import partial
from testtools import TestCase
from testtools.matchers import MatchesException, raises
from ._base import Effect
from ._sync import NotSynchronousError, sync_perform, sync_performer
def func_dispatcher(intent):
def performer(dispatcher, intent, box):
intent(box)
return ... | 0.887546 | 0.400398 |
import numericalunits as nu
import numpy as np
from scipy.interpolate import RegularGridInterpolator, interp1d
from scipy.integrate import quad, dblquad
import wimprates as wr
export, __all__ = wr.exporter()
__all__ += ['dme_shells', 'l_to_letter', 'l_to_number']
# Load form factor and construct interpolators
shell_d... | wimprates/electron.py | import numericalunits as nu
import numpy as np
from scipy.interpolate import RegularGridInterpolator, interp1d
from scipy.integrate import quad, dblquad
import wimprates as wr
export, __all__ = wr.exporter()
__all__ += ['dme_shells', 'l_to_letter', 'l_to_number']
# Load form factor and construct interpolators
shell_d... | 0.798344 | 0.408808 |
import asyncio
import struct
from dataclasses import dataclass
from aiomodbus import decoders, encoders
import serial_asyncio
import aiomodbus.crc
from aiomodbus.exceptions import modbus_exception_codes
class ModbusSerialProtocol(asyncio.Protocol):
def __init__(self, client):
self.transport = None
... | aiomodbus/serial.py | import asyncio
import struct
from dataclasses import dataclass
from aiomodbus import decoders, encoders
import serial_asyncio
import aiomodbus.crc
from aiomodbus.exceptions import modbus_exception_codes
class ModbusSerialProtocol(asyncio.Protocol):
def __init__(self, client):
self.transport = None
... | 0.541409 | 0.193338 |
from odoo.tests import common
@common.tagged('post_install', '-at_install')
class TestXMLRPC(common.HttpCase):
def setUp(self):
super(TestXMLRPC, self).setUp()
self.admin_uid = self.env.ref('base.user_admin').id
def test_01_xmlrpc_login(self):
""" Try to login on the common service.... | odoo-13.0/odoo/addons/base/tests/test_xmlrpc.py |
from odoo.tests import common
@common.tagged('post_install', '-at_install')
class TestXMLRPC(common.HttpCase):
def setUp(self):
super(TestXMLRPC, self).setUp()
self.admin_uid = self.env.ref('base.user_admin').id
def test_01_xmlrpc_login(self):
""" Try to login on the common service.... | 0.447943 | 0.118538 |
import ctypes
import bgfx
import unittest
class TestImport(unittest.TestCase):
def test_module(self):
self.assertEqual(bgfx.__author__, '<NAME>')
self.assertEqual(bgfx.__license__, 'BSD 2-clause')
self.assertEqual(bgfx.__status__, 'Development')
class TestEnums(unittest.TestCase):
de... | pybgfx/bgfx_tests.py | import ctypes
import bgfx
import unittest
class TestImport(unittest.TestCase):
def test_module(self):
self.assertEqual(bgfx.__author__, '<NAME>')
self.assertEqual(bgfx.__license__, 'BSD 2-clause')
self.assertEqual(bgfx.__status__, 'Development')
class TestEnums(unittest.TestCase):
de... | 0.494873 | 0.351116 |
{
'includes': [
'../mojo_variables.gypi',
],
'targets': [
{
'target_name': 'mojo_edk_tests',
'type': 'none',
'dependencies': [
# NOTE: If adding a new dependency here, please consider whether it
# should also be added to the list of Mojo-related dependencies of
#... | mojo/edk/mojo_edk_tests.gyp |
{
'includes': [
'../mojo_variables.gypi',
],
'targets': [
{
'target_name': 'mojo_edk_tests',
'type': 'none',
'dependencies': [
# NOTE: If adding a new dependency here, please consider whether it
# should also be added to the list of Mojo-related dependencies of
#... | 0.27474 | 0.157363 |
from ParadoxTrading.Engine import SignalType
from ParadoxTrading.Indicator.Stop.StopIndicatorAbstract import StopIndicatorAbstract
from ParadoxTrading.Utils import DataStruct
class ATRTrailingStop(StopIndicatorAbstract):
def __init__(
self,
_price_data: DataStruct,
_atr_data: D... | ParadoxTrading/Indicator/Stop/ATRTrailingStop.py | from ParadoxTrading.Engine import SignalType
from ParadoxTrading.Indicator.Stop.StopIndicatorAbstract import StopIndicatorAbstract
from ParadoxTrading.Utils import DataStruct
class ATRTrailingStop(StopIndicatorAbstract):
def __init__(
self,
_price_data: DataStruct,
_atr_data: D... | 0.698329 | 0.430866 |
from pprint import pformat
from six import iteritems
import re
class CartAddBySeatsResponse(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, success=None, entries_id=None):
"""
CartAddBySea... | digitick_client/models/cart_add_by_seats_response.py | from pprint import pformat
from six import iteritems
import re
class CartAddBySeatsResponse(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, success=None, entries_id=None):
"""
CartAddBySea... | 0.797596 | 0.239072 |
from django.db import models
from django.contrib.auth.models import User
from hknweb.models import Profile
from hknweb.events.models.event import Event
import hknweb.events.google_calendar_utils as gcal
class Rsvp(models.Model):
user = models.ForeignKey(User, models.CASCADE, verbose_name="rsvp'd by")
event =... | hknweb/events/models/rsvp.py | from django.db import models
from django.contrib.auth.models import User
from hknweb.models import Profile
from hknweb.events.models.event import Event
import hknweb.events.google_calendar_utils as gcal
class Rsvp(models.Model):
user = models.ForeignKey(User, models.CASCADE, verbose_name="rsvp'd by")
event =... | 0.542863 | 0.089933 |
from vm_network_migration.utils import initializer
from vm_network_migration.handlers.compute_engine_resource_migration import ComputeEngineResourceMigration
from vm_network_migration.handler_helper.selfLink_executor import SelfLinkExecutor
class TargetInstanceMigration(ComputeEngineResourceMigration):
@initializ... | vm_network_migration/handlers/instance_migration/target_instance_migration.py | from vm_network_migration.utils import initializer
from vm_network_migration.handlers.compute_engine_resource_migration import ComputeEngineResourceMigration
from vm_network_migration.handler_helper.selfLink_executor import SelfLinkExecutor
class TargetInstanceMigration(ComputeEngineResourceMigration):
@initializ... | 0.862134 | 0.187244 |
import operator
from rpython.rlib.buffer import Buffer, SubBuffer
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.error import OperationError, oefmt
from pypy.interpreter.gateway import interp2app
from pypy.interpreter.typedef import TypeDef, GetSetProperty
class W_MemoryView(W_Root):
"""I... | pypy/objspace/std/memoryobject.py | import operator
from rpython.rlib.buffer import Buffer, SubBuffer
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.error import OperationError, oefmt
from pypy.interpreter.gateway import interp2app
from pypy.interpreter.typedef import TypeDef, GetSetProperty
class W_MemoryView(W_Root):
"""I... | 0.591251 | 0.216736 |
import unittest
from datawinners.blue.error_translation_utils import transform_error_message
EXPECTED_DUPLICATE_HEADER_ERROR = "Duplicate column header: 'column_name'. Update your XLSForm and upload again."
EXPECTED_DUPLICATE_ELEMENT_NAME_ERROR = "There are two survey elements named 'ff'. Update your XLSForm and uploa... | datawinners/blue/test/test_error_translation_utils.py | import unittest
from datawinners.blue.error_translation_utils import transform_error_message
EXPECTED_DUPLICATE_HEADER_ERROR = "Duplicate column header: 'column_name'. Update your XLSForm and upload again."
EXPECTED_DUPLICATE_ELEMENT_NAME_ERROR = "There are two survey elements named 'ff'. Update your XLSForm and uploa... | 0.524882 | 0.373219 |
from geometry.points import Point3D
class Inserts:
def __init__(self, height, inner_radius, outer_radius):
self.height = height
self.inner_radius = inner_radius
self.outer_radius = outer_radius
# TODO 计算嵌件铣削的刀具路径
def cal_path(self):
pass
def __repr__(self):
p... | component/inserts.py |
from geometry.points import Point3D
class Inserts:
def __init__(self, height, inner_radius, outer_radius):
self.height = height
self.inner_radius = inner_radius
self.outer_radius = outer_radius
# TODO 计算嵌件铣削的刀具路径
def cal_path(self):
pass
def __repr__(self):
p... | 0.463444 | 0.279804 |
from src.Utils.Fitness import *
from src.Utils.Population import *
import matplotlib.pyplot as plt
import pandas as pd
from scipy.spatial import distance
from src.Utils.Graphs import *
from time import time
from src.Utils.HyperParameters import *
class NSHSDEARM:
def __init__(self,nbItem,populationSize,nbIteration... | src/Algorithm/NSHSDEARM.py | from src.Utils.Fitness import *
from src.Utils.Population import *
import matplotlib.pyplot as plt
import pandas as pd
from scipy.spatial import distance
from src.Utils.Graphs import *
from time import time
from src.Utils.HyperParameters import *
class NSHSDEARM:
def __init__(self,nbItem,populationSize,nbIteration... | 0.402744 | 0.406685 |
import __init__
import torch
import torch.optim as optim
import statistics
from dataset import OGBNDataset
from model import DeeperGCN
from args import ArgsInit
import time
import numpy as np
from ogb.nodeproppred import Evaluator
from utils.ckpt_util import save_ckpt
from utils.data_util import intersection, process_i... | OGBN_proteins/unify/ogb/ogbn_proteins/main_imp.py | import __init__
import torch
import torch.optim as optim
import statistics
from dataset import OGBNDataset
from model import DeeperGCN
from args import ArgsInit
import time
import numpy as np
from ogb.nodeproppred import Evaluator
from utils.ckpt_util import save_ckpt
from utils.data_util import intersection, process_i... | 0.556159 | 0.216902 |
from .base_options import BaseOptions
class TrainOptions(BaseOptions):
def __init__(self):
super(TrainOptions, self).__init__()
def initialize(self):
BaseOptions.initialize(self)
# HTML visualization parameters
self.parser.add_argument('--display_freq', type=int, default=100,... | options/train_options.py | from .base_options import BaseOptions
class TrainOptions(BaseOptions):
def __init__(self):
super(TrainOptions, self).__init__()
def initialize(self):
BaseOptions.initialize(self)
# HTML visualization parameters
self.parser.add_argument('--display_freq', type=int, default=100,... | 0.789234 | 0.123102 |
import numpy as np
from pungi.agents.agent import Agent
import random
from collections import deque
import pungi.agents.policies as policies
from pungi.agents.qlearning.qlearning import DIRECTIONS
import time
STRING_TO_ACTION = {"left": 0, "right": 1, "up": 2, "down": 3}
class DQLAgent(Agent):
def on_after_epi... | pungi/agents/dql/dql_agent.py | import numpy as np
from pungi.agents.agent import Agent
import random
from collections import deque
import pungi.agents.policies as policies
from pungi.agents.qlearning.qlearning import DIRECTIONS
import time
STRING_TO_ACTION = {"left": 0, "right": 1, "up": 2, "down": 3}
class DQLAgent(Agent):
def on_after_epi... | 0.62498 | 0.33846 |
from __future__ import print_function
import random
#hangList = ["cow", "rat", "animal", "pizza"]
def hangman_display(guessed, secret):
""" This sets up the hangman display"""
#guessed = letters guessed so far
#secret = full secret word/phrase
secret_list = list(secret)
guess_list = list(guessed)
... | Tewari_Sumardy_Hangman.py | from __future__ import print_function
import random
#hangList = ["cow", "rat", "animal", "pizza"]
def hangman_display(guessed, secret):
""" This sets up the hangman display"""
#guessed = letters guessed so far
#secret = full secret word/phrase
secret_list = list(secret)
guess_list = list(guessed)
... | 0.170854 | 0.089058 |
TEMPLATE = '''// AUTO-GENERATED FILE. DO NOT MODIFY. GENERATED BY scripts/generate_can_enums.py
# pragma once
namespace HWBRIDGE {{
constexpr uint32_t ROVER_CANBUS_FREQUENCY_HZ = {canbus_frequency_value};
constexpr uint16_t ROVER_CANID_FILTER_MASK = {canid_filter_mask}; // Use bits 5:10 for addressing, bits ... | scripts/generate_can_enums.py | TEMPLATE = '''// AUTO-GENERATED FILE. DO NOT MODIFY. GENERATED BY scripts/generate_can_enums.py
# pragma once
namespace HWBRIDGE {{
constexpr uint32_t ROVER_CANBUS_FREQUENCY_HZ = {canbus_frequency_value};
constexpr uint16_t ROVER_CANID_FILTER_MASK = {canid_filter_mask}; // Use bits 5:10 for addressing, bits ... | 0.401101 | 0.273605 |
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
from unipath import Path
import dj_database_url
from decouple import config, Csv
from mendeley import Mendeley
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
CSRF_COOKIE_SECURE = config('CSRF_COOKIE_SECURE', default=True, cast=bo... | parsifal/settings.py | from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
from unipath import Path
import dj_database_url
from decouple import config, Csv
from mendeley import Mendeley
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
CSRF_COOKIE_SECURE = config('CSRF_COOKIE_SECURE', default=True, cast=bo... | 0.193795 | 0.044183 |
from __future__ import print_function, division
from caffe import layers as L
from caffe import params as P
__author__ = '<NAME>'
__copyright__ = 'Copyright (c) 2016, <NAME>'
__email__ = '<EMAIL>'
__license__ = 'MIT'
def make_image_label_data(image_list_path, label_list_path, batch_size,
... | network.py |
from __future__ import print_function, division
from caffe import layers as L
from caffe import params as P
__author__ = '<NAME>'
__copyright__ = 'Copyright (c) 2016, <NAME>'
__email__ = '<EMAIL>'
__license__ = 'MIT'
def make_image_label_data(image_list_path, label_list_path, batch_size,
... | 0.808105 | 0.170543 |
import os
import json
import getopt
import urllib
import urllib2
from viper.common.out import *
from viper.common.abstracts import Module
from viper.core.session import __sessions__
VIRUSTOTAL_URL = 'https://www.virustotal.com/vtapi/v2/file/report'
KEY = '<KEY>'
class VirusTotal(Module):
cmd = 'virustotal'
... | modules/virustotal.py |
import os
import json
import getopt
import urllib
import urllib2
from viper.common.out import *
from viper.common.abstracts import Module
from viper.core.session import __sessions__
VIRUSTOTAL_URL = 'https://www.virustotal.com/vtapi/v2/file/report'
KEY = '<KEY>'
class VirusTotal(Module):
cmd = 'virustotal'
... | 0.212804 | 0.069321 |
import sys
import pickle
import re
from portfolio import build_index, check_for_real_ticker
from utils import yes_no_prompt, parse_tickers, parse_input
HELP_FUNC = {'build' : 'Build Index from input ticker symbols',
'exist' : 'Prints existing Index objects being tracked',
'table' : 'Pick exi... | commands.py | import sys
import pickle
import re
from portfolio import build_index, check_for_real_ticker
from utils import yes_no_prompt, parse_tickers, parse_input
HELP_FUNC = {'build' : 'Build Index from input ticker symbols',
'exist' : 'Prints existing Index objects being tracked',
'table' : 'Pick exi... | 0.200636 | 0.12932 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA @UnusedWildImport
import io
import warnings
import numpy as np
from matplotlib import path as mplpath
from matplotlib import collections, patches, transforms
from decorato... | IRIS_data_download/IRIS_download_support/obspy/imaging/beachball.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA @UnusedWildImport
import io
import warnings
import numpy as np
from matplotlib import path as mplpath
from matplotlib import collections, patches, transforms
from decorato... | 0.847337 | 0.393385 |
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
import ll1
MAX = 10
class Gui:
def __init__(self, master):
self.init_input = StringVar()
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++... | CompilerTheory_exp/exp2/gui.py |
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
import ll1
MAX = 10
class Gui:
def __init__(self, master):
self.init_input = StringVar()
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++... | 0.313105 | 0.099208 |
import json
from calm.dsl.runbooks import read_local_file
from calm.dsl.runbooks import runbook
from calm.dsl.runbooks import RunbookTask as Task, RunbookVariable as Variable
from calm.dsl.runbooks import CalmEndpoint as Endpoint
from calm.dsl.config import get_context
from utils import read_test_config, change_uuids
... | tests/api_interface/test_runbooks/test_files/http_task.py | import json
from calm.dsl.runbooks import read_local_file
from calm.dsl.runbooks import runbook
from calm.dsl.runbooks import RunbookTask as Task, RunbookVariable as Variable
from calm.dsl.runbooks import CalmEndpoint as Endpoint
from calm.dsl.config import get_context
from utils import read_test_config, change_uuids
... | 0.515376 | 0.142381 |
from FreeTAKServer.controllers.DatabaseControllers.DatabaseController import DatabaseController
from defusedxml import ElementTree as etree
from FreeTAKServer.model.ExCheck.templateInstanceContents import templateInstanceContents
import hashlib
import os
from FreeTAKServer.model.ExCheck.template import template
from Fr... | FreeTAKServer/controllers/ExCheckControllers/templateToJsonSerializer.py | from FreeTAKServer.controllers.DatabaseControllers.DatabaseController import DatabaseController
from defusedxml import ElementTree as etree
from FreeTAKServer.model.ExCheck.templateInstanceContents import templateInstanceContents
import hashlib
import os
from FreeTAKServer.model.ExCheck.template import template
from Fr... | 0.183082 | 0.085901 |
from qiskit import QuantumCircuit
import numpy as np
from qiskit.circuit.library import Diagonal
def dj_problem_oracle(problem, to_gate=True):
"""Returns a 5-qubit Deutsch-Joza Oracle"""
qc = QuantumCircuit(5)
int(problem)
if problem == 1:
for q in range(4):
qc.cx(q, 4)
elif pro... | qiskit-textbook-src/qiskit_textbook/problems/__init__.py | from qiskit import QuantumCircuit
import numpy as np
from qiskit.circuit.library import Diagonal
def dj_problem_oracle(problem, to_gate=True):
"""Returns a 5-qubit Deutsch-Joza Oracle"""
qc = QuantumCircuit(5)
int(problem)
if problem == 1:
for q in range(4):
qc.cx(q, 4)
elif pro... | 0.842798 | 0.706836 |
import scrapy
from scrapy.selector import Selector
from scrapy_selenium import SeleniumRequest
from selenium.webdriver.common.keys import Keys
import time
import datetime
class BoroondaraSpiderSpider(scrapy.Spider):
name = 'boroondara_spider'
def remove_nonUTF_char(self, value):
try:
filte... | UpWork_Projects/Will Farell_Spiders/boroondara/boroondara/spiders/boroondara_spider.py | import scrapy
from scrapy.selector import Selector
from scrapy_selenium import SeleniumRequest
from selenium.webdriver.common.keys import Keys
import time
import datetime
class BoroondaraSpiderSpider(scrapy.Spider):
name = 'boroondara_spider'
def remove_nonUTF_char(self, value):
try:
filte... | 0.218003 | 0.136148 |
import stare
import time
import pickle
import logging
import pytest
# set some things on user that we expect to persist or not persist
_name = 'Test User'
_response = 'A response'
_status_code = 200
_access_token = '<PASSWORD>'
_raw_id_token = '<PASSWORD>'
@pytest.fixture
def user_temp(tmpdir):
temp = tmpdir.joi... | tests/test_user.py | import stare
import time
import pickle
import logging
import pytest
# set some things on user that we expect to persist or not persist
_name = 'Test User'
_response = 'A response'
_status_code = 200
_access_token = '<PASSWORD>'
_raw_id_token = '<PASSWORD>'
@pytest.fixture
def user_temp(tmpdir):
temp = tmpdir.joi... | 0.349977 | 0.267522 |
__version__ = '1.0.0-beta.1'
import enum
from io import StringIO
from typing import Iterable, Iterator, Optional, TextIO, Tuple, Union
__all__ = ['parse_msd', 'MSDParserError']
def trailing_newline(line: str):
end_of_line = len(line.rstrip('\r\n'))
return line[end_of_line:]
class State(enum.Enum):
""... | msdparser/__init__.py | __version__ = '1.0.0-beta.1'
import enum
from io import StringIO
from typing import Iterable, Iterator, Optional, TextIO, Tuple, Union
__all__ = ['parse_msd', 'MSDParserError']
def trailing_newline(line: str):
end_of_line = len(line.rstrip('\r\n'))
return line[end_of_line:]
class State(enum.Enum):
""... | 0.809464 | 0.355887 |
from __future__ import annotations
from enum import Enum
from typing import Optional
from sqlalchemy import Column, Enum as EnumType, ForeignKey, Integer, String, Boolean, select
from sqlalchemy.orm import relationship, backref, Session
from raconteur.models.base import Base
from raconteur.plugin import PluginModelM... | raconteur/plugins/unknown_armies/models.py | from __future__ import annotations
from enum import Enum
from typing import Optional
from sqlalchemy import Column, Enum as EnumType, ForeignKey, Integer, String, Boolean, select
from sqlalchemy.orm import relationship, backref, Session
from raconteur.models.base import Base
from raconteur.plugin import PluginModelM... | 0.86031 | 0.139983 |
__author__ = '<NAME>'
from dataclasses import dataclass
import sys
from pathlib import Path
from spacy.tokens.doc import Doc
from zensols.config import Configurable
from zensols.nlp import (
FeatureDocument, FeatureDocumentParser, LanguageResource
)
import logging
logger = logging.getLogger(__name__)
@dataclass... | example/config/app.py | __author__ = '<NAME>'
from dataclasses import dataclass
import sys
from pathlib import Path
from spacy.tokens.doc import Doc
from zensols.config import Configurable
from zensols.nlp import (
FeatureDocument, FeatureDocumentParser, LanguageResource
)
import logging
logger = logging.getLogger(__name__)
@dataclass... | 0.3027 | 0.22595 |
from collections import namedtuple, deque
import torch
import random
import numpy as np
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class ReplayBuffer:
"""Fixed-size buffer to store experience tuples."""
def __init__(self, buffer_size, batch_size):
"""Initialize a ReplayB... | p3_collab-compet/replay_buffer.py | from collections import namedtuple, deque
import torch
import random
import numpy as np
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class ReplayBuffer:
"""Fixed-size buffer to store experience tuples."""
def __init__(self, buffer_size, batch_size):
"""Initialize a ReplayB... | 0.906295 | 0.416619 |
import os
import copy
import pathlib
from dffml.util.os import prepend_to_path
from dffml.util.net import cached_download_unpack_archive
from dffml.util.asynctestcase import AsyncTestCase
from shouldi.golangci_lint import run_golangci_lint
class TestRunGolangci_lintOp(AsyncTestCase):
async def setUp(self):
... | examples/shouldi/tests/test_golangci_lint.py | import os
import copy
import pathlib
from dffml.util.os import prepend_to_path
from dffml.util.net import cached_download_unpack_archive
from dffml.util.asynctestcase import AsyncTestCase
from shouldi.golangci_lint import run_golangci_lint
class TestRunGolangci_lintOp(AsyncTestCase):
async def setUp(self):
... | 0.443359 | 0.193871 |
from subprocess import run, PIPE, TimeoutExpired
from glob import glob
import argparse
def parse_command_line(cmd_argv=None):
parser = argparse.ArgumentParser(description='Run all tests for dynamite.')
parser.add_argument('--mpiexec', default='mpirun',
help='Command to launch an MPI jo... | tests/integration/run_all_tests.py | from subprocess import run, PIPE, TimeoutExpired
from glob import glob
import argparse
def parse_command_line(cmd_argv=None):
parser = argparse.ArgumentParser(description='Run all tests for dynamite.')
parser.add_argument('--mpiexec', default='mpirun',
help='Command to launch an MPI jo... | 0.465387 | 0.122444 |
from __future__ import annotations
from abc import ABC, abstractmethod
from collections import OrderedDict, Sequence, Mapping
from dataclasses import dataclass
from enum import Enum
from typing import Hashable, Iterable
class Missing:
def __str__(self):
return ''
missing = Missing()
class Diff(ABC):
... | django_ontruck/utils/diff_dicts.py | from __future__ import annotations
from abc import ABC, abstractmethod
from collections import OrderedDict, Sequence, Mapping
from dataclasses import dataclass
from enum import Enum
from typing import Hashable, Iterable
class Missing:
def __str__(self):
return ''
missing = Missing()
class Diff(ABC):
... | 0.949012 | 0.328772 |
import logging
from typing import List
from pdpc_decisions.classes import PDPCDecisionItem, Options, PDFFile
from pdpc_decisions.download_file import check_pdf
logger = logging.getLogger(__name__)
def get_enforcement(items: List[PDPCDecisionItem], options) -> None:
"""
Get enforcement details for a list of ... | pdpc_decisions/scraper_extras.py | import logging
from typing import List
from pdpc_decisions.classes import PDPCDecisionItem, Options, PDFFile
from pdpc_decisions.download_file import check_pdf
logger = logging.getLogger(__name__)
def get_enforcement(items: List[PDPCDecisionItem], options) -> None:
"""
Get enforcement details for a list of ... | 0.81457 | 0.285142 |
queries = {
"column": {
"head": "select %s from %s limit %d;",
"all": "select %s from %s;",
"unique": "select distinct %s from %s;",
"sample": "select %s from %s order by random() limit %d;"
},
"table": {
"select": "select %s from %s;",
"head": "select * from ... | db/queries/postgres.py | queries = {
"column": {
"head": "select %s from %s limit %d;",
"all": "select %s from %s;",
"unique": "select distinct %s from %s;",
"sample": "select %s from %s order by random() limit %d;"
},
"table": {
"select": "select %s from %s;",
"head": "select * from ... | 0.398758 | 0.218378 |
from tests.unit_tests.test_lattice import zr, pincell1, pincell2, rlat2
def test_discretization_degenerate(rlat2):
rlat_clone = rlat2.clone()
rlat_clone.discretize()
assert rlat_clone.get_universe((0, 0)).id !=\
rlat_clone.get_universe((1, 0)).id
assert rlat_clone.get_universe((1, 0)).id !=... | tests/unit_tests/test_lattice_discretization.py | from tests.unit_tests.test_lattice import zr, pincell1, pincell2, rlat2
def test_discretization_degenerate(rlat2):
rlat_clone = rlat2.clone()
rlat_clone.discretize()
assert rlat_clone.get_universe((0, 0)).id !=\
rlat_clone.get_universe((1, 0)).id
assert rlat_clone.get_universe((1, 0)).id !=... | 0.49585 | 0.632786 |
import unittest
import ast
from dissect.traits.s03.s03 import s03_curve_function
from dissect.traits.example_curves import curve_names
results = {
'secp112r2': {
"{'weight': 1}": {
'Arithmetic mean': 110.84197998046875,
'Geometric mean': 110.83241195110318,
'Quadratic mea... | dissect/unit_tests/test_s03.py | import unittest
import ast
from dissect.traits.s03.s03 import s03_curve_function
from dissect.traits.example_curves import curve_names
results = {
'secp112r2': {
"{'weight': 1}": {
'Arithmetic mean': 110.84197998046875,
'Geometric mean': 110.83241195110318,
'Quadratic mea... | 0.689933 | 0.510863 |
from portality import models, lcc
from portality.crosswalks.journal_form import JournalGenericXWalk, JournalFormXWalk
class ApplicationFormXWalk(JournalGenericXWalk):
_formFields2objectFields = {
"alternative_title" : "bibjson.alternative_title",
"apc_charges.apc_max" : "bibjson.apc.max.price",
... | portality/crosswalks/application_form.py | from portality import models, lcc
from portality.crosswalks.journal_form import JournalGenericXWalk, JournalFormXWalk
class ApplicationFormXWalk(JournalGenericXWalk):
_formFields2objectFields = {
"alternative_title" : "bibjson.alternative_title",
"apc_charges.apc_max" : "bibjson.apc.max.price",
... | 0.619011 | 0.128143 |
import time
import click
from datetime import datetime
from beijing_bus import BeijingBus, cache
@click.group()
def cmd_group():
pass
@cmd_group.command(help='build or re-build the cache')
def build_cache():
import logging
logging.basicConfig(level=logging.INFO)
cache.invalidate(hard=True)
Bei... | manage.py |
import time
import click
from datetime import datetime
from beijing_bus import BeijingBus, cache
@click.group()
def cmd_group():
pass
@cmd_group.command(help='build or re-build the cache')
def build_cache():
import logging
logging.basicConfig(level=logging.INFO)
cache.invalidate(hard=True)
Bei... | 0.190197 | 0.102529 |