code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from pudzu.charts import *
from pudzu.sandbox.bamboo import *
import scipy.stats
df = pd.read_csv("../dataviz/datasets/countries.csv").filter_rows("organisations >> un").split_columns('country', "|").explode('country').set_index('country').drop_duplicates(subset='flag', keep='first')
wf = pd.read_html("https://en.wik... | dataviz/flagsaverage4.py | from pudzu.charts import *
from pudzu.sandbox.bamboo import *
import scipy.stats
df = pd.read_csv("../dataviz/datasets/countries.csv").filter_rows("organisations >> un").split_columns('country', "|").explode('country').set_index('country').drop_duplicates(subset='flag', keep='first')
wf = pd.read_html("https://en.wik... | 0.461988 | 0.439807 |
import os
import warnings
from typing import cast
import numpy as np
import srl
from srl.base.define import EnvObservationType
from srl.base.env.singleplay_wrapper import SinglePlayEnvWrapper
from srl.base.rl.processors.image_processor import ImageProcessor
from srl.base.rl.registration import make_worker
from srl.bas... | srl/test/rl.py | import os
import warnings
from typing import cast
import numpy as np
import srl
from srl.base.define import EnvObservationType
from srl.base.env.singleplay_wrapper import SinglePlayEnvWrapper
from srl.base.rl.processors.image_processor import ImageProcessor
from srl.base.rl.registration import make_worker
from srl.bas... | 0.608361 | 0.211335 |
import sys
import os
import idaapi
import idc
MAX_PREVIOUS_SEARCH = 10
def call_xrefs(function_name):
function_address = LocByName(function_name)
for addr in XrefsTo(function_address):
mnem = GetMnem(addr.frm)
# We only care about the calls
if mnem not in ['jalr', 'jr']:
continue
yield addr.frm
def ... | 2020.06.15-netgear/tools/find_mips_gadget.py |
import sys
import os
import idaapi
import idc
MAX_PREVIOUS_SEARCH = 10
def call_xrefs(function_name):
function_address = LocByName(function_name)
for addr in XrefsTo(function_address):
mnem = GetMnem(addr.frm)
# We only care about the calls
if mnem not in ['jalr', 'jr']:
continue
yield addr.frm
def ... | 0.163612 | 0.178311 |
from flask import Flask, jsonify, request, json
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from datetime import datetime
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from flask_jwt_extended import JWTManager
from flask_jwt_extended import (create_access_token)
app = Flask(__nam... | backend/main.py | from flask import Flask, jsonify, request, json
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from datetime import datetime
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from flask_jwt_extended import JWTManager
from flask_jwt_extended import (create_access_token)
app = Flask(__nam... | 0.216923 | 0.050588 |
from keystoneauth1 import fixture as ksa_fixture
from requests_mock.contrib import fixture
from openstackclient.tests.unit import test_shell
from openstackclient.tests.unit import utils
HOST = "192.168.5.41"
URL_BASE = "http://%s/identity" % HOST
V2_AUTH_URL = URL_BASE + "/v2.0/"
V2_VERSION_RESP = {
"version":... | openstackclient/tests/unit/integ/base.py |
from keystoneauth1 import fixture as ksa_fixture
from requests_mock.contrib import fixture
from openstackclient.tests.unit import test_shell
from openstackclient.tests.unit import utils
HOST = "192.168.5.41"
URL_BASE = "http://%s/identity" % HOST
V2_AUTH_URL = URL_BASE + "/v2.0/"
V2_VERSION_RESP = {
"version":... | 0.643441 | 0.267755 |
import numpy as np
from Source.Utility.GameMetricsNew import GameMetrics
def reward_1(obs, latest_obs): # reward from Avg Distance, Avg Speed, change Num Living Players, Border Distances
reward = ((obs[0] - latest_obs[0]) # average distance
+ (obs[2]) / 10 # avg Speed normalized
+ (... | Source/Utility/RewardFunctions.py | import numpy as np
from Source.Utility.GameMetricsNew import GameMetrics
def reward_1(obs, latest_obs): # reward from Avg Distance, Avg Speed, change Num Living Players, Border Distances
reward = ((obs[0] - latest_obs[0]) # average distance
+ (obs[2]) / 10 # avg Speed normalized
+ (... | 0.529507 | 0.592726 |
import geojson, argparse, csv, zipfile
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from datetime import timedelta
from decimal import Decimal
def gtfs_stops(gtfs, output_f):
"""
For each stop, convert it into a GeoJSON Point, and make all of it's attributes available.
:... | gtfs2geojson.py | import geojson, argparse, csv, zipfile
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from datetime import timedelta
from decimal import Decimal
def gtfs_stops(gtfs, output_f):
"""
For each stop, convert it into a GeoJSON Point, and make all of it's attributes available.
:... | 0.518059 | 0.327265 |
from os.path import join, dirname, abspath
from collections import defaultdict
import yaml
try:
import ujson as json
except ImportError:
import json
from aiohttp import web
from jinja2 import Template
SWAGGER_TEMPLATE = abspath(join(dirname(__file__), "..", "templates"))
def build_doc_from_func_doc(route)... | aiohttp-swagger/aiohttp_swagger/helpers/builders.py | from os.path import join, dirname, abspath
from collections import defaultdict
import yaml
try:
import ujson as json
except ImportError:
import json
from aiohttp import web
from jinja2 import Template
SWAGGER_TEMPLATE = abspath(join(dirname(__file__), "..", "templates"))
def build_doc_from_func_doc(route)... | 0.539711 | 0.069763 |
import argparse
import os
import warnings
import subprocess
subprocess.call(['pip', 'install', 'sagemaker-experiments'])
import pandas as pd
import numpy as np
import tarfile
from smexperiments.tracker import Tracker
from sklearn.externals import joblib
from sklearn.model_selection import train_test_split
from skle... | 02_data_exploration_and_feature_eng/source_dir/preprocessor_dw_fs_model.py | import argparse
import os
import warnings
import subprocess
subprocess.call(['pip', 'install', 'sagemaker-experiments'])
import pandas as pd
import numpy as np
import tarfile
from smexperiments.tracker import Tracker
from sklearn.externals import joblib
from sklearn.model_selection import train_test_split
from skle... | 0.510496 | 0.184896 |
import src.cmd_modules.UsbADI as usb
import ctypes
import numpy as np
import struct
from numpy import *
class DemoRad():
"""Implementation of DemoRad class
Uses the UsbADI Module to Read and Write data via USB.
Implements functions to send specific commands to the Dsp and it's attached components
"""... | AppNotes/src/cmd_modules/DemoRad.py | import src.cmd_modules.UsbADI as usb
import ctypes
import numpy as np
import struct
from numpy import *
class DemoRad():
"""Implementation of DemoRad class
Uses the UsbADI Module to Read and Write data via USB.
Implements functions to send specific commands to the Dsp and it's attached components
"""... | 0.32146 | 0.175114 |
import logging
from pathlib import Path
from tokenizers.implementations import ByteLevelBPETokenizer
from tokenizers.processors import BertProcessing
import torch as nn
from torch.utils.data.dataset import Dataset
from ..ner.arguments import ModelArguments, DataTrainingArguments
from transformers import (
AutoModel... | nlp/handler/pretrain/pretrain.py | import logging
from pathlib import Path
from tokenizers.implementations import ByteLevelBPETokenizer
from tokenizers.processors import BertProcessing
import torch as nn
from torch.utils.data.dataset import Dataset
from ..ner.arguments import ModelArguments, DataTrainingArguments
from transformers import (
AutoModel... | 0.766031 | 0.226196 |
import tensorflow as tf
FLAGS = tf.flags.FLAGS
tf.flags.DEFINE_integer('batch_size', 8, 'batch size, default: 1')
tf.flags.DEFINE_integer('image_size', 256, 'image size, default: 256')
tf.flags.DEFINE_integer('image_size_retina', 256, 'image size, default: 256')
tf.flags.DEFINE_float('learning_rate', 1e-4,
... | hyper_parameters.py | import tensorflow as tf
FLAGS = tf.flags.FLAGS
tf.flags.DEFINE_integer('batch_size', 8, 'batch size, default: 1')
tf.flags.DEFINE_integer('image_size', 256, 'image size, default: 256')
tf.flags.DEFINE_integer('image_size_retina', 256, 'image size, default: 256')
tf.flags.DEFINE_float('learning_rate', 1e-4,
... | 0.582254 | 0.211051 |
## Introduction
Vision Transformers (ViT; [Dosovitskiy et al.](https://arxiv.org/abs/1612.00593)) extract
small patches from the input images, linearly project them, and then apply the
Transformer ([Vaswani et al.](https://arxiv.org/abs/1706.03762)) blocks. The application
of ViTs to image recognition tasks is quickly... | examples/vision/convmixer.py | pip install -U -q tensorflow-addons | 0.732305 | 0.981718 |
import datetime
from typing import Tuple, Generator
from twitch.helix import Video
from twitch.v5 import Comment, Comments
from tcd.formats.format import Format
from tcd.pipe import Pipe
from tcd.safedict import SafeDict
class SRT(Format):
def __init__(self, video: Video):
"""
Initialize SRT fo... | tcd/formats/srt.py | import datetime
from typing import Tuple, Generator
from twitch.helix import Video
from twitch.v5 import Comment, Comments
from tcd.formats.format import Format
from tcd.pipe import Pipe
from tcd.safedict import SafeDict
class SRT(Format):
def __init__(self, video: Video):
"""
Initialize SRT fo... | 0.86319 | 0.221677 |
"""Flip problem sense tests."""
from test import QiskitOptimizationTestCase
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.converters import MaximizeToMinimize, MinimizeToMaximize
class TestFlipProblemSense(QiskitOptimizationTestCase):
"""Tests various flips of problem sense."""
... | test/converters/test_flip_problem_sense.py |
"""Flip problem sense tests."""
from test import QiskitOptimizationTestCase
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.converters import MaximizeToMinimize, MinimizeToMaximize
class TestFlipProblemSense(QiskitOptimizationTestCase):
"""Tests various flips of problem sense."""
... | 0.863147 | 0.745584 |
from typing import Optional
import numpy as np # type: ignore
from scipy.constants import g # type: ignore
def compact(
dz: np.ndarray,
porosity: np.ndarray,
c: float = 5e-8,
rho_grain: float = 2650.0,
excess_pressure: float = 0.0,
porosity_min: float = 0.0,
porosity_max: float = 1.0,
... | compaction/compaction.py | from typing import Optional
import numpy as np # type: ignore
from scipy.constants import g # type: ignore
def compact(
dz: np.ndarray,
porosity: np.ndarray,
c: float = 5e-8,
rho_grain: float = 2650.0,
excess_pressure: float = 0.0,
porosity_min: float = 0.0,
porosity_max: float = 1.0,
... | 0.960137 | 0.768342 |
import os
import sys
import numpy as np
import scipy.io as io
rng = np.random.RandomState(23456)
import torch
import torchvision
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision.utils import save_image
from torchvision.datasets import MNIST
import os
fr... | utils/modelZoo.py | import os
import sys
import numpy as np
import scipy.io as io
rng = np.random.RandomState(23456)
import torch
import torchvision
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision.utils import save_image
from torchvision.datasets import MNIST
import os
fr... | 0.670069 | 0.329891 |
from __future__ import annotations
from typing import Optional
import numpy as np
import scipy.integrate
from sklearn.base import BaseEstimator, TransformerMixin
from ..._utils import check_is_univariate
from ...representation import FDataGrid
from ...representation._typing import ArrayLike
from ._operators import O... | skfda/misc/operators/_srvf.py | from __future__ import annotations
from typing import Optional
import numpy as np
import scipy.integrate
from sklearn.base import BaseEstimator, TransformerMixin
from ..._utils import check_is_univariate
from ...representation import FDataGrid
from ...representation._typing import ArrayLike
from ._operators import O... | 0.976401 | 0.632772 |
from django.contrib import admin
from umum.models import Provinsi, Kabupaten, LokasiBidang, SKPD, SUBSKPD, KodeBarang, HakTanah, SatuanBarang, KeadaanBarang, SKPenghapusan, MutasiBerkurang, JenisPemanfaatan, AsalUsul, Tahun, GolonganBarang, Tanah, KontrakTanah, PenghapusanTanah, TanahPenghapusan, PemanfaatanTanah, Tan... | openaset/paringinkota/admin.py |
from django.contrib import admin
from umum.models import Provinsi, Kabupaten, LokasiBidang, SKPD, SUBSKPD, KodeBarang, HakTanah, SatuanBarang, KeadaanBarang, SKPenghapusan, MutasiBerkurang, JenisPemanfaatan, AsalUsul, Tahun, GolonganBarang, Tanah, KontrakTanah, PenghapusanTanah, TanahPenghapusan, PemanfaatanTanah, Tan... | 0.283087 | 0.269546 |
from pymap import pyMAP
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
np.set_printoptions(precision=2)
np.set_printoptions(suppress=True)
baseline2 = ['--------------- LINE DICTIONARY -------------------------',
'LineType Diam MassDenInAir EA CB ... | test/sphinx_example.py | from pymap import pyMAP
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
np.set_printoptions(precision=2)
np.set_printoptions(suppress=True)
baseline2 = ['--------------- LINE DICTIONARY -------------------------',
'LineType Diam MassDenInAir EA CB ... | 0.401453 | 0.453746 |
import math
from .exceptions import IllegalFileSystemOperation
class Container:
"""Mixin-style class that makes an object behave as a container for other file system objects"""
def __init__(self, name, type):
self.name = name
self.type = type
self.parent = None
self.children = ... | memfs/filesystem.py | import math
from .exceptions import IllegalFileSystemOperation
class Container:
"""Mixin-style class that makes an object behave as a container for other file system objects"""
def __init__(self, name, type):
self.name = name
self.type = type
self.parent = None
self.children = ... | 0.684897 | 0.151153 |
etas = {
'generic14_learning': {
'alpha_sys': { 'muT__hat': 1.0, 'muT__muT': 0.0896875702392, 'muT__muW': 0.00786798398002, 'muT__phi': 0.0, 'muW__hat': 1.0, 'muW__muT': 0.00803419913052, 'muW__muW': 0.214994532712, 'muW__phi': 0.0 },
},
'generic20_learning': {
'alpha_sys': { 'muT__hat': 1.0, 'muT__muT__down': 0... | plotsForPaper/twoBin/scenarioB_interpCode0_etas_table.py | etas = {
'generic14_learning': {
'alpha_sys': { 'muT__hat': 1.0, 'muT__muT': 0.0896875702392, 'muT__muW': 0.00786798398002, 'muT__phi': 0.0, 'muW__hat': 1.0, 'muW__muT': 0.00803419913052, 'muW__muW': 0.214994532712, 'muW__phi': 0.0 },
},
'generic20_learning': {
'alpha_sys': { 'muT__hat': 1.0, 'muT__muT__down': 0... | 0.314682 | 0.246908 |
from datetime import timedelta
from decimal import Decimal
from random import randint
import pytest
from aggrep.jobs.ctr import CTR
from aggrep.models import JobLock, JobType, Post
from aggrep.utils import now
from tests.factories import PostFactory
@pytest.mark.usefixtures("db")
class TestCTR:
"""Click-through... | tests/jobs/test_ctr.py | from datetime import timedelta
from decimal import Decimal
from random import randint
import pytest
from aggrep.jobs.ctr import CTR
from aggrep.models import JobLock, JobType, Post
from aggrep.utils import now
from tests.factories import PostFactory
@pytest.mark.usefixtures("db")
class TestCTR:
"""Click-through... | 0.659076 | 0.370168 |
import heapq
import sys
# allow for recusion; easier to follow
sys.setrecursionlimit(1000 * 3)
# input
n = int(input())
goals = input().split()
names = {}
deps = {}
for _ in range(n):
name, value, _, *deps_ = input().split()
names[value] = name
deps[value] = deps_
valid_stack = set()
valid = set()
# che... | problems/dungeoncrawler/solutions/dungeon.py | import heapq
import sys
# allow for recusion; easier to follow
sys.setrecursionlimit(1000 * 3)
# input
n = int(input())
goals = input().split()
names = {}
deps = {}
for _ in range(n):
name, value, _, *deps_ = input().split()
names[value] = name
deps[value] = deps_
valid_stack = set()
valid = set()
# che... | 0.18374 | 0.285587 |
import requests,html5lib,re,socket,socks,os,time
from bs4 import BeautifulSoup
print('''H3爬虫「抓取指定网站和下载」\n
名称:触网虫\n
类型:爬虫类邪恶型数码精灵\n
状态:成长期\n
必杀技:上下其手!\n
说明:针对一个网站伸出触手的变态数码精灵。\n
口号:触遍所有HTML!
''')
print('===========简陋的分割线===========')
#抓取网页
def spider(x):
while True:
... | Heru3.py |
import requests,html5lib,re,socket,socks,os,time
from bs4 import BeautifulSoup
print('''H3爬虫「抓取指定网站和下载」\n
名称:触网虫\n
类型:爬虫类邪恶型数码精灵\n
状态:成长期\n
必杀技:上下其手!\n
说明:针对一个网站伸出触手的变态数码精灵。\n
口号:触遍所有HTML!
''')
print('===========简陋的分割线===========')
#抓取网页
def spider(x):
while True:
... | 0.150746 | 0.089574 |
from fbchat import Client
from fbchat.models import *
def get_sent_messages(client: Client):
return _get_messages(client, True)
def get_received_messages(client: Client):
return _get_messages(client, False)
def print_single_thread(client: Client, thread_id):
messages = client.fetchThreadMessages(threa... | fbchat/separate_messages.py | from fbchat import Client
from fbchat.models import *
def get_sent_messages(client: Client):
return _get_messages(client, True)
def get_received_messages(client: Client):
return _get_messages(client, False)
def print_single_thread(client: Client, thread_id):
messages = client.fetchThreadMessages(threa... | 0.334263 | 0.056679 |
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from .utils import *
__all__ = [
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
'vgg19_bn', 'vgg19',
]
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
'vgg13': 'https://download.p... | src/models/models_lpf/vgg.py |
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from .utils import *
__all__ = [
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
'vgg19_bn', 'vgg19',
]
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
'vgg13': 'https://download.p... | 0.909868 | 0.485478 |
import os
import csv
import tensorflow as tf
import tokenization
from data_processor import DataProcessor, InputExample, InputFeatures
from model_fn import create_sequential_tagging_model
class SequentialTagProcessor(DataProcessor):
"""Base class for data converters for sequence classification data sets."""
... | sequential_tag_processor.py | import os
import csv
import tensorflow as tf
import tokenization
from data_processor import DataProcessor, InputExample, InputFeatures
from model_fn import create_sequential_tagging_model
class SequentialTagProcessor(DataProcessor):
"""Base class for data converters for sequence classification data sets."""
... | 0.691081 | 0.309575 |
import capture_junit as cj
import re
import os
tests_begin = """-------------------------------------------------------
T E S T S
-------------------------------------------------------"""
def findBeginningOfTests(output):
""" Find where the test running begins
Parameters
----------
output : list of... | framework/lib/dlju/maven_junit.py | import capture_junit as cj
import re
import os
tests_begin = """-------------------------------------------------------
T E S T S
-------------------------------------------------------"""
def findBeginningOfTests(output):
""" Find where the test running begins
Parameters
----------
output : list of... | 0.547222 | 0.492371 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20211113_1939'),
]
operations = [
migrations.CreateModel(
name='Profile',
field... | todo/users/migrations/0003_profile.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20211113_1939'),
]
operations = [
migrations.CreateModel(
name='Profile',
field... | 0.545044 | 0.169956 |
from grb.dataset import Dataset
import grb.utils as utils
import sys
import torch
import torch.nn.functional as F
sys.path.append('..')
if __name__ == '__main__':
# Load data
dataset = Dataset(name='grb-cora',
data_dir="../../data/grb-cora",
mode='easy', feat_norm... | tests/attack/test_prbcd.py | from grb.dataset import Dataset
import grb.utils as utils
import sys
import torch
import torch.nn.functional as F
sys.path.append('..')
if __name__ == '__main__':
# Load data
dataset = Dataset(name='grb-cora',
data_dir="../../data/grb-cora",
mode='easy', feat_norm... | 0.74008 | 0.320595 |
import functools
import os
from matplotlib import gridspec
import matplotlib.pylab as plt
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import gradio as gr
def crop_center(image):
"""Returns a cropped square image."""
shape = image.shape
new_shape = min(shape[1], shape[2])
offset_y ... | demo.py | import functools
import os
from matplotlib import gridspec
import matplotlib.pylab as plt
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import gradio as gr
def crop_center(image):
"""Returns a cropped square image."""
shape = image.shape
new_shape = min(shape[1], shape[2])
offset_y ... | 0.770637 | 0.582432 |
import json
from typing import cast
from ariadne.constants import DATA_TYPE_JSON, DATA_TYPE_MULTIPART
from ariadne.exceptions import HttpBadRequestError
from ariadne.file_uploads import combine_multipart_data
from ariadne.graphql import graphql_sync
from django.conf import settings
from django.contrib import admin
fro... | backend/sugomA/urls.py | import json
from typing import cast
from ariadne.constants import DATA_TYPE_JSON, DATA_TYPE_MULTIPART
from ariadne.exceptions import HttpBadRequestError
from ariadne.file_uploads import combine_multipart_data
from ariadne.graphql import graphql_sync
from django.conf import settings
from django.contrib import admin
fro... | 0.626696 | 0.120439 |
import sys, time
from socket import socket
from random import random, choice
# obtain input parameters
try:
graphite_host = sys.argv[1]
graphite_port = int(sys.argv[2])
num_unique_metrics = int(sys.argv[3])
per_minute_metrics = int(sys.argv[4])
except:
print "Expected usage: ./load_test_graphite.p... | python--load-test-graphite/load_test_graphite.py |
import sys, time
from socket import socket
from random import random, choice
# obtain input parameters
try:
graphite_host = sys.argv[1]
graphite_port = int(sys.argv[2])
num_unique_metrics = int(sys.argv[3])
per_minute_metrics = int(sys.argv[4])
except:
print "Expected usage: ./load_test_graphite.p... | 0.341692 | 0.138404 |
import asyncio
from datetime import datetime
import os
from random import *
import string
from models.CheckoutModel import CheckoutModel
from models.FamilyModel import FamilyModel
from models.MemberModel import MemberModel
from models.VerificationModel import VerificationModel
from utils.logger import Logger
from ut... | controllers/MemberController.py | import asyncio
from datetime import datetime
import os
from random import *
import string
from models.CheckoutModel import CheckoutModel
from models.FamilyModel import FamilyModel
from models.MemberModel import MemberModel
from models.VerificationModel import VerificationModel
from utils.logger import Logger
from ut... | 0.310381 | 0.091707 |
__all__ = [
'AdminCmd',
'CreateComplexModelCmd',
'CreateSimpleModelCmd',
'EnableBashCompleteCmd',
]
import os
import sys
from argparse import RawDescriptionHelpFormatter
from platform import system
from subprocess import (
CalledProcessError,
run
)
from ..utils.path import as_path
from .base... | oasislmf/cli/admin.py | __all__ = [
'AdminCmd',
'CreateComplexModelCmd',
'CreateSimpleModelCmd',
'EnableBashCompleteCmd',
]
import os
import sys
from argparse import RawDescriptionHelpFormatter
from platform import system
from subprocess import (
CalledProcessError,
run
)
from ..utils.path import as_path
from .base... | 0.442396 | 0.068569 |
from django.shortcuts import render,redirect
from django.http import HttpResponse,Http404,HttpResponseRedirect,JsonResponse
from .models import Profile,Neighbourhood,Business
from .forms import NewProfileForm,NewBusinessForm,NewHoodForm,UpdateProfileForm
from django.contrib.auth.models import User
from django.contrib.a... | hood/views.py | from django.shortcuts import render,redirect
from django.http import HttpResponse,Http404,HttpResponseRedirect,JsonResponse
from .models import Profile,Neighbourhood,Business
from .forms import NewProfileForm,NewBusinessForm,NewHoodForm,UpdateProfileForm
from django.contrib.auth.models import User
from django.contrib.a... | 0.257859 | 0.058804 |
from pprint import pformat
from six import iteritems
import re
class RunnerDefinition(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
RunnerDefinition - a model defined in Swagger
... | swagger_client/models/runner_definition.py | from pprint import pformat
from six import iteritems
import re
class RunnerDefinition(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
RunnerDefinition - a model defined in Swagger
... | 0.708515 | 0.215268 |
import cv2
from enum import Enum
from PIL import Image
from skimage import filters, morphology, transform
from scipy import ndimage
class TRANSFORMATION(Enum):
CLEAN = 'clean'
ROTATE = 'rotate'
SHIFT = 'shift'
FLIP = 'flip'
AFFINE_TRANS = 'affine'
MORPH_TRANS = 'morph'
AUGMENT = 'augment'
... | src/utils/transformation_configs.py | import cv2
from enum import Enum
from PIL import Image
from skimage import filters, morphology, transform
from scipy import ndimage
class TRANSFORMATION(Enum):
CLEAN = 'clean'
ROTATE = 'rotate'
SHIFT = 'shift'
FLIP = 'flip'
AFFINE_TRANS = 'affine'
MORPH_TRANS = 'morph'
AUGMENT = 'augment'
... | 0.408277 | 0.112503 |
from os import path
from cafe.drivers.unittest.fixtures import BaseTestFixture
from cloudcafe.cloudkeep.barbican.version.client import VersionClient
from cloudcafe.cloudkeep.barbican.secrets.client import SecretsClient
from cloudcafe.cloudkeep.barbican.orders.client import OrdersClient
from cloudcafe.cloudkeep.barbica... | cloudroast/cloudkeep/client_lib/fixtures.py | from os import path
from cafe.drivers.unittest.fixtures import BaseTestFixture
from cloudcafe.cloudkeep.barbican.version.client import VersionClient
from cloudcafe.cloudkeep.barbican.secrets.client import SecretsClient
from cloudcafe.cloudkeep.barbican.orders.client import OrdersClient
from cloudcafe.cloudkeep.barbica... | 0.615781 | 0.068226 |
import discord
from discord.ext import commands, slash
import methods
class CogBank(commands.Cog):
def __init__(self, client):
self.client = client
@self.client.slash_group()
async def bank(ctx: slash.Context):
"""Bank commands."""
print('Options:', ctx.options)
... | cogs/cog_bank.py | import discord
from discord.ext import commands, slash
import methods
class CogBank(commands.Cog):
def __init__(self, client):
self.client = client
@self.client.slash_group()
async def bank(ctx: slash.Context):
"""Bank commands."""
print('Options:', ctx.options)
... | 0.408277 | 0.144269 |
import random
# This is the amount of digits that are accounted for in the random number generation and user input collection processes. This value can be modified to increase/decrease diversity in value selection.
digitCount = 3
def getRandomNumber():
'''
This function generates a random number (the s... | JNavarroBNavarro_Bagels.py | import random
# This is the amount of digits that are accounted for in the random number generation and user input collection processes. This value can be modified to increase/decrease diversity in value selection.
digitCount = 3
def getRandomNumber():
'''
This function generates a random number (the s... | 0.436262 | 0.567757 |
import unittest
from .realParser import eval
from .realParser import parse
class functionXTest(unittest.TestCase):
def test_one(self):
self.assertEqual(7, parse("((2)+(5))"))
self.assertEqual(-3, parse(" (2)-(5)"))
self.assertEqual(28, parse("+3 +5*5*(+1)"))
sel... | pymep/realParserTest.py | import unittest
from .realParser import eval
from .realParser import parse
class functionXTest(unittest.TestCase):
def test_one(self):
self.assertEqual(7, parse("((2)+(5))"))
self.assertEqual(-3, parse(" (2)-(5)"))
self.assertEqual(28, parse("+3 +5*5*(+1)"))
sel... | 0.360151 | 0.580947 |
import sys
class MapError(Exception):
pass
def _parse_first_line(f):
"""
Parse map first line.
Arguments:
f -- opened file object pointing at the top
Returns:
f -- opened file object pointing at the second line
line_num -- number of line in the map
empty -- empty chara... | parse_map.py |
import sys
class MapError(Exception):
pass
def _parse_first_line(f):
"""
Parse map first line.
Arguments:
f -- opened file object pointing at the top
Returns:
f -- opened file object pointing at the second line
line_num -- number of line in the map
empty -- empty chara... | 0.530236 | 0.421492 |
from setuptools import setup, find_packages
meta = {}
with open("grape/meta.py") as fp:
exec(fp.read(), meta)
# Package meta-data.
IMPORTNAME = meta['__title__']
PIPNAME = meta['__packagename__']
NAME = meta['__title__']
DESCRIPTION = 'GRAph Parallel Environment.'
URL = 'https://github.com/mathLab/GRAPE'
MAIL = m... | setup.py | from setuptools import setup, find_packages
meta = {}
with open("grape/meta.py") as fp:
exec(fp.read(), meta)
# Package meta-data.
IMPORTNAME = meta['__title__']
PIPNAME = meta['__packagename__']
NAME = meta['__title__']
DESCRIPTION = 'GRAph Parallel Environment.'
URL = 'https://github.com/mathLab/GRAPE'
MAIL = m... | 0.682045 | 0.296769 |
import os
import sys
import json
import argparse
import asyncio
import time
import aiohttp
from aiohttp import ClientConnectorError
from lbry import __version__
from lbry.blob.blob_file import MAX_BLOB_SIZE
from lbry.conf import Config
from lbry.extras.daemon.client import daemon_rpc
from lbry.extras import system_inf... | scripts/time_to_first_byte.py | import os
import sys
import json
import argparse
import asyncio
import time
import aiohttp
from aiohttp import ClientConnectorError
from lbry import __version__
from lbry.blob.blob_file import MAX_BLOB_SIZE
from lbry.conf import Config
from lbry.extras.daemon.client import daemon_rpc
from lbry.extras import system_inf... | 0.294925 | 0.131731 |
from __future__ import unicode_literals
import django.db.models.deletion
import djgeojson.fields
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),... | mainapp/migrations/0001_custom_squashed_.py | from __future__ import unicode_literals
import django.db.models.deletion
import djgeojson.fields
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),... | 0.541651 | 0.20142 |
import xmltodict
from . import log_util
from urllib.parse import quote_plus as url_encode
import pandas as pd, json
from .utils import recast_df
import string
from pathlib import Path
import os
logger = log_util.get_logger(__name__)
class ElsSearch():
"""Represents a search to one of the search inde... | elsapy/elssearch.py | import xmltodict
from . import log_util
from urllib.parse import quote_plus as url_encode
import pandas as pd, json
from .utils import recast_df
import string
from pathlib import Path
import os
logger = log_util.get_logger(__name__)
class ElsSearch():
"""Represents a search to one of the search inde... | 0.487307 | 0.159054 |
"entry point module"
import json
import pathlib
from typing import Tuple
import click
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from msi_zarr_analysis.ml.dataset.cytomine_ms_overlay import (
CytomineTranslated,
CytomineTranslatedProgressiveBinningFactory... | msi_zarr_analysis/cli/entry.py | "entry point module"
import json
import pathlib
from typing import Tuple
import click
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from msi_zarr_analysis.ml.dataset.cytomine_ms_overlay import (
CytomineTranslated,
CytomineTranslatedProgressiveBinningFactory... | 0.559049 | 0.237963 |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Annotations',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, seriali... | server/image_api/migrations/0001_initial.py |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Annotations',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, seriali... | 0.609524 | 0.322233 |
from decimal import Decimal
from decimal import getcontext
from collections import namedtuple
from common.functions import optimalLog
from common.constants import MAX_PRECISION
from common.constants import LOG_MAX_HI_TERM_VAL
from common.constants import LOG_NUM_OF_HI_TERMS
getcontext().prec = 100
FIXED_1 = (1<<MAX_P... | solidity/python/AutoGenerate/PrintFunctionOptimalLog.py | from decimal import Decimal
from decimal import getcontext
from collections import namedtuple
from common.functions import optimalLog
from common.constants import MAX_PRECISION
from common.constants import LOG_MAX_HI_TERM_VAL
from common.constants import LOG_NUM_OF_HI_TERMS
getcontext().prec = 100
FIXED_1 = (1<<MAX_P... | 0.2587 | 0.178723 |
import logging
import requests
class TLDGenerator():
def _load_tld_file(self, tld_file):
with open(tld_file, "r") as f:
return self._load_raw_tlds(f.read())
def _load_raw_tlds(self, raw_tld_list):
# Loads a list of top or n-th level domains
returnlist = []
for line in raw_tld_list.split("\n"):
line =... | utils/tld_generator.py | import logging
import requests
class TLDGenerator():
def _load_tld_file(self, tld_file):
with open(tld_file, "r") as f:
return self._load_raw_tlds(f.read())
def _load_raw_tlds(self, raw_tld_list):
# Loads a list of top or n-th level domains
returnlist = []
for line in raw_tld_list.split("\n"):
line =... | 0.425128 | 0.159021 |
import os
import time
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.widgets as wid
import tensorflow as tf
from pathlib import Path
from matplotlib import dates
from keras.preprocessing.sequence import TimeseriesGenerator
from sklearn.preprocessing imp... | LSTM Neural Network/Data Setup/Data_Setup.py | import os
import time
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.widgets as wid
import tensorflow as tf
from pathlib import Path
from matplotlib import dates
from keras.preprocessing.sequence import TimeseriesGenerator
from sklearn.preprocessing imp... | 0.510496 | 0.223589 |
import os
import numpy as np
import re
from transposonmapper.importing import load_default_files
from transposonmapper.processing import list_known_essentials
def read_pergene_file(pergenefile):
"""It reads the content of the pergene file , one of the outputs of Transposonmapper
Parameters
----------
... | transposonmapper/statistics/dataframe_from_pergene_helpers.py | import os
import numpy as np
import re
from transposonmapper.importing import load_default_files
from transposonmapper.processing import list_known_essentials
def read_pergene_file(pergenefile):
"""It reads the content of the pergene file , one of the outputs of Transposonmapper
Parameters
----------
... | 0.624294 | 0.576363 |
'''Turns a stroke into dots.'''
__url__ = 'http://github.com/silnrsi/stroke-font-tools'
__copyright__ = 'Copyright (c) 2019 SIL International (http://www.sil.org)'
__license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)'
__author__ = '<NAME>, <NAME>'
# Usage: python3 dotstroke.py StrokeTest-... | tools/dotstroke.py | '''Turns a stroke into dots.'''
__url__ = 'http://github.com/silnrsi/stroke-font-tools'
__copyright__ = 'Copyright (c) 2019 SIL International (http://www.sil.org)'
__license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)'
__author__ = '<NAME>, <NAME>'
# Usage: python3 dotstroke.py StrokeTest-... | 0.379723 | 0.164215 |
from collections import namedtuple
import json
import logging
import os
import pprint
import sys
import threading
import webbrowser
import pyperclip
import requests
import toga
from toga.style import Pack
from toga.style.pack import COLUMN, CENTER
import dativetop.logging
import dativetop.constants as c
import dative... | src/dativetop/app.py | from collections import namedtuple
import json
import logging
import os
import pprint
import sys
import threading
import webbrowser
import pyperclip
import requests
import toga
from toga.style import Pack
from toga.style.pack import COLUMN, CENTER
import dativetop.logging
import dativetop.constants as c
import dative... | 0.400046 | 0.098686 |
import logging
from datetime import datetime, timedelta
from apscheduler.events import EVENT_JOB_EXECUTED, JobExecutionEvent
from apscheduler.schedulers.base import BaseScheduler
class JobMisfireError(RuntimeError):
pass
def enable_job_retry(
scheduler: BaseScheduler,
retry_delay: timedelta,
max_re... | retry.py | import logging
from datetime import datetime, timedelta
from apscheduler.events import EVENT_JOB_EXECUTED, JobExecutionEvent
from apscheduler.schedulers.base import BaseScheduler
class JobMisfireError(RuntimeError):
pass
def enable_job_retry(
scheduler: BaseScheduler,
retry_delay: timedelta,
max_re... | 0.356335 | 0.098599 |
from bitarray._bitarray import _bitarray, bitdiff, bits2bytes, _sysinfo
__version__ = '1.2.1'
class bitarray(_bitarray):
"""bitarray(initial=0, /, endian='big')
Return a new bitarray object whose items are bits initialized from
the optional initial object, and endianness.
If no initial object is provided, an em... | shell/ext-py/bitarray-1.2.1/bitarray/__init__.py | from bitarray._bitarray import _bitarray, bitdiff, bits2bytes, _sysinfo
__version__ = '1.2.1'
class bitarray(_bitarray):
"""bitarray(initial=0, /, endian='big')
Return a new bitarray object whose items are bits initialized from
the optional initial object, and endianness.
If no initial object is provided, an em... | 0.868353 | 0.691517 |
from __future__ import absolute_import
__all__ = ('Filter', 'GroupFilter', 'EventFilter')
from django.utils.datastructures import SortedDict
from sentry.models import Group, Event, FilterValue, MessageIndex
from .widgets import ChoiceWidget
class Filter(object):
label = ''
column = ''
widget = ChoiceWi... | src/sentry/filters/base.py | from __future__ import absolute_import
__all__ = ('Filter', 'GroupFilter', 'EventFilter')
from django.utils.datastructures import SortedDict
from sentry.models import Group, Event, FilterValue, MessageIndex
from .widgets import ChoiceWidget
class Filter(object):
label = ''
column = ''
widget = ChoiceWi... | 0.646237 | 0.126515 |
import colour
from colour.utilities import message_box
message_box('Colour Component Transfer Functions (CCTF) Computations')
C = 18 / 100
message_box(('Encoding to video component signal value using "BT.709" OETF '
'and given linear-light value:\n'
'\n\t{0}'.format(C)))
print(colour.oetf(C... | colour/examples/models/examples_transfer_functions.py | import colour
from colour.utilities import message_box
message_box('Colour Component Transfer Functions (CCTF) Computations')
C = 18 / 100
message_box(('Encoding to video component signal value using "BT.709" OETF '
'and given linear-light value:\n'
'\n\t{0}'.format(C)))
print(colour.oetf(C... | 0.601477 | 0.206294 |
import time
import traceback
import pygame
DEBOUNCE_PERIOD = 1.0 / 50.0
class Controller(object):
def __init__(self, state_change_callback=None):
pygame.init()
pygame.joystick.init()
self.controller = pygame.joystick.Joystick(0)
self.controller.init()
self.state_change_... | phase_3/controller.py | import time
import traceback
import pygame
DEBOUNCE_PERIOD = 1.0 / 50.0
class Controller(object):
def __init__(self, state_change_callback=None):
pygame.init()
pygame.joystick.init()
self.controller = pygame.joystick.Joystick(0)
self.controller.init()
self.state_change_... | 0.391871 | 0.156201 |
import threading
import socket
import sys
#Host and port declaration (uses localhost)
host = '127.0.0.1'
port = 8080
#Creates socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Server binding
server.bind((host, port))
server.listen()
#Handles the client messeges
def clientHandler(cli... | myServer.py | import threading
import socket
import sys
#Host and port declaration (uses localhost)
host = '127.0.0.1'
port = 8080
#Creates socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Server binding
server.bind((host, port))
server.listen()
#Handles the client messeges
def clientHandler(cli... | 0.152127 | 0.038214 |
import numpy as np
import pandas as pd
from sitka.utils.time_series import TimeSeriesComponent
class ExternalShortwaveRadiation(TimeSeriesComponent):
"""
External shortwave radiation calculation for time-series.
Parameters
----------
time : Time
solar_angles : SolarAngles
weather : Weath... | sitka/calculations/radiation.py | import numpy as np
import pandas as pd
from sitka.utils.time_series import TimeSeriesComponent
class ExternalShortwaveRadiation(TimeSeriesComponent):
"""
External shortwave radiation calculation for time-series.
Parameters
----------
time : Time
solar_angles : SolarAngles
weather : Weath... | 0.905154 | 0.571587 |
import subprocess
import sys
from collections import namedtuple
def pad_list(items, pad_to=10, pad_with=''):
if len(items) >= pad_to:
return items
return items + [pad_with for i in range(0, pad_to - len(items))]
def namedtuplify(headers, rows):
max_cols = len(headers)
Row = namedtuple(
... | prune.py | import subprocess
import sys
from collections import namedtuple
def pad_list(items, pad_to=10, pad_with=''):
if len(items) >= pad_to:
return items
return items + [pad_with for i in range(0, pad_to - len(items))]
def namedtuplify(headers, rows):
max_cols = len(headers)
Row = namedtuple(
... | 0.258981 | 0.396243 |
import time
import sqlite3
import threading
from reddit.redditconstants import WAIT, SUBREDDIT, IGNOREAUTHORS, KEYWORDS, MAXPOSTS, CLEANCYCLES
from reddit import workeranalyzecontent
from reddit.botinfo import message
message2 = False
def findComments(r):
subreddit = r.subreddit(SUBREDDIT)
cycles = 0
if... | reddit/workerfindcomments.py | import time
import sqlite3
import threading
from reddit.redditconstants import WAIT, SUBREDDIT, IGNOREAUTHORS, KEYWORDS, MAXPOSTS, CLEANCYCLES
from reddit import workeranalyzecontent
from reddit.botinfo import message
message2 = False
def findComments(r):
subreddit = r.subreddit(SUBREDDIT)
cycles = 0
if... | 0.071721 | 0.062962 |
import sys
import argparse
import configparser
import logging
import os
import binascii
import numpy as np
from datetime import datetime
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logger = logging.getLogger(__name__)
def set_if_none(target, value):
if target is None:
return value
els... | tools/convert_screaming_to_cw.py | import sys
import argparse
import configparser
import logging
import os
import binascii
import numpy as np
from datetime import datetime
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logger = logging.getLogger(__name__)
def set_if_none(target, value):
if target is None:
return value
els... | 0.247987 | 0.133443 |
try:
from utils import *
except ImportError:
from scrapeutils.utils import *
SCRIPTPATH=os.path.dirname(os.path.abspath(sys.argv[0]))
JSON_OUTPUT_FILE = os.path.abspath(os.path.join(SCRIPTPATH, '..', "data", "courses.json"))
SEARCH_URL = r'https://www.pluralsight.com/search?categories=course&sort=title'
def ... | scrapeutils/autoscrape_pluralsight_regex.py | try:
from utils import *
except ImportError:
from scrapeutils.utils import *
SCRIPTPATH=os.path.dirname(os.path.abspath(sys.argv[0]))
JSON_OUTPUT_FILE = os.path.abspath(os.path.join(SCRIPTPATH, '..', "data", "courses.json"))
SEARCH_URL = r'https://www.pluralsight.com/search?categories=course&sort=title'
def ... | 0.207616 | 0.100613 |
import sys
import os
import math
import fnmatch
from timeit import default_timer as timer
from multiprocessing import Process, Queue
import numpy
from scipy.spatial import KDTree
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as Figure... | nsmaps/contourmap.py | import sys
import os
import math
import fnmatch
from timeit import default_timer as timer
from multiprocessing import Process, Queue
import numpy
from scipy.spatial import KDTree
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as Figure... | 0.475118 | 0.222848 |
from matplotlib.colors import ListedColormap,LogNorm
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import cmasher as cma
import pandas as pd
from matplotlib.ticker import LogLocator,AutoLocator,AutoMinorLocator,MaxNLocator
from .sampler import to_time_series, TigressWindSampler
discrete_cm... | twind/plotter.py | from matplotlib.colors import ListedColormap,LogNorm
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import cmasher as cma
import pandas as pd
from matplotlib.ticker import LogLocator,AutoLocator,AutoMinorLocator,MaxNLocator
from .sampler import to_time_series, TigressWindSampler
discrete_cm... | 0.63114 | 0.506713 |
from oslo_log import log as logging
from tempest.common import utils
from tempest import config
from tempest.lib.common import api_version_utils
from tempest.lib import decorators
from barbican_tempest_plugin.tests.scenario import barbican_manager
CONF = config.CONF
LOG = logging.getLogger(__name__)
class Ephemera... | barbican_tempest_plugin/tests/scenario/test_ephemeral_disk_encryption.py |
from oslo_log import log as logging
from tempest.common import utils
from tempest import config
from tempest.lib.common import api_version_utils
from tempest.lib import decorators
from barbican_tempest_plugin.tests.scenario import barbican_manager
CONF = config.CONF
LOG = logging.getLogger(__name__)
class Ephemera... | 0.470007 | 0.319559 |
import os
import numpy as np
from signal_utils import save_audio
from signal_utils import audio_files_to_numpy
from signal_utils import blend_voice_with_noise
from signal_utils import numpy_audio_to_matrix_spectrogram
import argparse
def make_dir(path):
try:
os.makedirs(path)
except OSError:
p... | create_dataset.py | import os
import numpy as np
from signal_utils import save_audio
from signal_utils import audio_files_to_numpy
from signal_utils import blend_voice_with_noise
from signal_utils import numpy_audio_to_matrix_spectrogram
import argparse
def make_dir(path):
try:
os.makedirs(path)
except OSError:
p... | 0.396302 | 0.3029 |
import unittest
from swamp.parsers.mtzparser import MtzParser
class MockGemmiMtz(object):
"""A class to mock :py:obj:gemmi.Mtz for testing purposes
:param list columns: a list containing instances of :py:obj:`~swmap.parsers.tests.test_mtz_parser.MockGemmiMtzColumn`
"""
def __init__(self, columns):
... | swamp/parsers/tests/test_mtz_parser.py | import unittest
from swamp.parsers.mtzparser import MtzParser
class MockGemmiMtz(object):
"""A class to mock :py:obj:gemmi.Mtz for testing purposes
:param list columns: a list containing instances of :py:obj:`~swmap.parsers.tests.test_mtz_parser.MockGemmiMtzColumn`
"""
def __init__(self, columns):
... | 0.674265 | 0.512083 |
import logging
from app_common.apptools.io.serializer import DataElement_Serializer, \
Serializer
logger = logging.getLogger(__name__)
def serialize(obj, array_collection=None):
""" Serialization functional entry point.
Parameters
----------
obj : any
Object to serialize
array_coll... | pybleau/app/io/serializer.py | import logging
from app_common.apptools.io.serializer import DataElement_Serializer, \
Serializer
logger = logging.getLogger(__name__)
def serialize(obj, array_collection=None):
""" Serialization functional entry point.
Parameters
----------
obj : any
Object to serialize
array_coll... | 0.747524 | 0.224045 |
from argparse import ArgumentParser
from collections import defaultdict
import csv
from functools import partial
from multiprocessing import Pool
import os
import random
from typing import Dict, List, Tuple
from rdkit import Chem
from rdkit.Chem import rdFMCS, rdMolAlign, rdShapeHelpers
from tqdm import tqdm
def loa... | 3d/build_conformer_pairs.py | from argparse import ArgumentParser
from collections import defaultdict
import csv
from functools import partial
from multiprocessing import Pool
import os
import random
from typing import Dict, List, Tuple
from rdkit import Chem
from rdkit.Chem import rdFMCS, rdMolAlign, rdShapeHelpers
from tqdm import tqdm
def loa... | 0.656658 | 0.302114 |
import random
from dataclasses import dataclass
from datetime import datetime
from typing import Iterable, List, Optional
from dateutil.parser import parse as parse_datetime
from .hashing import sha256
from .messages import MessageInfo
from .storage import Storage, get_default_storage
from .times import now
async d... | pepubot/lottery_box.py | import random
from dataclasses import dataclass
from datetime import datetime
from typing import Iterable, List, Optional
from dateutil.parser import parse as parse_datetime
from .hashing import sha256
from .messages import MessageInfo
from .storage import Storage, get_default_storage
from .times import now
async d... | 0.760072 | 0.232114 |
import collections
import math
import numpy as np
import sqlite3
import time
from statistics import mean
from datetime import datetime, timedelta
SAMPLE_PERIOD_S = 60
HOURLY_TIME_DELTA_S = SAMPLE_PERIOD_S * 60
# timestamp and uid must be the first two
data_columns = [
"timestamp",
"uid",
"temperature",
... | sw/chaac/chaac/chaacdb.py | import collections
import math
import numpy as np
import sqlite3
import time
from statistics import mean
from datetime import datetime, timedelta
SAMPLE_PERIOD_S = 60
HOURLY_TIME_DELTA_S = SAMPLE_PERIOD_S * 60
# timestamp and uid must be the first two
data_columns = [
"timestamp",
"uid",
"temperature",
... | 0.5 | 0.222331 |
import torch.nn as nn
import torch
import math
import torch.nn.functional as F
import random
from models.networks.base_networks import *
import os
class BaseGenerator(nn.Module):
def __init__(self, img_nc=3, kpt_nc=18, ngf=64, latent_nc=256, style_nc=64, n_human_parts=8, n_downsampling=4, n_style_blocks=4, norm_ty... | models/networks/generators.py | import torch.nn as nn
import torch
import math
import torch.nn.functional as F
import random
from models.networks.base_networks import *
import os
class BaseGenerator(nn.Module):
def __init__(self, img_nc=3, kpt_nc=18, ngf=64, latent_nc=256, style_nc=64, n_human_parts=8, n_downsampling=4, n_style_blocks=4, norm_ty... | 0.841207 | 0.288181 |
import binascii
from substrateinterface import SubstrateInterface
from substrateinterface.utils import hasher
from scalecodec.base import ScaleBytes, RuntimeConfiguration
from scalecodec.type_registry import load_type_registry_preset
#subkey inspect "//Alice"
#acc_pk = bytearray.fromhex("6031188a7c447201a20c044b5e... | read_attr_cs.py | import binascii
from substrateinterface import SubstrateInterface
from substrateinterface.utils import hasher
from scalecodec.base import ScaleBytes, RuntimeConfiguration
from scalecodec.type_registry import load_type_registry_preset
#subkey inspect "//Alice"
#acc_pk = bytearray.fromhex("6031188a7c447201a20c044b5e... | 0.308294 | 0.168686 |
import os
import re
# Draws a big pretty looking sign
def printAnouncement(msg, char='=', lineCount=1, width=80):
separatorStr = char * width
print ('')
for i in range(lineCount):
print (separatorStr)
minBorder = width//10
if minBorder < 3:
minBorder = 3
... | common/si.isystem.commons.plugin/buildUtils.py | import os
import re
# Draws a big pretty looking sign
def printAnouncement(msg, char='=', lineCount=1, width=80):
separatorStr = char * width
print ('')
for i in range(lineCount):
print (separatorStr)
minBorder = width//10
if minBorder < 3:
minBorder = 3
... | 0.169166 | 0.066843 |
from smac.env import StarCraft2Env
import numpy as np
import os
from sc2_model import ComaModel
from sc2_agent import Agents
from parl.algorithms import COMA
from parl.utils import tensorboard
def run_episode(env, agents, config, test=False):
o, u, r, s, avail_u, u_onehot, isover, padded = [], [], [], [], [], []... | benchmark/torch/coma/train.py |
from smac.env import StarCraft2Env
import numpy as np
import os
from sc2_model import ComaModel
from sc2_agent import Agents
from parl.algorithms import COMA
from parl.utils import tensorboard
def run_episode(env, agents, config, test=False):
o, u, r, s, avail_u, u_onehot, isover, padded = [], [], [], [], [], []... | 0.328206 | 0.152852 |
from sauronlab.caches.caching_wfs import *
from sauronlab.caches.sensor_caches import *
from sauronlab.caches.wf_caches import *
from sauronlab.core.core_imports import *
from sauronlab.model.compound_names import *
from sauronlab.model.features import FeatureType
from sauronlab.model.well_frames import *
from sauronla... | sauronlab/caches/datasets.py | from sauronlab.caches.caching_wfs import *
from sauronlab.caches.sensor_caches import *
from sauronlab.caches.wf_caches import *
from sauronlab.core.core_imports import *
from sauronlab.model.compound_names import *
from sauronlab.model.features import FeatureType
from sauronlab.model.well_frames import *
from sauronla... | 0.716318 | 0.118283 |
from fastai.vision import *
from io import BytesIO
from typing import List, Dict, Union, ByteString
import requests
def load_model(path=".", file="classifier.pkl"):
learn = load_learner(path, file=file)
return learn
def load_image_url(url: str) -> Image:
response = requests.get(url)
img = open_image... | predict.py | from fastai.vision import *
from io import BytesIO
from typing import List, Dict, Union, ByteString
import requests
def load_model(path=".", file="classifier.pkl"):
learn = load_learner(path, file=file)
return learn
def load_image_url(url: str) -> Image:
response = requests.get(url)
img = open_image... | 0.755366 | 0.417331 |
from pytket.circuit import Circuit, PauliExpBox, Pauli
from pytket.predicates import CompilationUnit
from pytket.passes import DecomposeBoxes, PauliSimp, SequencePass
from pytket.utils import expectation_from_counts
from pytket.extensions.qiskit import AerBackend, AerStateBackend
from sympy import Symbol
from scipy.o... | examples/oxfordQIS.py |
from pytket.circuit import Circuit, PauliExpBox, Pauli
from pytket.predicates import CompilationUnit
from pytket.passes import DecomposeBoxes, PauliSimp, SequencePass
from pytket.utils import expectation_from_counts
from pytket.extensions.qiskit import AerBackend, AerStateBackend
from sympy import Symbol
from scipy.o... | 0.866104 | 0.731526 |
import sys
import os.path
import configparser
import random
import psutil
import subprocess
import time
import win32gui
from pyautogui import press
import winreg # Renamed from _winreg in Pyhon 3
from rlbot.setup_manager import SetupManager
class TournamentManager:
def __init__(self):
self.available_bots_... | tournament_manager.py | import sys
import os.path
import configparser
import random
import psutil
import subprocess
import time
import win32gui
from pyautogui import press
import winreg # Renamed from _winreg in Pyhon 3
from rlbot.setup_manager import SetupManager
class TournamentManager:
def __init__(self):
self.available_bots_... | 0.141934 | 0.068164 |
import logging
from typing import Any, Dict, List, Optional, Tuple, Union
import validators
from alerta.app import db
JSON = Dict[str, Any]
class CustomerChannel:
SUPPORTED_CHANNEL_TYPES = ["webhook", "email"]
def __init__(self, name, channel_type, properties, customer_id, is_active=True, id=None):
... | alerta/models/channel.py | import logging
from typing import Any, Dict, List, Optional, Tuple, Union
import validators
from alerta.app import db
JSON = Dict[str, Any]
class CustomerChannel:
SUPPORTED_CHANNEL_TYPES = ["webhook", "email"]
def __init__(self, name, channel_type, properties, customer_id, is_active=True, id=None):
... | 0.828488 | 0.105441 |
import itertools
import numpy
from phydat import phycon
from phydat import ptab
import automol.util.vec
import automol.create as _create
def coordinates(geo, idxs=None, angstrom=False):
""" Obtain the Cartesian coordinates of atoms in the molecular geometry.
:param geo: molecular geometry
:type g... | automol/graph/geom.py | import itertools
import numpy
from phydat import phycon
from phydat import ptab
import automol.util.vec
import automol.create as _create
def coordinates(geo, idxs=None, angstrom=False):
""" Obtain the Cartesian coordinates of atoms in the molecular geometry.
:param geo: molecular geometry
:type g... | 0.765418 | 0.770767 |
import os
from base import BaseDataSet, BaseDataLoader
from utils import palette
import glob
import numpy as np
from PIL import Image
from skimage import io
class PhotovoltaicDataset(BaseDataSet):
"""
Pascal Voc dataset
http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar
"""
... | dataloaders/photovoltaic.py | import os
from base import BaseDataSet, BaseDataLoader
from utils import palette
import glob
import numpy as np
from PIL import Image
from skimage import io
class PhotovoltaicDataset(BaseDataSet):
"""
Pascal Voc dataset
http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar
"""
... | 0.595022 | 0.217795 |
import random
import numpy
import torch
class Vocabulary(object):
def __init__(self, file_or_object, size: int = None, eos: str = '</s>', unk: str = '<unk>',
pad: str = "<blank>") -> None:
super().__init__()
self._size = size
self._pad = pad
self._eos = eos
... | thseq/data/vocabulary.py | import random
import numpy
import torch
class Vocabulary(object):
def __init__(self, file_or_object, size: int = None, eos: str = '</s>', unk: str = '<unk>',
pad: str = "<blank>") -> None:
super().__init__()
self._size = size
self._pad = pad
self._eos = eos
... | 0.710327 | 0.299048 |
"""Base class for plugins used by the central agent.
"""
from keystoneclient.v2_0 import client as ksclient
from oslo.config import cfg
from ceilometer.openstack.common.gettextutils import _
from ceilometer.openstack.common import log
from ceilometer import plugin
cfg.CONF.import_opt('http_timeout', 'ceilometer.servi... | ceilometer/central/plugin.py | """Base class for plugins used by the central agent.
"""
from keystoneclient.v2_0 import client as ksclient
from oslo.config import cfg
from ceilometer.openstack.common.gettextutils import _
from ceilometer.openstack.common import log
from ceilometer import plugin
cfg.CONF.import_opt('http_timeout', 'ceilometer.servi... | 0.668447 | 0.076304 |
import unittest
from struct import error
from DAT.Header import Header, HEADER_OFFSET
class TestParse(unittest.TestCase):
def setUp(self):
self.header = Header()
def test_parse_valid_blob0(self):
fp = open("tests/data/headers/header0.bin", "rb")
fp.seek(HEADER_OFFSET)
self.h... | tests/DAT/test_Header.py | import unittest
from struct import error
from DAT.Header import Header, HEADER_OFFSET
class TestParse(unittest.TestCase):
def setUp(self):
self.header = Header()
def test_parse_valid_blob0(self):
fp = open("tests/data/headers/header0.bin", "rb")
fp.seek(HEADER_OFFSET)
self.h... | 0.501465 | 0.511107 |
import uuid
from pamqp import body, commands, header
from aiorabbit import exceptions, message
from . import testing
class BasicAckTestCase(testing.ClientTestCase):
@testing.async_test
async def test_validation_errors(self):
await self.connect()
with self.assertRaises(TypeError):
... | tests/test_basic.py | import uuid
from pamqp import body, commands, header
from aiorabbit import exceptions, message
from . import testing
class BasicAckTestCase(testing.ClientTestCase):
@testing.async_test
async def test_validation_errors(self):
await self.connect()
with self.assertRaises(TypeError):
... | 0.568056 | 0.393909 |
from __future__ import division, print_function, unicode_literals, \
absolute_import
import unittest
import os
import pandas as pd
import numpy as np
from pymatgen import Structure, Element, Lattice
from veidt.describer.structural_describer import DistinctSiteProperty
from veidt.describer.structural_describer imp... | veidt/describer/tests/test_structural_describer.py |
from __future__ import division, print_function, unicode_literals, \
absolute_import
import unittest
import os
import pandas as pd
import numpy as np
from pymatgen import Structure, Element, Lattice
from veidt.describer.structural_describer import DistinctSiteProperty
from veidt.describer.structural_describer imp... | 0.595845 | 0.480296 |
from django.test import TestCase
from storage import models
from storage import actions
class ActionsTest(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
# Authors
herman_melville = models.Author.objects.create(
first_name='Herman',
last_name... | storage/tests.py | from django.test import TestCase
from storage import models
from storage import actions
class ActionsTest(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
# Authors
herman_melville = models.Author.objects.create(
first_name='Herman',
last_name... | 0.581065 | 0.375048 |
import unittest
import torch
from towhee.models import clip
class TestClip(unittest.TestCase):
"""
Test CLIP model
"""
def test_clip(self):
img = torch.rand(1, 3, 4, 4)
text = torch.randint(high=49408, size=(2, 77), dtype=torch.int32)
model = clip.create_model(
emb... | tests/unittests/models/clip/test_clip.py |
import unittest
import torch
from towhee.models import clip
class TestClip(unittest.TestCase):
"""
Test CLIP model
"""
def test_clip(self):
img = torch.rand(1, 3, 4, 4)
text = torch.randint(high=49408, size=(2, 77), dtype=torch.int32)
model = clip.create_model(
emb... | 0.721939 | 0.650356 |
import yalix.utils as utils
from abc import ABCMeta, abstractmethod
from yalix.environment import Env
from yalix.exceptions import EvaluationError
class Primitive(object):
__metaclass__ = ABCMeta
# def __repr__(self):
# return str(self.eval(Env()))
@abstractmethod
def eval(self, env):
... | python/src/yalix/interpreter.py | import yalix.utils as utils
from abc import ABCMeta, abstractmethod
from yalix.environment import Env
from yalix.exceptions import EvaluationError
class Primitive(object):
__metaclass__ = ABCMeta
# def __repr__(self):
# return str(self.eval(Env()))
@abstractmethod
def eval(self, env):
... | 0.615203 | 0.271427 |
from app.cluegame import ClueRelationType, Game
import pytest
@pytest.fixture
def clue_game():
return Game(
[
"<NAME>",
"<NAME>",
"<NAME>",
"Mrs. White",
"Mr. Green",
"Mrs. Peacock"
],
... | tests/test_game.py | from app.cluegame import ClueRelationType, Game
import pytest
@pytest.fixture
def clue_game():
return Game(
[
"<NAME>",
"<NAME>",
"<NAME>",
"Mrs. White",
"Mr. Green",
"Mrs. Peacock"
],
... | 0.410047 | 0.417568 |
from flask import Flask, Response, redirect, url_for, request, send_file, session
from werkzeug.utils import header_property
from flask_session import Session
from werkzeug.utils import secure_filename
import json
from tags import MusicFileHandler
from database import DatabaseHandler
from utils import returnJSON... | src/server.py | from flask import Flask, Response, redirect, url_for, request, send_file, session
from werkzeug.utils import header_property
from flask_session import Session
from werkzeug.utils import secure_filename
import json
from tags import MusicFileHandler
from database import DatabaseHandler
from utils import returnJSON... | 0.304559 | 0.037117 |
from xml.etree import ElementTree
from typing import Final
from functools import reduce
from html import escape
from src import xml2html
import sys
import re
# The sub-components used in this component.
childComponents:Final = [
]
def html(tree:ElementTree):
html = ""
def make_fn_documentation(functionElems... | src/components/vcs/DataFieldDocumentation.py |
from xml.etree import ElementTree
from typing import Final
from functools import reduce
from html import escape
from src import xml2html
import sys
import re
# The sub-components used in this component.
childComponents:Final = [
]
def html(tree:ElementTree):
html = ""
def make_fn_documentation(functionElems... | 0.549641 | 0.169337 |
import win32gui
import win32process
import psutil
import json
import ntpath
import logging
with open('meta.json') as f:
# Parses metadata for associated applications
logging.debug("Loading 'meta.json'")
data = json.load(f)
def get_process_info():
# Retrieves pid of listed Adobe Application
logging... | api/windows.py | import win32gui
import win32process
import psutil
import json
import ntpath
import logging
with open('meta.json') as f:
# Parses metadata for associated applications
logging.debug("Loading 'meta.json'")
data = json.load(f)
def get_process_info():
# Retrieves pid of listed Adobe Application
logging... | 0.213377 | 0.069447 |
from __future__ import annotations
import asyncio
import logging
import os
import platform
import sys
import traceback
import typing as T
from contextlib import suppress
from dataclasses import dataclass
from functools import partial
from pathlib import Path
import aiohttp
import arrow
import discord
from discord imp... | naotimes/bot.py | from __future__ import annotations
import asyncio
import logging
import os
import platform
import sys
import traceback
import typing as T
from contextlib import suppress
from dataclasses import dataclass
from functools import partial
from pathlib import Path
import aiohttp
import arrow
import discord
from discord imp... | 0.491456 | 0.048631 |