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 datetime
import six
from gcloud._helpers import _datetime_to_rfc3339
from gcloud._helpers import _rfc3339_to_datetime
from gcloud.exceptions import NotFound
class StringValue(object):
"""StringValues hold individual text values for a given field
See:
https://cloud.google.com/search/reference/res... | gcloud/search/document.py | import datetime
import six
from gcloud._helpers import _datetime_to_rfc3339
from gcloud._helpers import _rfc3339_to_datetime
from gcloud.exceptions import NotFound
class StringValue(object):
"""StringValues hold individual text values for a given field
See:
https://cloud.google.com/search/reference/res... | 0.835517 | 0.469642 |
from pprint import pprint
import numpy as np
DIRECTION_FORWARD = 0
DIRECTION_BACKWARD = 1
def build_graph(pairs, to):
G = {to: {}}
for from_, to, weight in pairs:
if from_ not in G:
G[from_] = {}
G[from_][to] = weight
return G
def build_parents_graph(pairs, s):
G = {s: ... | src/lab8_ford-fulkerson/ford.py | from pprint import pprint
import numpy as np
DIRECTION_FORWARD = 0
DIRECTION_BACKWARD = 1
def build_graph(pairs, to):
G = {to: {}}
for from_, to, weight in pairs:
if from_ not in G:
G[from_] = {}
G[from_][to] = weight
return G
def build_parents_graph(pairs, s):
G = {s: ... | 0.194406 | 0.453322 |
from .Common import printExit
from .SolutionStructs import Solution
from . import YAMLIO
import csv
def getSummationKeys(header):
keys=[]
for i in range(7, len(header)):
keystr = header[i].split("=")[1].strip()
key = int(keystr)
keys.append(key)
return keys
def makeKey(row):
key=row[3]
for i i... | Tensile/SolutionSelectionLibrary.py |
from .Common import printExit
from .SolutionStructs import Solution
from . import YAMLIO
import csv
def getSummationKeys(header):
keys=[]
for i in range(7, len(header)):
keystr = header[i].split("=")[1].strip()
key = int(keystr)
keys.append(key)
return keys
def makeKey(row):
key=row[3]
for i i... | 0.236164 | 0.15961 |
import torch
import torch.optim.optimizer import Optimizer
class LARS(Optimizer):
def __init__(self, sub_optimizer, eps, trust_coefficient):
self.optim = sub_optimizer
self.eps = eps
self.trust_coef = trust_coefficient
self.adaptive_lr = torch.ones([])
@classmethod
def... | code/optimizer/lars.py | import torch
import torch.optim.optimizer import Optimizer
class LARS(Optimizer):
def __init__(self, sub_optimizer, eps, trust_coefficient):
self.optim = sub_optimizer
self.eps = eps
self.trust_coef = trust_coefficient
self.adaptive_lr = torch.ones([])
@classmethod
def... | 0.884139 | 0.235636 |
from __future__ import with_statement
from __future__ import absolute_import
import random, fileinput
from datetime import datetime, date, time, timedelta
from io import open
from itertools import izip
class ScheduleMaker(object):
u"""Creates schedules for use in automation tasks.
The schedules created shoul... | scripts/ScheduleManager/ScheduleManager.py | from __future__ import with_statement
from __future__ import absolute_import
import random, fileinput
from datetime import datetime, date, time, timedelta
from io import open
from itertools import izip
class ScheduleMaker(object):
u"""Creates schedules for use in automation tasks.
The schedules created shoul... | 0.799325 | 0.416678 |
import os
import argparse
import yaml
import datetime
import os.path
from shutil import copyfile
import subprocess
import evaluation_tools
import glob
TEMPDIR = "config/temp"
if __name__ == '__main__':
parser = argparse.ArgumentParser("./train_multiple.py", description='Train multiple models with the '
... | train/tasks/semantic/train_multiple.py | import os
import argparse
import yaml
import datetime
import os.path
from shutil import copyfile
import subprocess
import evaluation_tools
import glob
TEMPDIR = "config/temp"
if __name__ == '__main__':
parser = argparse.ArgumentParser("./train_multiple.py", description='Train multiple models with the '
... | 0.218586 | 0.062103 |
import logging
from typing import Iterable, Union
import discord
from discord.ext import commands, tasks
from discord.errors import HTTPException
from bot import constants
from bot.cogs.utils.checks import check_if_it_is_tortoise_guild
from bot.cogs.utils.embed_handler import success, warning, failure, authored, welc... | bot/cogs/tortoise_server.py | import logging
from typing import Iterable, Union
import discord
from discord.ext import commands, tasks
from discord.errors import HTTPException
from bot import constants
from bot.cogs.utils.checks import check_if_it_is_tortoise_guild
from bot.cogs.utils.embed_handler import success, warning, failure, authored, welc... | 0.571049 | 0.080213 |
import unittest
import hashlib
import os
import passph
BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
class PassphTests(unittest.TestCase):
def test_base_charlist_encode(self):
self.assertEqual(
passph.base_charlist_encode(b"The quick brown fox jumps over t... | lib/python/passph_test.py |
import unittest
import hashlib
import os
import passph
BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
class PassphTests(unittest.TestCase):
def test_base_charlist_encode(self):
self.assertEqual(
passph.base_charlist_encode(b"The quick brown fox jumps over t... | 0.424054 | 0.347426 |
import argparse
import logging
import os
import sys
import time
import numpy as np
import shap
import torch
import torch.nn.functional as F
import torchvision.models as models
from scipy.special import softmax
from sklearn.ensemble import RandomForestClassifier
from sklearn.externals import joblib
from sklearn.linear_... | generate_integrated_gradients.py | import argparse
import logging
import os
import sys
import time
import numpy as np
import shap
import torch
import torch.nn.functional as F
import torchvision.models as models
from scipy.special import softmax
from sklearn.ensemble import RandomForestClassifier
from sklearn.externals import joblib
from sklearn.linear_... | 0.754463 | 0.488222 |
import re
import requests
from bs4 import BeautifulSoup
from pprint import pprint
# links
def get_data(keyword):
def _get(page):
url = 'https://www.clien.net/service/search?q={}&sort=recency&p={}&boardCd=&isBoard=false'.format(keyword, page)
req = requests.get(url)
bs = Beau... | crawler.py | import re
import requests
from bs4 import BeautifulSoup
from pprint import pprint
# links
def get_data(keyword):
def _get(page):
url = 'https://www.clien.net/service/search?q={}&sort=recency&p={}&boardCd=&isBoard=false'.format(keyword, page)
req = requests.get(url)
bs = Beau... | 0.042157 | 0.064979 |
import io
from base64 import b64encode
from rest_framework import serializers
from .models import Application, Victim
from .helper import get_authorization_url
from .objects import Attachment
from django.contrib.sites.models import Site
from urllib.parse import urlparse
import magic
class ApplicationSerializer(seriali... | app/oauth_office365/serializers.py | import io
from base64 import b64encode
from rest_framework import serializers
from .models import Application, Victim
from .helper import get_authorization_url
from .objects import Attachment
from django.contrib.sites.models import Site
from urllib.parse import urlparse
import magic
class ApplicationSerializer(seriali... | 0.417153 | 0.113653 |
import matplotlib.pyplot as plt
import base64
from io import BytesIO
import numpy as np
def get_graph():
buffer=BytesIO()
plt.savefig(buffer,format='png')
buffer.seek(0)
image_png=buffer.getvalue()
graph=base64.b64encode(image_png)
graph=graph.decode('utf-8')
buffer.close()
return graph... | school/utils.py | import matplotlib.pyplot as plt
import base64
from io import BytesIO
import numpy as np
def get_graph():
buffer=BytesIO()
plt.savefig(buffer,format='png')
buffer.seek(0)
image_png=buffer.getvalue()
graph=base64.b64encode(image_png)
graph=graph.decode('utf-8')
buffer.close()
return graph... | 0.628977 | 0.471345 |
from py.test import raises
from pypy.conftest import gettestobjspace
class AppTestUnicodeData:
def setup_class(cls):
space = gettestobjspace(usemodules=('unicodedata',))
cls.space = space
def test_hangul_syllables(self):
import unicodedata
# Test all leading, vowel and trailing... | pypy/module/unicodedata/test/test_unicodedata.py | from py.test import raises
from pypy.conftest import gettestobjspace
class AppTestUnicodeData:
def setup_class(cls):
space = gettestobjspace(usemodules=('unicodedata',))
cls.space = space
def test_hangul_syllables(self):
import unicodedata
# Test all leading, vowel and trailing... | 0.352536 | 0.282074 |
import ctypes
import sysconfig
try:
import fcntl
# TODO check if on linux >= 3.15
libc = ctypes.cdll.LoadLibrary('libc.so.6')
libc_fcntl = libc.fcntl
type_of_size = {ctypes.sizeof(ctypes.c_short): ctypes.c_short,
ctypes.sizeof(ctypes.c_int): ctypes.c_int,
... | bare_locks/open.py | import ctypes
import sysconfig
try:
import fcntl
# TODO check if on linux >= 3.15
libc = ctypes.cdll.LoadLibrary('libc.so.6')
libc_fcntl = libc.fcntl
type_of_size = {ctypes.sizeof(ctypes.c_short): ctypes.c_short,
ctypes.sizeof(ctypes.c_int): ctypes.c_int,
... | 0.405684 | 0.289516 |
"""Tests for xts_result."""
import os
from absl.testing import absltest
from multitest_transport.util import xts_result
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'test_data')
class XtsResultTest(absltest.TestCase):
def testSummary(self):
with open(os.path.join(TEST_DATA_DIR, 'test_result.xml'... | multitest_transport/util/xts_result_test.py |
"""Tests for xts_result."""
import os
from absl.testing import absltest
from multitest_transport.util import xts_result
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'test_data')
class XtsResultTest(absltest.TestCase):
def testSummary(self):
with open(os.path.join(TEST_DATA_DIR, 'test_result.xml'... | 0.49585 | 0.259162 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('competition', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('ctf', '0001... | apps/info/migrations/0003_auto_20190805_2041.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('competition', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('ctf', '0001... | 0.517815 | 0.075517 |
import matplotlib.pyplot as plt
import requests
import sqlite3
class dianmarkuci() :
def __init__(self, kode, hargatotal, kuota):
self.kode = kode
self.hargatotal = hargatotal
self.kuota = kuota
def rental(self):
if (self.kode[1]) == "1":
print("Avanza", "In... | kelas_2c/dianmarkuci.py | import matplotlib.pyplot as plt
import requests
import sqlite3
class dianmarkuci() :
def __init__(self, kode, hargatotal, kuota):
self.kode = kode
self.hargatotal = hargatotal
self.kuota = kuota
def rental(self):
if (self.kode[1]) == "1":
print("Avanza", "In... | 0.067412 | 0.277614 |
import random
import cirq
import matplotlib.pyplot as plt
NUM_QUBITS = 7
POSITIONS = 2**NUM_QUBITS
INITIAL_POSITION_POW = NUM_QUBITS - 1
STEPS = 30
SAMPLES = 5000
_coin = cirq.LineQubit(0)
_qubits = cirq.LineQubit.range(1, NUM_QUBITS + 1)
def classical_walk():
results = {}
for _ in range(SAMPLES):
... | cirq/quantum_walk.py | import random
import cirq
import matplotlib.pyplot as plt
NUM_QUBITS = 7
POSITIONS = 2**NUM_QUBITS
INITIAL_POSITION_POW = NUM_QUBITS - 1
STEPS = 30
SAMPLES = 5000
_coin = cirq.LineQubit(0)
_qubits = cirq.LineQubit.range(1, NUM_QUBITS + 1)
def classical_walk():
results = {}
for _ in range(SAMPLES):
... | 0.438785 | 0.517327 |
from .elements import CompositeElement, DrawableElement
import math
class RobotElement(CompositeElement):
"""
TODO: allow user customization
"""
def __init__(self, controller, config_obj):
super().__init__()
# Load params from the user's sim/config.json
px_per_ft = conf... | lib/pyfrc/sim/field/robot_element.py | from .elements import CompositeElement, DrawableElement
import math
class RobotElement(CompositeElement):
"""
TODO: allow user customization
"""
def __init__(self, controller, config_obj):
super().__init__()
# Load params from the user's sim/config.json
px_per_ft = conf... | 0.622804 | 0.253237 |
import numpy as np
from nengo.builder.builder import Builder
from nengo.builder.operator import Operator
from nengo.builder.signal import Signal
from nengo.exceptions import BuildError
from nengo.neurons import NeuronType, RatesToSpikesNeuronType
from nengo.utils.numpy import is_array_like
class SimNeurons(Operator)... | nengo/builder/neurons.py | import numpy as np
from nengo.builder.builder import Builder
from nengo.builder.operator import Operator
from nengo.builder.signal import Signal
from nengo.exceptions import BuildError
from nengo.neurons import NeuronType, RatesToSpikesNeuronType
from nengo.utils.numpy import is_array_like
class SimNeurons(Operator)... | 0.881857 | 0.701502 |
# # need special branch of sacrebleu for thai bleu
# !pip uninstall -q sacrebleu
# !pip install -q git+https://github.com/cstorm125/sacrebleu.git@add_thai_tokenizer
# # written with transformers 4.6.0
# export WANDB_PROJECT=mariantmt-zh_cn-th
# python train_model.py --input_fname ../data/v1/Train.csv \
# --output... | scripts/train_model.py |
# # need special branch of sacrebleu for thai bleu
# !pip uninstall -q sacrebleu
# !pip install -q git+https://github.com/cstorm125/sacrebleu.git@add_thai_tokenizer
# # written with transformers 4.6.0
# export WANDB_PROJECT=mariantmt-zh_cn-th
# python train_model.py --input_fname ../data/v1/Train.csv \
# --output... | 0.537284 | 0.190028 |
import numpy as np
import pandas as pd
import lightgbm as lgb
import gc
import sklearn.datasets
from common.data import get_embedding_sizes, get_validation_index
from sklearn.model_selection import KFold, StratifiedKFold, train_test_split
from fastai.structured import *
from fastai.metrics import *
from fastai.colum... | common/fc.py | import numpy as np
import pandas as pd
import lightgbm as lgb
import gc
import sklearn.datasets
from common.data import get_embedding_sizes, get_validation_index
from sklearn.model_selection import KFold, StratifiedKFold, train_test_split
from fastai.structured import *
from fastai.metrics import *
from fastai.colum... | 0.819569 | 0.34494 |
import occo.infobroker as ib
import logging
import occo.util as util
from occo.infobroker import main_uds
log = logging.getLogger('occo.scaling')
datalog = logging.getLogger('occo.data.scaling')
def get_scaling_limits(node):
smin = max(node.get('scaling',dict()).get('min',1),1)
smax = max(node.get('scaling',... | occo/enactor/scaling.py | import occo.infobroker as ib
import logging
import occo.util as util
from occo.infobroker import main_uds
log = logging.getLogger('occo.scaling')
datalog = logging.getLogger('occo.data.scaling')
def get_scaling_limits(node):
smin = max(node.get('scaling',dict()).get('min',1),1)
smax = max(node.get('scaling',... | 0.277179 | 0.114121 |
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.impo... | pysnmp/ETHERNET-MIB.py | OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.impo... | 0.442637 | 0.201499 |
# The result of `supplement_range()` shows that
# every subset of `unicode.json` has about 138 ~ 189 chars.
# So I group every 150 chars of missing cjk into a new subset,
# which prefixed with `ex`.
import json
def supplement_range(unicode_range: str):
"""Returns supplemented range.
Parameters:
uni... | unicode.py |
# The result of `supplement_range()` shows that
# every subset of `unicode.json` has about 138 ~ 189 chars.
# So I group every 150 chars of missing cjk into a new subset,
# which prefixed with `ex`.
import json
def supplement_range(unicode_range: str):
"""Returns supplemented range.
Parameters:
uni... | 0.836388 | 0.613121 |
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from decimal import *
from django.core.validators import MinValueValidator, MaxValueValidator
class PerguruanTinggi(models.Model):
nama_perguruantinggi = models.CharField(max_lengt... | cari-pakar web/caripakar_app/models.py | from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from decimal import *
from django.core.validators import MinValueValidator, MaxValueValidator
class PerguruanTinggi(models.Model):
nama_perguruantinggi = models.CharField(max_lengt... | 0.398758 | 0.188193 |
import argparse
import pecan
from pecan import request
from pecan import response
from pecan import rest
import openid.extensions.sreg
import openid.server.server
from openid.store.filestore import FileOpenIDStore
from wsgiref import simple_server
class controller(rest.RestController):
_custom_actions = {
... | tools/openid_server.py |
import argparse
import pecan
from pecan import request
from pecan import response
from pecan import rest
import openid.extensions.sreg
import openid.server.server
from openid.store.filestore import FileOpenIDStore
from wsgiref import simple_server
class controller(rest.RestController):
_custom_actions = {
... | 0.483161 | 0.077308 |
import torch
from nnc.controllers.base import ControlledDynamics
from nnc.helpers.torch_utils.numerics import sin_difference, sin_difference_mem
class AdditiveControlKuramotoDynamics(ControlledDynamics):
def __init__(self,
interaction_matrix,
coupling_constant,
n... | nnc/controllers/baselines/oscillators/dynamics.py | import torch
from nnc.controllers.base import ControlledDynamics
from nnc.helpers.torch_utils.numerics import sin_difference, sin_difference_mem
class AdditiveControlKuramotoDynamics(ControlledDynamics):
def __init__(self,
interaction_matrix,
coupling_constant,
n... | 0.917919 | 0.541773 |
import json
from logging import error, exception, warning, info
from requests import post as request_post
from uuid import UUID
from django.db.models import (
CharField,
DecimalField,
ForeignKey,
JSONField,
PositiveIntegerField,
PROTECT,
)
from django.db.utils import IntegrityError
from eth_uti... | backend/networks/models.py | import json
from logging import error, exception, warning, info
from requests import post as request_post
from uuid import UUID
from django.db.models import (
CharField,
DecimalField,
ForeignKey,
JSONField,
PositiveIntegerField,
PROTECT,
)
from django.db.utils import IntegrityError
from eth_uti... | 0.666931 | 0.087213 |
from pathlib import Path
from typing import Union
import h5py
import numpy
from easistrain.EDD.fitEDD import fitEDD
ORIENTATION = "OR1"
def generate_config(tmp_path: Path, test_data_path: Union[Path, str]) -> dict:
with h5py.File(test_data_path, "r") as test_file:
nb_peaks_in_boxes = test_file[f"{ORIENTA... | tests/EDD/test_fit.py | from pathlib import Path
from typing import Union
import h5py
import numpy
from easistrain.EDD.fitEDD import fitEDD
ORIENTATION = "OR1"
def generate_config(tmp_path: Path, test_data_path: Union[Path, str]) -> dict:
with h5py.File(test_data_path, "r") as test_file:
nb_peaks_in_boxes = test_file[f"{ORIENTA... | 0.635336 | 0.33035 |
from pbu import AbstractMongoStore
class Project:
"""
Object class representing a document in this database collection.
"""
def __init__(self):
self.name = None
self.id = None
self.image_count = 0
self.annotation_count = 0
self.annotation_types = {}
def to... | storage/project_store.py | from pbu import AbstractMongoStore
class Project:
"""
Object class representing a document in this database collection.
"""
def __init__(self):
self.name = None
self.id = None
self.image_count = 0
self.annotation_count = 0
self.annotation_types = {}
def to... | 0.861989 | 0.210219 |
import sys
try:
import fabric.version # NOQA
is_fabric1 = True
# This way we can have a single `expect UnexpectedExit` statement instead of having two separate code paths for fabric1/fabric2
UnexpectedExit = SystemExit
# This way we can have a single `expect Exit` when asserting for `abort` dur... | hammer/util.py | import sys
try:
import fabric.version # NOQA
is_fabric1 = True
# This way we can have a single `expect UnexpectedExit` statement instead of having two separate code paths for fabric1/fabric2
UnexpectedExit = SystemExit
# This way we can have a single `expect Exit` when asserting for `abort` dur... | 0.410284 | 0.354042 |
import os
import time
import argparse
import random
import numpy as np
import torch
import logging
import logging.config
from utils.tf_logger import TfLogger
import uuid
import sys
import pathlib
import glob
import shutil
category_names = ['Bag', 'Bed', 'Bottle', 'Bowl', 'Chair', 'Clock', 'Dishwasher', 'Display', 'Do... | deep_gcns_torch/examples/part_sem_seg/config.py | import os
import time
import argparse
import random
import numpy as np
import torch
import logging
import logging.config
from utils.tf_logger import TfLogger
import uuid
import sys
import pathlib
import glob
import shutil
category_names = ['Bag', 'Bed', 'Bottle', 'Bowl', 'Chair', 'Clock', 'Dishwasher', 'Display', 'Do... | 0.436382 | 0.068787 |
import datetime
import logging
import os
import shutil
import sqlite3
import tempfile
import pytest
from c4.backends.sharedSQLite import (DBManager,
SharedSqliteDBBackend)
from c4.system.backend import BackendInfo
log = logging.getLogger(__name__)
@pytest.fixture(scope="functi... | tests/test_sharedSQLite.py | import datetime
import logging
import os
import shutil
import sqlite3
import tempfile
import pytest
from c4.backends.sharedSQLite import (DBManager,
SharedSqliteDBBackend)
from c4.system.backend import BackendInfo
log = logging.getLogger(__name__)
@pytest.fixture(scope="functi... | 0.361165 | 0.298568 |
import math
import os
import src.analysis.dynamic_entropy as path_entropy
import src.analysis.tms_entropy as tms_entropy
DEFAULT_OUTFILE = 'plot.pdf'
PREAMBLE = r"""
\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage{esvect}
\usepackage{nicefrac}
\u... | plot/utils.py | import math
import os
import src.analysis.dynamic_entropy as path_entropy
import src.analysis.tms_entropy as tms_entropy
DEFAULT_OUTFILE = 'plot.pdf'
PREAMBLE = r"""
\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage{esvect}
\usepackage{nicefrac}
\u... | 0.371365 | 0.620018 |
from utils import *
from sklearn.metrics import auc
def parse_args():
import argparse
parser = argparse.ArgumentParser(description='Benchmark methods')
parser.add_argument('method', type=str,
help='Benchmarking method to use')
parser.add_argument('virus', type=str,
... | bin/escape_energy.py | from utils import *
from sklearn.metrics import auc
def parse_args():
import argparse
parser = argparse.ArgumentParser(description='Benchmark methods')
parser.add_argument('method', type=str,
help='Benchmarking method to use')
parser.add_argument('virus', type=str,
... | 0.439988 | 0.153771 |
from abc import ABC, abstractmethod
from typing import Any, Type, List, Union, Optional
from inspect import signature, Parameter
from bson import ObjectId
from extutils.flags import is_flag_class
from .logger import LOGGER
__all__ = ("arg_type_ensure", "TypeCastingFailedError", "BaseDataTypeConverter", "NonSafeDataT... | extutils/checker/arg.py | from abc import ABC, abstractmethod
from typing import Any, Type, List, Union, Optional
from inspect import signature, Parameter
from bson import ObjectId
from extutils.flags import is_flag_class
from .logger import LOGGER
__all__ = ("arg_type_ensure", "TypeCastingFailedError", "BaseDataTypeConverter", "NonSafeDataT... | 0.923601 | 0.34091 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('open_now', '0006_auto_20210416_2056'),
]
operations = [
migrations.CreateModel(
name='OpeningHours',
fields=[
('id'... | open_now/migrations/0007_auto_20210416_2113.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('open_now', '0006_auto_20210416_2056'),
]
operations = [
migrations.CreateModel(
name='OpeningHours',
fields=[
('id'... | 0.541651 | 0.182826 |
import argparse
from itertools import chain
import math
import time
import torch
import numpy as np
import matplotlib.pyplot as plt
from imageio import imwrite
from fast_transformers.builders import RecurrentEncoderBuilder
from main import ImageGenerator
from image_datasets import add_dataset_arguments, get_dataset... | image-generation/prediction.py |
import argparse
from itertools import chain
import math
import time
import torch
import numpy as np
import matplotlib.pyplot as plt
from imageio import imwrite
from fast_transformers.builders import RecurrentEncoderBuilder
from main import ImageGenerator
from image_datasets import add_dataset_arguments, get_dataset... | 0.81604 | 0.350533 |
from __future__ import division, print_function
import tensorflow as tf
import numpy as np
import os
import pprint
import sys
import keras
from keras.models import Sequential, Model
from keras.layers import Dense, Activation, Dropout, Input
from keras.utils import to_categorical
from keras import regularizers, initiali... | code/data process/Autoencode.py | from __future__ import division, print_function
import tensorflow as tf
import numpy as np
import os
import pprint
import sys
import keras
from keras.models import Sequential, Model
from keras.layers import Dense, Activation, Dropout, Input
from keras.utils import to_categorical
from keras import regularizers, initiali... | 0.578567 | 0.20093 |
import random
# use queue to move() more efficiently
# combine with dict{} to locate the values
class Game:
def __init__(self):
self.score = 0
self.merge = 0 # indicator of merge occurance
# 0: continue, 1: lose
self.game_state = 0
# faster
self.board = [[0 for _ ... | game2048.py |
import random
# use queue to move() more efficiently
# combine with dict{} to locate the values
class Game:
def __init__(self):
self.score = 0
self.merge = 0 # indicator of merge occurance
# 0: continue, 1: lose
self.game_state = 0
# faster
self.board = [[0 for _ ... | 0.437343 | 0.315209 |
class MorseConverter:
special_chars = ['.', ',', '?', ' ']
alphabet_to_morse = {'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', 'f':'..-.', 'g':'--.', 'h':'....', \
'i': '..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--', 'n':'-.', 'o':'---', 'p':'.--.', \
'q': '... | morse_converter.py | class MorseConverter:
special_chars = ['.', ',', '?', ' ']
alphabet_to_morse = {'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', 'f':'..-.', 'g':'--.', 'h':'....', \
'i': '..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--', 'n':'-.', 'o':'---', 'p':'.--.', \
'q': '... | 0.487551 | 0.493164 |
import os
import json
# Check if in a working git repository
def is_git_repo():
cmd = 'git rev-parse --is-inside-work-tree'
stream = os.popen(cmd)
output = stream.read()
return output == 'true\n'
# Check if branch is present in repo
def branch_in_local(branch):
cmd = 'git branch --list {0}'.form... | gitdit/utils/git_util.py | import os
import json
# Check if in a working git repository
def is_git_repo():
cmd = 'git rev-parse --is-inside-work-tree'
stream = os.popen(cmd)
output = stream.read()
return output == 'true\n'
# Check if branch is present in repo
def branch_in_local(branch):
cmd = 'git branch --list {0}'.form... | 0.166269 | 0.120983 |
import datetime
import logging
import os
import re
import time
import functest.utils.functest_constants as ft_constants
import functest.utils.functest_utils as ft_utils
class Foundation:
def __init__(self):
# currentpath = os.getcwd()
currentpath = '%s/sdn/onos/teston/ci' % ft_constants.FUNCTES... | functest/opnfv_tests/sdn/onos/teston/adapters/foundation.py | import datetime
import logging
import os
import re
import time
import functest.utils.functest_constants as ft_constants
import functest.utils.functest_utils as ft_utils
class Foundation:
def __init__(self):
# currentpath = os.getcwd()
currentpath = '%s/sdn/onos/teston/ci' % ft_constants.FUNCTES... | 0.301671 | 0.074568 |
import math
import random
villages_to_fake = ["407|498", "415|498", "401|492", "410|490", "403|486", "402|491", "402|489", "409|473", "410|475",
"402|479", "405|490", "408|498", "411|499", "413|489", "401|495", "404|494", "402|485", "401|486",
"403|498", "404|499", "405|499", "4... | fake_plan.py | import math
import random
villages_to_fake = ["407|498", "415|498", "401|492", "410|490", "403|486", "402|491", "402|489", "409|473", "410|475",
"402|479", "405|490", "408|498", "411|499", "413|489", "401|495", "404|494", "402|485", "401|486",
"403|498", "404|499", "405|499", "4... | 0.665193 | 0.380414 |
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverse_between(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
if not head.next or left == right:
return he... | 0/92_reverse_linked_list_II/main.py | from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverse_between(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
if not head.next or left == right:
return he... | 0.911842 | 0.372334 |
import os
import core
class PathInfo(object):
"""
路径相关的类
"""
def __init__(self, arch, project_folder):
self.project_folder = project_folder
self.arch = arch
# build 根路径 project_floder/build
self.build_base_path = os.path.join(self.project_folder, "build")
#... | core/info/tmake_path_info.py | import os
import core
class PathInfo(object):
"""
路径相关的类
"""
def __init__(self, arch, project_folder):
self.project_folder = project_folder
self.arch = arch
# build 根路径 project_floder/build
self.build_base_path = os.path.join(self.project_folder, "build")
#... | 0.236516 | 0.058831 |
from __future__ import print_function
import argparse
import csv
import json
import sys
import os
import vpr_io_place
from lib.parse_pcf import parse_simple_pcf
def main():
parser = argparse.ArgumentParser(
description='Convert a PCF file into a VPR io.place file.'
)
parser.add_argument(
"... | xc/common/utils/prjxray_create_ioplace.py | from __future__ import print_function
import argparse
import csv
import json
import sys
import os
import vpr_io_place
from lib.parse_pcf import parse_simple_pcf
def main():
parser = argparse.ArgumentParser(
description='Convert a PCF file into a VPR io.place file.'
)
parser.add_argument(
"... | 0.458106 | 0.100172 |
import argparse
from datetime import datetime
import glob
import logging
from math import floor
import numpy as np
import os
import pandas as pd
import seaborn as sns; sns.set(color_codes=True)
import sys
try:
from utilities.utilities import _ALL_ABBR, _ALL_CANCERS
except ModuleNotFoundError:
sys.path.append(
... | figures_and_analysis/fig2C_cell_of_origin_heatmap.py | import argparse
from datetime import datetime
import glob
import logging
from math import floor
import numpy as np
import os
import pandas as pd
import seaborn as sns; sns.set(color_codes=True)
import sys
try:
from utilities.utilities import _ALL_ABBR, _ALL_CANCERS
except ModuleNotFoundError:
sys.path.append(
... | 0.441432 | 0.149531 |
import dataclasses
import pickle
from typing import Dict, Optional
import hydra
from hydra.core.config_store import ConfigStore
import pytorch_lightning
import pytorch_lightning.callbacks
import tqdm
from torch_geometric.transforms import Compose
from autobahn.transform import Pathifier, Cyclifier
from autobahn.ex... | src/autobahn/experiments/test_on_zinc.py |
import dataclasses
import pickle
from typing import Dict, Optional
import hydra
from hydra.core.config_store import ConfigStore
import pytorch_lightning
import pytorch_lightning.callbacks
import tqdm
from torch_geometric.transforms import Compose
from autobahn.transform import Pathifier, Cyclifier
from autobahn.ex... | 0.849269 | 0.273568 |
import HostTools
class HostsFile(object):
def __init__(self, filepath):
self.filepath = filepath
with open(filepath, 'r') as textFile:
text = textFile.read()
self.lines = _parseHosts(text)
def __str__(self):
output = ''
for notComment, comment, ip, hosts in self.lines:
if ... | Hosts.py |
import HostTools
class HostsFile(object):
def __init__(self, filepath):
self.filepath = filepath
with open(filepath, 'r') as textFile:
text = textFile.read()
self.lines = _parseHosts(text)
def __str__(self):
output = ''
for notComment, comment, ip, hosts in self.lines:
if ... | 0.124266 | 0.059346 |
from datetime import date, datetime
from unittest import TestCase
from django.template import engines
from pytz import timezone
class DatetimesExtensionTests(TestCase):
def setUp(self):
self.engine = engines["wagtail-env"]
def test_date_filter(self):
tmpl = self.engine.from_string("{{ d | d... | cfgov/v1/tests/jinja2tags/test_datetimes.py | from datetime import date, datetime
from unittest import TestCase
from django.template import engines
from pytz import timezone
class DatetimesExtensionTests(TestCase):
def setUp(self):
self.engine = engines["wagtail-env"]
def test_date_filter(self):
tmpl = self.engine.from_string("{{ d | d... | 0.727589 | 0.35474 |
import os
import argparse
import time
import torch.utils.model_zoo as model_zoo
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
import torch.backends.cudnn as cudnn
import torchvision
import datasets
from m... | train.py | import os
import argparse
import time
import torch.utils.model_zoo as model_zoo
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
import torch.backends.cudnn as cudnn
import torchvision
import datasets
from m... | 0.572842 | 0.217795 |
def insertSort(data_list):
finish_list = []
finish_list.append(data_list[0])
for num in range(1, len(data_list)):
for pre in range(0, num):
# 如果待加入的数据已经比已排好的最小数据还小,直接放在最前面就行
if data_list[num] <= finish_list[pre]:
finish_list.insert(pre, data_list[num])
... | python_study/py/algorithm/insertSort.py | def insertSort(data_list):
finish_list = []
finish_list.append(data_list[0])
for num in range(1, len(data_list)):
for pre in range(0, num):
# 如果待加入的数据已经比已排好的最小数据还小,直接放在最前面就行
if data_list[num] <= finish_list[pre]:
finish_list.insert(pre, data_list[num])
... | 0.158174 | 0.583203 |
import json
import pytest
import tornado.ioloop
import util.net
import pool.proc
import web
def test_non_2XX_codes():
async def handler(req):
1 / 0
app = web.app([('/', {'get': handler})])
with web.test(app) as url:
resp = web.get_sync(url)
assert '1 / 0' not in resp['body']
... | tests/test_web.py | import json
import pytest
import tornado.ioloop
import util.net
import pool.proc
import web
def test_non_2XX_codes():
async def handler(req):
1 / 0
app = web.app([('/', {'get': handler})])
with web.test(app) as url:
resp = web.get_sync(url)
assert '1 / 0' not in resp['body']
... | 0.29584 | 0.122917 |
from suds import *
from suds.bindings.binding import Binding
from suds.sax.element import Element
from logging import getLogger
log = getLogger(__name__)
class Document(Binding):
"""
The document/literal style. Literal is the only (@use) supported since
document/encoded is pretty much dead.
Althoug... | tests/functional_test/Libs/suds/bindings/document.py | from suds import *
from suds.bindings.binding import Binding
from suds.sax.element import Element
from logging import getLogger
log = getLogger(__name__)
class Document(Binding):
"""
The document/literal style. Literal is the only (@use) supported since
document/encoded is pretty much dead.
Althoug... | 0.673299 | 0.321993 |
from allennlp.nn.util import get_text_field_mask, get_range_vector
from allennlp.nn.util import get_device_of, get_lengths_from_binary_sequence_mask
from typing import Dict, Optional, Tuple, Any, List
import torch
from graph_dependency_parser.components.losses.base import EdgeLoss, EdgeExistenceLoss, EdgeLabelLoss
... | graph_dependency_parser/components/losses/DM.py | from allennlp.nn.util import get_text_field_mask, get_range_vector
from allennlp.nn.util import get_device_of, get_lengths_from_binary_sequence_mask
from typing import Dict, Optional, Tuple, Any, List
import torch
from graph_dependency_parser.components.losses.base import EdgeLoss, EdgeExistenceLoss, EdgeLabelLoss
... | 0.95044 | 0.636198 |
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import ParseError
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from core.authentication import Authentications
from core.permissions import module_permi... | server/projects/views.py | from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import ParseError
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from core.authentication import Authentications
from core.permissions import module_permi... | 0.51879 | 0.112065 |
from pathlib import Path
from typing import Callable, Dict, List
input_file: Path = Path(__file__).parent.joinpath("input.txt")
def get_allowed_numbers(rules):
allowed_numbers = {}
for rule in rules:
name, rest = rule.split(": ")
allowed_numbers[name] = []
ranges = rest.split(" or ")
... | day16/day16.py | from pathlib import Path
from typing import Callable, Dict, List
input_file: Path = Path(__file__).parent.joinpath("input.txt")
def get_allowed_numbers(rules):
allowed_numbers = {}
for rule in rules:
name, rest = rule.split(": ")
allowed_numbers[name] = []
ranges = rest.split(" or ")
... | 0.493409 | 0.464476 |
from typing import Literal
import numpy as np
import pandas as pd
from pydantic import validate_arguments
from . import DATA_DIR
# Cash report data type
CASH_DATA_TYPE = Literal["fund-balances", "spending", "revenue", "net-cash-flow"]
# Cache folder
CACHE_DIR = DATA_DIR / "processed" / "qcmr"
__all__ = [
"loa... | src/phl_budget_data/qcmr.py | from typing import Literal
import numpy as np
import pandas as pd
from pydantic import validate_arguments
from . import DATA_DIR
# Cash report data type
CASH_DATA_TYPE = Literal["fund-balances", "spending", "revenue", "net-cash-flow"]
# Cache folder
CACHE_DIR = DATA_DIR / "processed" / "qcmr"
__all__ = [
"loa... | 0.834137 | 0.204501 |
import os
import sys
import re
import commands
import requests
import time
from bs4 import BeautifulSoup
import mechanize
br = mechanize.Browser()
# Setting url,account,password,browser
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
url = "https://lzone.d... | inputpass.py | import os
import sys
import re
import commands
import requests
import time
from bs4 import BeautifulSoup
import mechanize
br = mechanize.Browser()
# Setting url,account,password,browser
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
url = "https://lzone.d... | 0.039048 | 0.092155 |
from abc import abstractmethod
from prometheus_client import Gauge, Info, Histogram
from polkadot_prometheus_exporter._utils import PeriodicTask, check
from polkadot_prometheus_exporter._rpc import PolkadotRPCError, get_block_num
class ExporterPeriodicTask(PeriodicTask):
"""
PeriodicTask shim which handles... | polkadot_prometheus_exporter/_tasks.py |
from abc import abstractmethod
from prometheus_client import Gauge, Info, Histogram
from polkadot_prometheus_exporter._utils import PeriodicTask, check
from polkadot_prometheus_exporter._rpc import PolkadotRPCError, get_block_num
class ExporterPeriodicTask(PeriodicTask):
"""
PeriodicTask shim which handles... | 0.702836 | 0.167832 |
import fault
import aetherling.helpers.fault_helpers as fault_helpers
from aetherling.space_time import *
from aetherling.space_time.reshape_st import DefineReshape_ST
import magma as m
import json
@cache_definition
def Module_0() -> DefineCircuitKind:
class _Module_0(Circuit):
name = "Module_0"
... | test/no_bench/magma_examples/tuple_reduce/tuple_reduce_1 % 2thr.py | import fault
import aetherling.helpers.fault_helpers as fault_helpers
from aetherling.space_time import *
from aetherling.space_time.reshape_st import DefineReshape_ST
import magma as m
import json
@cache_definition
def Module_0() -> DefineCircuitKind:
class _Module_0(Circuit):
name = "Module_0"
... | 0.440951 | 0.382833 |
from flask import Flask, render_template, json, request, redirect, send_file
from bson import json_util
from flask_bootstrap import Bootstrap
import requests
from io import BytesIO, StringIO
from PIL import Image
import base64
import array
app = Flask(__name__)
class Response:
def __init__(self, code, data, *arg... | frontend/frontend.py | from flask import Flask, render_template, json, request, redirect, send_file
from bson import json_util
from flask_bootstrap import Bootstrap
import requests
from io import BytesIO, StringIO
from PIL import Image
import base64
import array
app = Flask(__name__)
class Response:
def __init__(self, code, data, *arg... | 0.389779 | 0.147126 |
from flask import Blueprint
from flask_restplus import Api
from service.exception.exceptions import (AuthenticationError, BadRequestError, ObjectNotFoundError, ServiceError,
ServiceErrors, InternalServerError)
from service.resources.files import ns as fns
from service.resourc... | service/resources/api_blueprint.py |
from flask import Blueprint
from flask_restplus import Api
from service.exception.exceptions import (AuthenticationError, BadRequestError, ObjectNotFoundError, ServiceError,
ServiceErrors, InternalServerError)
from service.resources.files import ns as fns
from service.resourc... | 0.639624 | 0.095223 |
import sys
import petsc4py
petsc4py.init(sys.argv)
from petsc4py import PETSc
import pickle
from src.support_class import *
from src.myio import *
from src.myvtk import save_singleEcoli_vtk
from src.objComposite import *
import numpy as np
import src.stokes_flow as sf
__all__ = ['get_problem_kwargs', 'print_case_in... | codeStore/ecoli_common.py | import sys
import petsc4py
petsc4py.init(sys.argv)
from petsc4py import PETSc
import pickle
from src.support_class import *
from src.myio import *
from src.myvtk import save_singleEcoli_vtk
from src.objComposite import *
import numpy as np
import src.stokes_flow as sf
__all__ = ['get_problem_kwargs', 'print_case_in... | 0.400398 | 0.127354 |
import logging
from .api import parse_connection
from .auth.mongodb import VMQAuth
logger = logging.getLogger(__name__)
class MQTTConnection:
def __init__(self, api, auth):
self._api = api
self._auth = auth
@property
def api_version(self):
"""which connection api this is using
... | zconnect-mqtt-auth/zconnectmqttauth/connection.py | import logging
from .api import parse_connection
from .auth.mongodb import VMQAuth
logger = logging.getLogger(__name__)
class MQTTConnection:
def __init__(self, api, auth):
self._api = api
self._auth = auth
@property
def api_version(self):
"""which connection api this is using
... | 0.848251 | 0.156137 |
import torch
from torch import nn, Tensor
from .layers import DropPath
class MLP(nn.Module):
def __init__(self, dim, hidden_dim, out_dim=None) -> None:
super().__init__()
out_dim = out_dim or dim
self.fc1 = nn.Linear(dim, hidden_dim)
self.act = nn.GELU()
self.fc2 = nn.Linea... | models/patchconvnet.py | import torch
from torch import nn, Tensor
from .layers import DropPath
class MLP(nn.Module):
def __init__(self, dim, hidden_dim, out_dim=None) -> None:
super().__init__()
out_dim = out_dim or dim
self.fc1 = nn.Linear(dim, hidden_dim)
self.act = nn.GELU()
self.fc2 = nn.Linea... | 0.951063 | 0.658555 |
import pygame,random
blue = (0, 0, 255)
red = (0, 255, 0)
pygame.init()
win = pygame.display.set_mode((640, 700))
pygame.display.set_caption('2048')
pygame.font.init()
myFont = pygame.font.SysFont(None, 100)
titleText = myFont.render('2048', True, (255, 165, 0))
win.blit(titleText, (250, 0))
colourDict={2:'grey',4:'or... | 2048 Final.py | import pygame,random
blue = (0, 0, 255)
red = (0, 255, 0)
pygame.init()
win = pygame.display.set_mode((640, 700))
pygame.display.set_caption('2048')
pygame.font.init()
myFont = pygame.font.SysFont(None, 100)
titleText = myFont.render('2048', True, (255, 165, 0))
win.blit(titleText, (250, 0))
colourDict={2:'grey',4:'or... | 0.068545 | 0.194406 |
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from rest_framework_jwt.settings import api_settings
from rest_framework import permissions, generics, status
from rest_framework.response import Response
from .serializers import TokenSerializer, UserSerializer
from .decor... | flights/auth_views.py | from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from rest_framework_jwt.settings import api_settings
from rest_framework import permissions, generics, status
from rest_framework.response import Response
from .serializers import TokenSerializer, UserSerializer
from .decor... | 0.502197 | 0.079032 |
import json
import pytest
from mongomock.gridfs import enable_gridfs_integration
from tornado.httpclient import HTTPError, HTTPRequest
import beer_garden.db.mongo.models
import beer_garden.events
import beer_garden.requests
import beer_garden.router
from beer_garden.api.http.authentication import issue_token_pair
fro... | src/app/test/api/http/unit/handlers/v1/request_test.py | import json
import pytest
from mongomock.gridfs import enable_gridfs_integration
from tornado.httpclient import HTTPError, HTTPRequest
import beer_garden.db.mongo.models
import beer_garden.events
import beer_garden.requests
import beer_garden.router
from beer_garden.api.http.authentication import issue_token_pair
fro... | 0.442155 | 0.179189 |
from concurrent.futures import Future
from curio.thread import is_async_thread, _locals, AWAIT, AsyncThread
from curio import spawn, UniversalQueue
_request_queue = None
def TAWAIT(coro, *args, **kwargs):
'''
Ensure that the caller is an async thread (promoting if necessary),
then await for a coroutine
... | thredo/thr.py |
from concurrent.futures import Future
from curio.thread import is_async_thread, _locals, AWAIT, AsyncThread
from curio import spawn, UniversalQueue
_request_queue = None
def TAWAIT(coro, *args, **kwargs):
'''
Ensure that the caller is an async thread (promoting if necessary),
then await for a coroutine
... | 0.467575 | 0.067209 |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import parl
class ActorCritic(parl.Model):
def __init__(self, act_dim):
super(ActorCritic, self).__init__()
self.conv1 = nn.Conv2d(
in_channels=4, out_channels=32, kernel_size=8, stride=4, padding=1... | benchmark/torch/a2c/atari_model.py |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import parl
class ActorCritic(parl.Model):
def __init__(self, act_dim):
super(ActorCritic, self).__init__()
self.conv1 = nn.Conv2d(
in_channels=4, out_channels=32, kernel_size=8, stride=4, padding=1... | 0.882788 | 0.362659 |
from typing import Any, List, Optional
from assertpy.assertpy import assert_that
from randmac import RandMac # type: ignore
from lisa.executable import Tool
from lisa.operating_system import Fedora, Posix
from lisa.tools import Kill, Lsmod
class Qemu(Tool):
QEMU_INSTALL_LOCATIONS = ["qemu-system-x86_64", "qe... | lisa/tools/qemu.py |
from typing import Any, List, Optional
from assertpy.assertpy import assert_that
from randmac import RandMac # type: ignore
from lisa.executable import Tool
from lisa.operating_system import Fedora, Posix
from lisa.tools import Kill, Lsmod
class Qemu(Tool):
QEMU_INSTALL_LOCATIONS = ["qemu-system-x86_64", "qe... | 0.82734 | 0.330525 |
from typing import Generator
def squares_generator(n: int) -> Generator[int, None, None]:
"""Generator to return the perfect squares less than `n`."""
if n > 0:
i = next_square = 1
while next_square < n:
yield next_square
i += 1
next_square = i * i
def pri... | ProgramFlow/sets/primes_and_squares.py | from typing import Generator
def squares_generator(n: int) -> Generator[int, None, None]:
"""Generator to return the perfect squares less than `n`."""
if n > 0:
i = next_square = 1
while next_square < n:
yield next_square
i += 1
next_square = i * i
def pri... | 0.903979 | 0.417212 |
import csv
import math
import os
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import numpy.random as rnd
from numpy.core.function_base import linspace
from tqdm import tqdm
titleHeaders = ['Simulate', 'Validate', 'ATE']
xAxisLabels = ['Frequency', 'Voltage', 'Time', 'Decibels (dB)'... | generate_data/RandomWaveform.py | import csv
import math
import os
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import numpy.random as rnd
from numpy.core.function_base import linspace
from tqdm import tqdm
titleHeaders = ['Simulate', 'Validate', 'ATE']
xAxisLabels = ['Frequency', 'Voltage', 'Time', 'Decibels (dB)'... | 0.481941 | 0.19923 |
from tqdm import tqdm
import numpy as np
import paddle
from .abc_interpreter import Interpreter, InputOutputInterpreter
from ..data_processor.readers import preprocess_inputs, preprocess_save_path
from ..data_processor.visualizer import explanation_to_vis, show_vis_explanation, save_image
class OcclusionInterpreter... | interpretdl/interpreter/occlusion.py | from tqdm import tqdm
import numpy as np
import paddle
from .abc_interpreter import Interpreter, InputOutputInterpreter
from ..data_processor.readers import preprocess_inputs, preprocess_save_path
from ..data_processor.visualizer import explanation_to_vis, show_vis_explanation, save_image
class OcclusionInterpreter... | 0.743354 | 0.429968 |
import unittest
import pathlib
import pandas as pd
import numpy as np
import inspect
from autopew.io import (
get_filehandler,
registered_extensions,
PewIOSpecification,
PewCSV,
PewSCANCSV,
PewJEOLpos
)
from autopew.util.general import temp_path, remove_tempdir
class TestGetReg... | test/io/test_io.py | import unittest
import pathlib
import pandas as pd
import numpy as np
import inspect
from autopew.io import (
get_filehandler,
registered_extensions,
PewIOSpecification,
PewCSV,
PewSCANCSV,
PewJEOLpos
)
from autopew.util.general import temp_path, remove_tempdir
class TestGetReg... | 0.233182 | 0.29022 |
import time
from .. import factory,constants
from ...utils import formater,capturer,util
class TestCase(object):
def __init__(self,context,test_data):
self._context = context
self._test_data = test_data
self._name = ''
self._sampler = None
self._request_type = ''
sel... | lasttester/core/lasttest/case.py | import time
from .. import factory,constants
from ...utils import formater,capturer,util
class TestCase(object):
def __init__(self,context,test_data):
self._context = context
self._test_data = test_data
self._name = ''
self._sampler = None
self._request_type = ''
sel... | 0.405802 | 0.245543 |
import unittest
from config import Session
from script import replace_literals, find_literals, compile_script
class ScriptTestCase(unittest.TestCase):
def setUp(self):
self.session = Session()
def tearDown(self):
self.session.close()
def test_replace_literals(self):
script_in = ... | test_script.py | import unittest
from config import Session
from script import replace_literals, find_literals, compile_script
class ScriptTestCase(unittest.TestCase):
def setUp(self):
self.session = Session()
def tearDown(self):
self.session.close()
def test_replace_literals(self):
script_in = ... | 0.482673 | 0.414721 |
import asyncio
import logging
from io import BytesIO
import aiohttp
from discord import File
from discord.ext import commands
from util import auto_help
logger = logging.getLogger(__name__)
def setup(bot):
bot.add_cog(WolframAlpha(bot))
class WolframAlpha(commands.Cog):
RESULT_API_URL = "https://api.wolf... | cogs/WolframAlpha.py | import asyncio
import logging
from io import BytesIO
import aiohttp
from discord import File
from discord.ext import commands
from util import auto_help
logger = logging.getLogger(__name__)
def setup(bot):
bot.add_cog(WolframAlpha(bot))
class WolframAlpha(commands.Cog):
RESULT_API_URL = "https://api.wolf... | 0.347648 | 0.083703 |
from decimal import Decimal
from datetime import datetime
from django.urls import reverse
from rest_framework.test import APITestCase
from cotidia.account import fixtures
from cotidia.admin.tests.factory import ExampleModelOneFactory, ExampleModelTwoFactory
class AdminSearchDashboardTests(APITestCase):
@fixtures... | cotidia/admin/tests/api/test_search_dashboard_ordering.py | from decimal import Decimal
from datetime import datetime
from django.urls import reverse
from rest_framework.test import APITestCase
from cotidia.account import fixtures
from cotidia.admin.tests.factory import ExampleModelOneFactory, ExampleModelTwoFactory
class AdminSearchDashboardTests(APITestCase):
@fixtures... | 0.698946 | 0.171079 |
from enum import Enum
import logging
import os.path
from typing import Any, Mapping, Optional, Tuple, Union
from jinja2 import Environment, FileSystemLoader
from sqlalchemy.orm import Session as SQLASession
from srcf.database import Member, Society
from srcf.mail import send_mail
from ..plumbing.common import Owner... | srcflib/email/__init__.py | from enum import Enum
import logging
import os.path
from typing import Any, Mapping, Optional, Tuple, Union
from jinja2 import Environment, FileSystemLoader
from sqlalchemy.orm import Session as SQLASession
from srcf.database import Member, Society
from srcf.mail import send_mail
from ..plumbing.common import Owner... | 0.794465 | 0.167287 |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='BucketList',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serializ... | web/migrations/0001_initial.py |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='BucketList',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serializ... | 0.61057 | 0.182462 |
import psycopg2
import pytz
from datetime import datetime
from bot.dao import Dao
from bot.feed import Feed
class FeedDao(Dao):
# TABLE_INFO = {"name": "feed", "param1": "title", "param2": "link", "param3": "source", "param4": "time", "param5": "summary", "param6": "category"}
TABLE_INFO = {"name": "feed", ... | bot/feed_dao.py | import psycopg2
import pytz
from datetime import datetime
from bot.dao import Dao
from bot.feed import Feed
class FeedDao(Dao):
# TABLE_INFO = {"name": "feed", "param1": "title", "param2": "link", "param3": "source", "param4": "time", "param5": "summary", "param6": "category"}
TABLE_INFO = {"name": "feed", ... | 0.252384 | 0.243958 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['QueueArgs', 'Queue']
@pulumi.input_type
class QueueArgs:
def __init__(__self__, *,
content_b... | sdk/python/pulumi_aws_native/sqs/queue.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['QueueArgs', 'Queue']
@pulumi.input_type
class QueueArgs:
def __init__(__self__, *,
content_b... | 0.878946 | 0.130923 |
from rest_framework import serializers
# djnago imports
from django.contrib.auth import get_user_model
# Local Imports
from assignments.models import (
Assignment,
AssignmentFile,
)
from courses.models import (
Course,
CourseSection,
)
User = get_user_model()
class AssignmentCreateSerializer(... | assignments/api/admin/serializers.py | from rest_framework import serializers
# djnago imports
from django.contrib.auth import get_user_model
# Local Imports
from assignments.models import (
Assignment,
AssignmentFile,
)
from courses.models import (
Course,
CourseSection,
)
User = get_user_model()
class AssignmentCreateSerializer(... | 0.639286 | 0.21767 |
help = '''
HOP
Hearth OS Package manager
Version 1.0
Install a package: hop install <package_name>
Check for an update of a package: hop update
'''
# Import modules that are needed
import json, requests, sys, os, rich
from rich.console import Console
from rich.prompt import Confirm
from rich.panel import Panel
co... | package_data/chromeos.py |
help = '''
HOP
Hearth OS Package manager
Version 1.0
Install a package: hop install <package_name>
Check for an update of a package: hop update
'''
# Import modules that are needed
import json, requests, sys, os, rich
from rich.console import Console
from rich.prompt import Confirm
from rich.panel import Panel
co... | 0.261614 | 0.126299 |
# Form implementation generated from reading ui file 'front_end.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
import pandas as pd
import datetime
from tqdm... | frontend.py |
# Form implementation generated from reading ui file 'front_end.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
import pandas as pd
import datetime
from tqdm... | 0.245627 | 0.039527 |
__docformat__ = 'restructuredtext'
import os
from glob import glob
import numpy as np
from nipype.externals.pynifti import load
from nipype.utils.filemanip import fname_presuffix
from nipype.interfaces.io import FreeSurferSource
from nipype.interfaces.freesurfer.base import FSCommand, FSTraitedSpec
from nipype.inter... | nipype/interfaces/freesurfer/preprocess.py | __docformat__ = 'restructuredtext'
import os
from glob import glob
import numpy as np
from nipype.externals.pynifti import load
from nipype.utils.filemanip import fname_presuffix
from nipype.interfaces.io import FreeSurferSource
from nipype.interfaces.freesurfer.base import FSCommand, FSTraitedSpec
from nipype.inter... | 0.569853 | 0.131954 |
import sys
import gzip
import json
from datetime import datetime
from itertools import chain
import re
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
from ckanapi.errors import (NotFound, NotAuthorized, ValidationError,
SearchIndexError)
from ckanapi.cli import wor... | ckanapi/cli/delete.py | import sys
import gzip
import json
from datetime import datetime
from itertools import chain
import re
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
from ckanapi.errors import (NotFound, NotAuthorized, ValidationError,
SearchIndexError)
from ckanapi.cli import wor... | 0.269614 | 0.150871 |
import argparse
def arguments():
# Handle command line arguments
parser = argparse.ArgumentParser(description='Adventofcode.')
parser.add_argument('-f', '--file', required=True)
args = parser.parse_args()
return args
class computer():
def __init__(self):
self.reset()
def reset... | 2019/day2/day2.py | import argparse
def arguments():
# Handle command line arguments
parser = argparse.ArgumentParser(description='Adventofcode.')
parser.add_argument('-f', '--file', required=True)
args = parser.parse_args()
return args
class computer():
def __init__(self):
self.reset()
def reset... | 0.499512 | 0.210401 |
"""This test module contains the tests for the `aea install` sub-command."""
import os
import tempfile
import unittest.mock
from pathlib import Path
import yaml
from ..common.click_testing import CliRunner
import aea.cli.common
from aea.cli import cli
from aea.configurations.base import DEFAULT_PROTOCOL_CONFIG_FILE
... | tests/test_cli/test_install.py |
"""This test module contains the tests for the `aea install` sub-command."""
import os
import tempfile
import unittest.mock
from pathlib import Path
import yaml
from ..common.click_testing import CliRunner
import aea.cli.common
from aea.cli import cli
from aea.configurations.base import DEFAULT_PROTOCOL_CONFIG_FILE
... | 0.741206 | 0.379235 |
import base64
import pkg_resources
import six
X509_CERT_CN = 'www.example.com'
X509_CERT_SHA1 = '9965834d856a7e24459522af0b91df69323947b3'
X509_CERT = b"""-----BEGIN CERTIFICATE-----
MIIE8TCCAtmgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwIzEhMB8GA1UEAwwYY2Et
aW50QHNiYWx1a29mZi5pYm0uY29tMB4XDTE2MDkyNzA4MjkzNFoXDTI... | zuul.d/octavia/tests/unit/common/sample_configs/sample_certs.py |
import base64
import pkg_resources
import six
X509_CERT_CN = 'www.example.com'
X509_CERT_SHA1 = '9965834d856a7e24459522af0b91df69323947b3'
X509_CERT = b"""-----BEGIN CERTIFICATE-----
MIIE8TCCAtmgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwIzEhMB8GA1UEAwwYY2Et
aW50QHNiYWx1a29mZi5pYm0uY29tMB4XDTE2MDkyNzA4MjkzNFoXDTI... | 0.24817 | 0.092237 |
"""Trainer for clause search models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import keras
import tensorflow as tf
from deepmath.util import model_utils
metrics = tf.contrib.metrics
slim = tf.contrib.slim
training = tf.contrib.training... | deepmath/guidance/train.py | """Trainer for clause search models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import keras
import tensorflow as tf
from deepmath.util import model_utils
metrics = tf.contrib.metrics
slim = tf.contrib.slim
training = tf.contrib.training... | 0.933469 | 0.20343 |
from __future__ import unicode_literals
import logging
import os
from abc import ABCMeta, abstractmethod
from django.db import transaction
from ingest.models import Ingest, Scan
from ingest.scan.scanners.exceptions import ScannerInterruptRequested
from storage.models import Workspace
logger = logging.getLogger(__na... | scale/ingest/scan/scanners/scanner.py | from __future__ import unicode_literals
import logging
import os
from abc import ABCMeta, abstractmethod
from django.db import transaction
from ingest.models import Ingest, Scan
from ingest.scan.scanners.exceptions import ScannerInterruptRequested
from storage.models import Workspace
logger = logging.getLogger(__na... | 0.81946 | 0.221182 |
import cv2
def getTrainingData(window_name, camera_id, path_name, max_num): # path_name是图片存储目录,max_num是需要捕捉的图片数量
cv2.namedWindow(window_name) # 创建窗口
cap = cv2.VideoCapture(camera_id) # 打开摄像头
classifier = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml') # 加载分类器
color = (0,255,0) # 人脸矩形框的颜色
... | save_face_image1.py | import cv2
def getTrainingData(window_name, camera_id, path_name, max_num): # path_name是图片存储目录,max_num是需要捕捉的图片数量
cv2.namedWindow(window_name) # 创建窗口
cap = cv2.VideoCapture(camera_id) # 打开摄像头
classifier = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml') # 加载分类器
color = (0,255,0) # 人脸矩形框的颜色
... | 0.21684 | 0.283812 |
import redistools
from redistools.conn import Conn
class RedisUtils:
def __init__(self, **kwargs):
self.conn = Conn(**kwargs)
self.ex = 604800
def keys(self, filter=""):
if (filter):
if (type(filter) == type("")):
return self.conn.keys(filter)
e... | redistools/serde.py | import redistools
from redistools.conn import Conn
class RedisUtils:
def __init__(self, **kwargs):
self.conn = Conn(**kwargs)
self.ex = 604800
def keys(self, filter=""):
if (filter):
if (type(filter) == type("")):
return self.conn.keys(filter)
e... | 0.568176 | 0.139016 |
from __future__ import division, print_function, unicode_literals
__author__ = 'setten'
import os
import unittest
from pymatgen.util.testing import PymatgenTest
from pymatgen.core.structure import Structure
from pymatgen.matproj.rest import MPRester, MPRestError
from pymatgen.io.gwwrapper.datastructures import GWSpe... | pymatgen/io/gwwrapper/tests/test_classes.py | from __future__ import division, print_function, unicode_literals
__author__ = 'setten'
import os
import unittest
from pymatgen.util.testing import PymatgenTest
from pymatgen.core.structure import Structure
from pymatgen.matproj.rest import MPRester, MPRestError
from pymatgen.io.gwwrapper.datastructures import GWSpe... | 0.541651 | 0.37958 |
import argparse
import time
from d4pg.actors import Actor
from d4pg.learners import Learner
from d4pg.replay import ReplayBuffer_remote
# Plot results
from d4pg.utils import VisdomLinePlotter
import gym
def make_cassie_env(*args, **kwargs):
def _thunk():
return CassieEnv(*args, **kwargs)
return _thu... | examples/distributed_td3.py | import argparse
import time
from d4pg.actors import Actor
from d4pg.learners import Learner
from d4pg.replay import ReplayBuffer_remote
# Plot results
from d4pg.utils import VisdomLinePlotter
import gym
def make_cassie_env(*args, **kwargs):
def _thunk():
return CassieEnv(*args, **kwargs)
return _thu... | 0.711631 | 0.157363 |