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 django.test import TestCase from rest_framework import serializers from rest_framework.serializers import ListSerializer from ai_django_core.drf.fields import RecursiveField from testapp.models import ModelWithFkToSelf, ModelWithOneToOneToSelf class TestManyTrueSerializer(serializers.ModelSerializer): child...
tests/drf/test_fields.py
from django.test import TestCase from rest_framework import serializers from rest_framework.serializers import ListSerializer from ai_django_core.drf.fields import RecursiveField from testapp.models import ModelWithFkToSelf, ModelWithOneToOneToSelf class TestManyTrueSerializer(serializers.ModelSerializer): child...
0.746324
0.388763
import logging import warnings _logger = logging.getLogger(__name__) class UserError(Exception): """Generic error managed by the client. Typically when the user tries to do something that has no sense given the current state of a record. Semantically comparable to the generic 400 HTTP status codes. ...
odoo/exceptions.py
import logging import warnings _logger = logging.getLogger(__name__) class UserError(Exception): """Generic error managed by the client. Typically when the user tries to do something that has no sense given the current state of a record. Semantically comparable to the generic 400 HTTP status codes. ...
0.754101
0.246035
from edparser.utils.io_util import load_pickle, save_pickle from iwpt2020 import cdroot import numpy as np import matplotlib.pyplot as plt cdroot() gold_file = 'data/iwpt2020/test-udpipe/en.fixed.conllu' template = 'data/model/iwpt2020/bert/dep/en.conllu' def load_conll(path): with open(path) as src: t...
iwpt2020/error/oov.py
from edparser.utils.io_util import load_pickle, save_pickle from iwpt2020 import cdroot import numpy as np import matplotlib.pyplot as plt cdroot() gold_file = 'data/iwpt2020/test-udpipe/en.fixed.conllu' template = 'data/model/iwpt2020/bert/dep/en.conllu' def load_conll(path): with open(path) as src: t...
0.35031
0.174129
import unittest # Importing unittest Module from credential import Credential # Importing Credential Class class TestCredential(unittest.TestCase): ''' Test class that defines test cases for the credentials class behaviours. Arg: unittest.TestCase: TestCase class that helps in creating test cases...
credential_test.py
import unittest # Importing unittest Module from credential import Credential # Importing Credential Class class TestCredential(unittest.TestCase): ''' Test class that defines test cases for the credentials class behaviours. Arg: unittest.TestCase: TestCase class that helps in creating test cases...
0.522446
0.48871
import numpy as np import pandas from ggplot import * """ In this question, you need to: 1) implement the compute_cost() and gradient_descent() procedures 2) Select features (in the predictions procedure) and make predictions. """ def normalize_features(df): """ Normalize the features in the data set. ""...
chapter3/subwayRegress.py
import numpy as np import pandas from ggplot import * """ In this question, you need to: 1) implement the compute_cost() and gradient_descent() procedures 2) Select features (in the predictions procedure) and make predictions. """ def normalize_features(df): """ Normalize the features in the data set. ""...
0.666605
0.862525
# #### Level-4 data of L1000 gene-expression profiling is calculated as: # # Level 4 - Differential Expression (ZSPC): # # To obtain a measure of relative gene expression, we use a robust z-scoring procedure to generate differential expression values from normalized profiles (Level-3). We compute the **differential ...
1.Data-exploration/Profiles_level4/L1000/scripts/nbconverted/L1000_calculate_cpd_median_score.py
# #### Level-4 data of L1000 gene-expression profiling is calculated as: # # Level 4 - Differential Expression (ZSPC): # # To obtain a measure of relative gene expression, we use a robust z-scoring procedure to generate differential expression values from normalized profiles (Level-3). We compute the **differential ...
0.718199
0.602062
import io import os def save_file(fh, path, name): """ Saves BytesIO stream into path/name """ with io.open(os.path.join(path, name), "wb") as file: fh.seek(0) file.write(fh.read()) def prettify_listing(items): """ Prints file names, one filename per line """ if len(items) > 1: ...
Backup_client/util.py
import io import os def save_file(fh, path, name): """ Saves BytesIO stream into path/name """ with io.open(os.path.join(path, name), "wb") as file: fh.seek(0) file.write(fh.read()) def prettify_listing(items): """ Prints file names, one filename per line """ if len(items) > 1: ...
0.421433
0.244597
# # CODI Prevelance Query (PQ) Results Visualization # # # ## Background - PQ algorithm # # [CODI-PQ](https://github.com/NORC-UChicago/CODI-PQ) is a program for weight-status-category prevalence based on BMI, and results can be stratified by age, sex, race and geography. PQViz can support the simple output of both ...
PQViz.py
# # CODI Prevelance Query (PQ) Results Visualization # # # ## Background - PQ algorithm # # [CODI-PQ](https://github.com/NORC-UChicago/CODI-PQ) is a program for weight-status-category prevalence based on BMI, and results can be stratified by age, sex, race and geography. PQViz can support the simple output of both ...
0.768473
0.758533
import argparse # TODO: Add any additional required modules import jinja2 import os import datetime # TODO: Think about reusability def save_to_text_file(fn, data): with open(fn, "w") as cfgfile: cfgfile.write(data) print(f"\nSaved Rendered Configuration to file {fn} in current script directory.") ...
sec09-2_gen_config_from_j2template/config_script.py
import argparse # TODO: Add any additional required modules import jinja2 import os import datetime # TODO: Think about reusability def save_to_text_file(fn, data): with open(fn, "w") as cfgfile: cfgfile.write(data) print(f"\nSaved Rendered Configuration to file {fn} in current script directory.") ...
0.213295
0.376852
get_all_qst = '''select questions.id as question_id, questions.question_text, questions.answer_text, askers.name as asker_name, experts.name as expert_name from questions join users as askers on askers.id = questions.asked_by_id join ...
Back-End/Python/External Libraries/Flask/Flask_website_examples/05 Question - Answer App/app_query.py
get_all_qst = '''select questions.id as question_id, questions.question_text, questions.answer_text, askers.name as asker_name, experts.name as expert_name from questions join users as askers on askers.id = questions.asked_by_id join ...
0.134691
0.089216
import os import numpy as np import pandas as pd from mlblocks.discovery import load_pipeline from orion.core import Orion class TestOrion: @classmethod def setup_class(cls): cls.clean = pd.DataFrame({ 'timestamp': list(range(100)), 'value': [1] * 100, }) cls...
tests/test_core.py
import os import numpy as np import pandas as pd from mlblocks.discovery import load_pipeline from orion.core import Orion class TestOrion: @classmethod def setup_class(cls): cls.clean = pd.DataFrame({ 'timestamp': list(range(100)), 'value': [1] * 100, }) cls...
0.643105
0.512327
import sys import types import newrelic.packages.six as six import newrelic.api.transaction import newrelic.api.object_wrapper import newrelic.api.external_trace class capture_external_trace(object): def __init__(self, wrapped): newrelic.api.object_wrapper.update_wrapper(self, wrapped) self._nr_...
venv/lib/python2.7/site-packages/newrelic-2.62.0.47/newrelic/hooks/external_feedparser.py
import sys import types import newrelic.packages.six as six import newrelic.api.transaction import newrelic.api.object_wrapper import newrelic.api.external_trace class capture_external_trace(object): def __init__(self, wrapped): newrelic.api.object_wrapper.update_wrapper(self, wrapped) self._nr_...
0.320183
0.064036
from euler_python.utils import eulerlib def problem090(): """ Each of the six faces on a cube has a different digit (0 to 9) written on it; the same is done to a second cube. By placing the two cubes side-by-side in different positions we can form a variety of 2-digit numbers. F...
src/euler_python_package/euler_python/medium/p090.py
from euler_python.utils import eulerlib def problem090(): """ Each of the six faces on a cube has a different digit (0 to 9) written on it; the same is done to a second cube. By placing the two cubes side-by-side in different positions we can form a variety of 2-digit numbers. F...
0.642769
0.848282
import numpy as np def logPPDNA(misfits): """ Calculate the log-posterior probability density function of model This routine converts the input data array to a log posterior probability density function. For example if the input data for each model is a simple sum of squares of residuals weig...
pyNA/appraise.py
import numpy as np def logPPDNA(misfits): """ Calculate the log-posterior probability density function of model This routine converts the input data array to a log posterior probability density function. For example if the input data for each model is a simple sum of squares of residuals weig...
0.886316
0.913252
import numpy as np import cv2 import matplotlib.pyplot as plt import math id = 3 # 图像预处理,长宽需要一致,最好都是偶数 fp_read, fp_write = '12.4 stiv images/%d_%d_599.jpg' % (id, 90 + id), '%d_%d_599_filtered.jpg' % (id, 90 + id) img = plt.imread(fp_read) img = img[:, 100:400] height = np.array(img).shape[0] width = np.array(img).sh...
fuliye.py
import numpy as np import cv2 import matplotlib.pyplot as plt import math id = 3 # 图像预处理,长宽需要一致,最好都是偶数 fp_read, fp_write = '12.4 stiv images/%d_%d_599.jpg' % (id, 90 + id), '%d_%d_599_filtered.jpg' % (id, 90 + id) img = plt.imread(fp_read) img = img[:, 100:400] height = np.array(img).shape[0] width = np.array(img).sh...
0.552057
0.557243
from PyDragonfly import Dragonfly_Module, CMessage, copy_from_msg, copy_to_msg, MT_EXIT import Dragonfly_config as rc from dragonfly_utils import respond_to_ping from argparse import ArgumentParser from ConfigParser import SafeConfigParser from PyQt4 import QtGui, QtCore from PyQt4.Qt import * import sys import random...
modules/CursorDisplay/CursorDisplay.py
from PyDragonfly import Dragonfly_Module, CMessage, copy_from_msg, copy_to_msg, MT_EXIT import Dragonfly_config as rc from dragonfly_utils import respond_to_ping from argparse import ArgumentParser from ConfigParser import SafeConfigParser from PyQt4 import QtGui, QtCore from PyQt4.Qt import * import sys import random...
0.214691
0.159544
import math import torch from torch import Tensor from torch.nn import Parameter from torch_geometric.nn.conv import MessagePassing, GCNConv class GCNIIConv(MessagePassing): """ The graph convolutional operator with initial residual connections and identity mapping (GCNII) from the `"Simple and Deep Grap...
gcnii_layer.py
import math import torch from torch import Tensor from torch.nn import Parameter from torch_geometric.nn.conv import MessagePassing, GCNConv class GCNIIConv(MessagePassing): """ The graph convolutional operator with initial residual connections and identity mapping (GCNII) from the `"Simple and Deep Grap...
0.922049
0.568775
from skopt.space import Categorical, Integer, Real from src.model import best_models from src.model.Interface import IContentModel, IBestModel, ICollaborativeModel import scipy.sparse as sps # ---------------- CONTENT BASED FILTERING ----------------- class ItemCBF_all(IContentModel): """ Item CBF tuned wit...
src/model/new_best_models.py
from skopt.space import Categorical, Integer, Real from src.model import best_models from src.model.Interface import IContentModel, IBestModel, ICollaborativeModel import scipy.sparse as sps # ---------------- CONTENT BASED FILTERING ----------------- class ItemCBF_all(IContentModel): """ Item CBF tuned wit...
0.797833
0.169269
from CycleGAN_ls import CycleGAN_LightningSystem from dataModule import ImageTransform, WatercolorDataset, WatercolorDataModule from discriminator import CycleGAN_Discriminator from generator import CycleGAN_Unet_Generator import os import glob import random import numpy as np import pandas as pd import matplotlib.pyp...
train.py
from CycleGAN_ls import CycleGAN_LightningSystem from dataModule import ImageTransform, WatercolorDataset, WatercolorDataModule from discriminator import CycleGAN_Discriminator from generator import CycleGAN_Unet_Generator import os import glob import random import numpy as np import pandas as pd import matplotlib.pyp...
0.639849
0.250414
import re import pytest from simpy import Interrupt from simpy.util import start_delayed, subscribe_at def test_start_delayed(env): def pem(env): assert env.now == 5 yield env.timeout(1) start_delayed(env, pem(env), delay=5) env.run() def test_start_delayed_error(env): """Check if...
Dessert.Benchmarks/SimPy3/test/test_util.py
import re import pytest from simpy import Interrupt from simpy.util import start_delayed, subscribe_at def test_start_delayed(env): def pem(env): assert env.now == 5 yield env.timeout(1) start_delayed(env, pem(env), delay=5) env.run() def test_start_delayed_error(env): """Check if...
0.599954
0.589244
from abc import abstractmethod import warnings import pandas as pd from fclib.feature_engineering.utils import is_datetime_like from fclib.feature_engineering.base_ts_estimators import BaseTSFeaturizer class BaseTemporalNormalizer(BaseTSFeaturizer): """ Base abstract class for creating normalized time feature...
contrib/tsperf/energy_utils/feature_engineering/normalization.py
from abc import abstractmethod import warnings import pandas as pd from fclib.feature_engineering.utils import is_datetime_like from fclib.feature_engineering.base_ts_estimators import BaseTSFeaturizer class BaseTemporalNormalizer(BaseTSFeaturizer): """ Base abstract class for creating normalized time feature...
0.94098
0.609117
import torch import torch.nn.functional as F from typing import Optional from core.modules import LayerNorm from core.modules import SepConv1d class VariancePredictor(torch.nn.Module): def __init__(self, idim: int, n_layers: int=2, n_chans: int=256, out: int=1, kernel_size: int=3, dropout_rate: f...
core/variance_predictor.py
import torch import torch.nn.functional as F from typing import Optional from core.modules import LayerNorm from core.modules import SepConv1d class VariancePredictor(torch.nn.Module): def __init__(self, idim: int, n_layers: int=2, n_chans: int=256, out: int=1, kernel_size: int=3, dropout_rate: f...
0.951278
0.544801
from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed from django.db.models.signals import post_save, post_delete, m2m_changed from django.dispatch import receiver from .models import ExpectedVariable, MapItem, Runner, Playbook, PlaybookItem, PlaybookMapping, Map, AuditEntry @rec...
django-backend/app/signals.py
from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed from django.db.models.signals import post_save, post_delete, m2m_changed from django.dispatch import receiver from .models import ExpectedVariable, MapItem, Runner, Playbook, PlaybookItem, PlaybookMapping, Map, AuditEntry @rec...
0.424531
0.065038
import os import glob import codecs import uuid import string import random import re def remove_substring(): with open ('out.txt', 'w', encoding = 'utf-8') as outfile: with open('in.txt', 'r') as infile: summ = 0 count = 0 for line in infile: line = line.split('acc')[1] line = line.split(',')[...
exp/easy_string_process.py
import os import glob import codecs import uuid import string import random import re def remove_substring(): with open ('out.txt', 'w', encoding = 'utf-8') as outfile: with open('in.txt', 'r') as infile: summ = 0 count = 0 for line in infile: line = line.split('acc')[1] line = line.split(',')[...
0.042167
0.116412
from diem import ( identifier, diem_types, stdlib, chain_ids, txnmetadata, utils, ) from diem.testing import create_client, Faucet, XUS import pytest, time, uuid @pytest.mark.asyncio async def test_p2p_under_threshold_by_subaddress(): client = create_client() faucet = Faucet(client) ...
examples/p2p_transfer.py
from diem import ( identifier, diem_types, stdlib, chain_ids, txnmetadata, utils, ) from diem.testing import create_client, Faucet, XUS import pytest, time, uuid @pytest.mark.asyncio async def test_p2p_under_threshold_by_subaddress(): client = create_client() faucet = Faucet(client) ...
0.555676
0.162546
from test.matcher import JSPECTestMatcher class JSPECTestMatcherArrayCapture(JSPECTestMatcher): """Class for testing the behaviour when using the ``match`` method for array captures. A JSPEC array capture will match a consecutive set of elements, which all match at least one of the elements in the arr...
test/matcher/arraycapture.py
from test.matcher import JSPECTestMatcher class JSPECTestMatcherArrayCapture(JSPECTestMatcher): """Class for testing the behaviour when using the ``match`` method for array captures. A JSPEC array capture will match a consecutive set of elements, which all match at least one of the elements in the arr...
0.83602
0.773986
# Standard lib import pathlib import unittest # Our own imports from deep_hipsc_tracking import utils from .. import helpers # Tests class TestIsNonemptyDir(helpers.FileSystemTestCase): def test_returns_false_for_empty_dirs(self): p1 = self.tempdir / 'foo' p1.mkdir() (p1 / '.hidden')....
tests/utils/test_pathdb.py
# Standard lib import pathlib import unittest # Our own imports from deep_hipsc_tracking import utils from .. import helpers # Tests class TestIsNonemptyDir(helpers.FileSystemTestCase): def test_returns_false_for_empty_dirs(self): p1 = self.tempdir / 'foo' p1.mkdir() (p1 / '.hidden')....
0.505859
0.355845
from bisect import bisect_right import random def argmin_dict(d): return min(d.items(), key=lambda x: x[1])[0] def add_tuples(tuple_a, tuple_b): """ :param tuple_a: ((int), (int)) :param tuple_b: ((int), (int)) :return: vector addition of tuple_a + tuple_b """ return tuple([x + y for x, ...
battleground/games/arena/util.py
from bisect import bisect_right import random def argmin_dict(d): return min(d.items(), key=lambda x: x[1])[0] def add_tuples(tuple_a, tuple_b): """ :param tuple_a: ((int), (int)) :param tuple_b: ((int), (int)) :return: vector addition of tuple_a + tuple_b """ return tuple([x + y for x, ...
0.779364
0.63542
from django.test import tag from test import cases as case from test import fixtures as data @tag('setaside') class SetAsideTest(case.APITestCase, metaclass = case.MetaAPISchema): fixtures = data.get_category_fixtures() schema = { 'object': { 'tags': ('setaside_object',), ...
app/api/tests/test_setaside.py
from django.test import tag from test import cases as case from test import fixtures as data @tag('setaside') class SetAsideTest(case.APITestCase, metaclass = case.MetaAPISchema): fixtures = data.get_category_fixtures() schema = { 'object': { 'tags': ('setaside_object',), ...
0.333178
0.22133
import pytest import asyncio from hat.drivers import tpkt @pytest.fixture def addr(unused_tcp_port): return tpkt.Address('127.0.0.1', unused_tcp_port) @pytest.mark.asyncio async def test_connect_listen(addr): conn1_future = asyncio.Future() srv = await tpkt.listen(lambda conn: conn1_future.set_result(c...
test_pytest/test_unit/test_drivers/test_tpkt.py
import pytest import asyncio from hat.drivers import tpkt @pytest.fixture def addr(unused_tcp_port): return tpkt.Address('127.0.0.1', unused_tcp_port) @pytest.mark.asyncio async def test_connect_listen(addr): conn1_future = asyncio.Future() srv = await tpkt.listen(lambda conn: conn1_future.set_result(c...
0.40157
0.583619
import logging from dataclasses import dataclass import pandas as pd import torch from torch import Tensor from zensols.deeplearn.layer import DeepLinear, DeepLinearNetworkSettings from zensols.deeplearn.model import BaseNetworkModule from zensols.deeplearn.batch import ( DataPoint, Batch, BatchFeatureMappi...
test/python/iris/model.py
import logging from dataclasses import dataclass import pandas as pd import torch from torch import Tensor from zensols.deeplearn.layer import DeepLinear, DeepLinearNetworkSettings from zensols.deeplearn.model import BaseNetworkModule from zensols.deeplearn.batch import ( DataPoint, Batch, BatchFeatureMappi...
0.863046
0.291781
import numpy as np from neuron import SimpleNeuron from helpers.diagnostic_helpers import time_measure class NeuralNetwork(object): def __init__(self, layer_size=[2, 2, 1], activation_function=None, activation_fun_prime=None): """ Default activation function: np.tanh(x) Default learning fun...
src/neural_networks.py
import numpy as np from neuron import SimpleNeuron from helpers.diagnostic_helpers import time_measure class NeuralNetwork(object): def __init__(self, layer_size=[2, 2, 1], activation_function=None, activation_fun_prime=None): """ Default activation function: np.tanh(x) Default learning fun...
0.772959
0.532851
from __future__ import absolute_import import struct import sys from .common import PY2, BytesIO, string_types if PY2: MAX_EXTRACT_VERSION = 63 from zipfile import ( BadZipfile as BadZipFile, ZipExtFile, ZipInfo, _CD_COMMENT_LENGTH, _CD_EXTRA_FIELD_LENGTH, _CD_...
Projects/Utilities/zippy/libs/zipfile.py
from __future__ import absolute_import import struct import sys from .common import PY2, BytesIO, string_types if PY2: MAX_EXTRACT_VERSION = 63 from zipfile import ( BadZipfile as BadZipFile, ZipExtFile, ZipInfo, _CD_COMMENT_LENGTH, _CD_EXTRA_FIELD_LENGTH, _CD_...
0.447702
0.107017
import numpy as np import cv2, os, collections from scipy.spatial import distance video = cv2.VideoCapture(0) hog_desc = cv2.HOGDescriptor() hog_list = [] # Fonction fancy pour montrer un histogram en couleur (mais vraiment inutile...) def show_histogram_color(frame): # Now create a histogram for the frame h...
project.py
import numpy as np import cv2, os, collections from scipy.spatial import distance video = cv2.VideoCapture(0) hog_desc = cv2.HOGDescriptor() hog_list = [] # Fonction fancy pour montrer un histogram en couleur (mais vraiment inutile...) def show_histogram_color(frame): # Now create a histogram for the frame h...
0.207817
0.486149
import argparse import logging import sys import time import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torchvision from torchvision import datasets, transforms import os from wideresnet import WideResNet from preactresnet i...
AT_AWP/ensemble_model.py
import argparse import logging import sys import time import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torchvision from torchvision import datasets, transforms import os from wideresnet import WideResNet from preactresnet i...
0.514888
0.245447
# Standard Library import datetime from typing import Any, Dict, Optional # Supercell Code from supercell.breezometer.models.base import BreezoMeterModel class AirQualityIndex(BreezoMeterModel): str_fmt = "{class_name} [{timestamp}]: {display_name} = {aqi_display} ({category}) !{dominant_pollutant}" short_na...
supercell/breezometer/air_quality/models/air_quality_index.py
# Standard Library import datetime from typing import Any, Dict, Optional # Supercell Code from supercell.breezometer.models.base import BreezoMeterModel class AirQualityIndex(BreezoMeterModel): str_fmt = "{class_name} [{timestamp}]: {display_name} = {aqi_display} ({category}) !{dominant_pollutant}" short_na...
0.821474
0.183758
import pytest import os import sys import numpy import librosa my_path = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, my_path + '/../') import dj_feet.song as song @pytest.fixture def no_process_base_song(random_song_file): yield song.Song(random_song_file, process=False) @pytest.fixture def ...
tests/test_songs.py
import pytest import os import sys import numpy import librosa my_path = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, my_path + '/../') import dj_feet.song as song @pytest.fixture def no_process_base_song(random_song_file): yield song.Song(random_song_file, process=False) @pytest.fixture def ...
0.41561
0.423637
from __future__ import absolute_import, print_function, unicode_literals from django.contrib.contenttypes.fields import GenericForeignKey, \ GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ from django_cou...
django_teledex/models.py
from __future__ import absolute_import, print_function, unicode_literals from django.contrib.contenttypes.fields import GenericForeignKey, \ GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ from django_cou...
0.407098
0.172869
import datetime import numpy import slycat.web.client import threading import time def generate_model(connection, pid, marking, index): def random_failure(probability): if numpy.random.uniform(0, 1) < probability: connection.update_model(mid, state="finished", result="failed", finished=datetime.datetime.u...
web-client/non-working-examples/slycat-demo-model-progress.py
import datetime import numpy import slycat.web.client import threading import time def generate_model(connection, pid, marking, index): def random_failure(probability): if numpy.random.uniform(0, 1) < probability: connection.update_model(mid, state="finished", result="failed", finished=datetime.datetime.u...
0.271831
0.129678
import numpy as np import pandas as pd from ..data import cat ifm_opr_ids = [ 'CAR1013', 'CAR1217', 'ACR210', 'ACR288', 'CAR973', 'ACR423', 'ACR281', 'ACR211', 'VCSOPR10', 'CAR1041', 'ACR273', 'ACR425', 'CAR1046', 'ACR280', 'ACR274', 'CAR1070', 'CAR1...
carbonplan_forest_offsets/load/issuance.py
import numpy as np import pandas as pd from ..data import cat ifm_opr_ids = [ 'CAR1013', 'CAR1217', 'ACR210', 'ACR288', 'CAR973', 'ACR423', 'ACR281', 'ACR211', 'VCSOPR10', 'CAR1041', 'ACR273', 'ACR425', 'CAR1046', 'ACR280', 'ACR274', 'CAR1070', 'CAR1...
0.55447
0.185523
import os import time import pickle from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions SLEEP_PAGE = 1 ATCODER_TOP_PAGE = r'https:/...
atcoderContestLoader.py
import os import time import pickle from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions SLEEP_PAGE = 1 ATCODER_TOP_PAGE = r'https:/...
0.163179
0.047536
from django.views.generic import TemplateView, View from django.http import Http404, HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.utils import timezone from django.contrib.staticfiles.templatetags.staticfiles import static from django.template.loader import get_template fr...
attendances/views.py
from django.views.generic import TemplateView, View from django.http import Http404, HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.utils import timezone from django.contrib.staticfiles.templatetags.staticfiles import static from django.template.loader import get_template fr...
0.544559
0.096238
from unittest import TestCase, mock from mycroft.util.process_utils import (_update_log_level, bus_logging_status, create_daemon, ProcessStatus, StatusCallbackMap) class TestCreateDaemon(TestCase): def test_create(self): """M...
test/unittests/util/test_process_utils.py
from unittest import TestCase, mock from mycroft.util.process_utils import (_update_log_level, bus_logging_status, create_daemon, ProcessStatus, StatusCallbackMap) class TestCreateDaemon(TestCase): def test_create(self): """M...
0.783823
0.373676
from future.standard_library import install_aliases install_aliases() from builtins import str import os import sys import csv import cssutils import re import requests from urllib.parse import urljoin from lxml import etree from lxml.cssselect import CSSSelector, ExpressionError _url_re = re.compile(r'''url\((['"]?...
inlinestyler/converter.py
from future.standard_library import install_aliases install_aliases() from builtins import str import os import sys import csv import cssutils import re import requests from urllib.parse import urljoin from lxml import etree from lxml.cssselect import CSSSelector, ExpressionError _url_re = re.compile(r'''url\((['"]?...
0.269806
0.07333
import logging from datetime import datetime import requests from stati_net.client import Client import hmac logger = logging.getLogger('stati') class HTTPClient(Client): """GottWall client to send data via """ def __init__(self, project, private_key, public_key, host='http://127.0.0.1...
stati_net/http.py
import logging from datetime import datetime import requests from stati_net.client import Client import hmac logger = logging.getLogger('stati') class HTTPClient(Client): """GottWall client to send data via """ def __init__(self, project, private_key, public_key, host='http://127.0.0.1...
0.638159
0.093885
import torch import os from collections import Counter class feature_lib: def __init__(self,cfg): self.feature_lib_path= cfg.FEATURELIB.PATH self.lib = self.load_lib() # size 2048*n self.lib_feature = self.lib['feature'] self.lib_label = self.lib['labels'] # 白米饭,...
food_detector/ground_feature.py
import torch import os from collections import Counter class feature_lib: def __init__(self,cfg): self.feature_lib_path= cfg.FEATURELIB.PATH self.lib = self.load_lib() # size 2048*n self.lib_feature = self.lib['feature'] self.lib_label = self.lib['labels'] # 白米饭,...
0.200088
0.117344
import os.path as osp from typing import List import mmcv import numpy as np from mmseg.datasets import DATASETS, CustomDataset from PIL import Image @DATASETS.register_module() class BDD100KSemSegDataset(CustomDataset): # type: ignore """BDD100K dataset for semantic segmentation.""" CLASSES = ( "...
sem_seg/datasets/bdd100k.py
import os.path as osp from typing import List import mmcv import numpy as np from mmseg.datasets import DATASETS, CustomDataset from PIL import Image @DATASETS.register_module() class BDD100KSemSegDataset(CustomDataset): # type: ignore """BDD100K dataset for semantic segmentation.""" CLASSES = ( "...
0.701611
0.424412
import re import os SEC_SETTINGS_DIR = 'web/src/delcien/sec_settings.py' def configure(): string = '' email = '' password = '' secretKey = '' emailRegex = r'[a-z,A-Z,.]+@[a-z,A-Z]+\.[a-z,A-Z,.]+[a-z,A-Z]+$' pattern = re.compile(emailRegex) while True: string = input('Enter an email account for the web page ...
configureWebPage.py
import re import os SEC_SETTINGS_DIR = 'web/src/delcien/sec_settings.py' def configure(): string = '' email = '' password = '' secretKey = '' emailRegex = r'[a-z,A-Z,.]+@[a-z,A-Z]+\.[a-z,A-Z,.]+[a-z,A-Z]+$' pattern = re.compile(emailRegex) while True: string = input('Enter an email account for the web page ...
0.053564
0.091544
import argparse from collections import defaultdict import json from nlp2go.cli import Cli from nlp2go.model import Model from nlp2go.server import Server import os os.environ["PYTHONIOENCODING"] = "utf-8" def parse_args(args): parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group(...
nlp2go/main.py
import argparse from collections import defaultdict import json from nlp2go.cli import Cli from nlp2go.model import Model from nlp2go.server import Server import os os.environ["PYTHONIOENCODING"] = "utf-8" def parse_args(args): parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group(...
0.442396
0.08389
import math import torch from tqdm import tqdm from torch.nn.functional import mse_loss, l1_loss from classifier import knn_classification from utils import Metric def train(args, classifier, dataloader, epoch, model, rotate, opt, rskel): model.train() feature, label = torch.empty(0), torch.empty(0) # ...
exec.py
import math import torch from tqdm import tqdm from torch.nn.functional import mse_loss, l1_loss from classifier import knn_classification from utils import Metric def train(args, classifier, dataloader, epoch, model, rotate, opt, rskel): model.train() feature, label = torch.empty(0), torch.empty(0) # ...
0.808786
0.456349
import logging import numpy as np from scipy import stats from minos import genotyper class GenotypeConfidenceSimulator: def __init__(self, mean_depth, depth_variance, error_rate, allele_length=1, iterations=10000): self.mean_depth = mean_depth self.depth_variance = depth_variance self.er...
minos/genotype_confidence_simulator.py
import logging import numpy as np from scipy import stats from minos import genotyper class GenotypeConfidenceSimulator: def __init__(self, mean_depth, depth_variance, error_rate, allele_length=1, iterations=10000): self.mean_depth = mean_depth self.depth_variance = depth_variance self.er...
0.659734
0.554531
from __future__ import absolute_import import nnabla as nn import nnabla.functions as F import nnabla.parametric_functions as PF from .helper import create_scale_bias, get_channel_axes # Small Channel First ResNet def cf_resblock(x, maps, kernel=(3, 3), pad=(1, 1), stride=(1, 1), test=False, channe...
python/test/utils/test_graph_converters/ref_graphs/resnets.py
from __future__ import absolute_import import nnabla as nn import nnabla.functions as F import nnabla.parametric_functions as PF from .helper import create_scale_bias, get_channel_axes # Small Channel First ResNet def cf_resblock(x, maps, kernel=(3, 3), pad=(1, 1), stride=(1, 1), test=False, channe...
0.883337
0.319957
from catboost import CatBoostClassifier, Pool from sklearn.model_selection import train_test_split from detector import Preprocess as pp from sklearn.metrics import roc_auc_score, accuracy_score import sys class CatBoostModel: def __init__(self): self._preprocess = pp.Preprocess() self._model = C...
detector/CatBoostModel.py
from catboost import CatBoostClassifier, Pool from sklearn.model_selection import train_test_split from detector import Preprocess as pp from sklearn.metrics import roc_auc_score, accuracy_score import sys class CatBoostModel: def __init__(self): self._preprocess = pp.Preprocess() self._model = C...
0.752013
0.265547
from math import trunc from re import L import lightbulb import random import hikari import wikipedia import requests import asyncio from hikari.colors import Color import datetime as dt from datetime import datetime, time, timedelta from wikipedia import exceptions from wikipedia.wikipedia import languages plugin ...
testbot/bot/extensions/fun.py
from math import trunc from re import L import lightbulb import random import hikari import wikipedia import requests import asyncio from hikari.colors import Color import datetime as dt from datetime import datetime, time, timedelta from wikipedia import exceptions from wikipedia.wikipedia import languages plugin ...
0.491944
0.317426
import numpy as np from scipy import interpolate __all__ = ["Material"] transmission_data = { "silica": np.array( [ [200, 87.428395], [201, 87.777818], [202, 88.083302], [203, 88.344465], [204, 88.634732], [205, 88.901925], ...
raosi/core/material.py
import numpy as np from scipy import interpolate __all__ = ["Material"] transmission_data = { "silica": np.array( [ [200, 87.428395], [201, 87.777818], [202, 88.083302], [203, 88.344465], [204, 88.634732], [205, 88.901925], ...
0.277571
0.417628
import io import os import platform import research PlatformName = platform.system() PlansPath = 'plans/' OutputPath = 'output/' markdown_output = OutputPath+"output.md" word_output = OutputPath+"output.docx" def md_gen(plan_file): print("Generating Markdown file...") plan = io.open(PlansPath+plan_file, "r",...
main.py
import io import os import platform import research PlatformName = platform.system() PlansPath = 'plans/' OutputPath = 'output/' markdown_output = OutputPath+"output.md" word_output = OutputPath+"output.docx" def md_gen(plan_file): print("Generating Markdown file...") plan = io.open(PlansPath+plan_file, "r",...
0.068347
0.162679
import datetime import logging import re import time import prettytable import requests from pyradiator.common import ColoredString from pyradiator.common import get_authenticator LOGGER = logging.getLogger(__name__) CURRENT_BUILD = 0 LAST_BUILD = 1 COLOR_MAP = { "UNSTABLE": (255, 255, 0), "FAILURE": (255,...
pyradiator/content_providers/ask_jenkins_jobs_status.py
import datetime import logging import re import time import prettytable import requests from pyradiator.common import ColoredString from pyradiator.common import get_authenticator LOGGER = logging.getLogger(__name__) CURRENT_BUILD = 0 LAST_BUILD = 1 COLOR_MAP = { "UNSTABLE": (255, 255, 0), "FAILURE": (255,...
0.364438
0.069289
from statue.cli import statue_cli from statue.command import Command from statue.constants import STANDARD from statue.context import Context from tests.constants import ( COMMAND1, COMMAND2, COMMAND_HELP_STRING1, COMMAND_HELP_STRING2, CONTEXT1, CONTEXT2, CONTEXT3, CONTEXT4, CONTEXT5...
tests/cli/test_context_cli.py
from statue.cli import statue_cli from statue.command import Command from statue.constants import STANDARD from statue.context import Context from tests.constants import ( COMMAND1, COMMAND2, COMMAND_HELP_STRING1, COMMAND_HELP_STRING2, CONTEXT1, CONTEXT2, CONTEXT3, CONTEXT4, CONTEXT5...
0.461259
0.314235
import unittest import os import shutil import numpy as np from sklearn.decomposition import PCA from pylipid.func import collect_bound_poses, vectorize_poses, write_bound_poses from pylipid.func import cluster_DBSCAN, cluster_KMeans from pylipid import LipidInteraction class TestCluster(unittest.TestCase): def s...
tests/funcs/test_clusterer.py
import unittest import os import shutil import numpy as np from sklearn.decomposition import PCA from pylipid.func import collect_bound_poses, vectorize_poses, write_bound_poses from pylipid.func import cluster_DBSCAN, cluster_KMeans from pylipid import LipidInteraction class TestCluster(unittest.TestCase): def s...
0.438064
0.273496
import itertools import os import sys import geopandas as gpd import pandas as pd from shapely.geometry import Polygon from atra.utils import * from atra.transport_flow_and_failure_functions import * from tqdm import tqdm def create_hazard_attributes_for_network(intersection_dir,climate_scenario,year,sector,hazard_f...
src/atra/analysis/hazards_network_intersections_results_collect.py
import itertools import os import sys import geopandas as gpd import pandas as pd from shapely.geometry import Polygon from atra.utils import * from atra.transport_flow_and_failure_functions import * from tqdm import tqdm def create_hazard_attributes_for_network(intersection_dir,climate_scenario,year,sector,hazard_f...
0.544075
0.353121
from zigpy.profiles import zha from zigpy.quirks import CustomDevice from zigpy.zcl.clusters.general import Basic, LevelControl, MultistateInput, OnOff, Ota from zhaquirks import CustomCluster, PowerConfigurationCluster from zhaquirks.const import ( COMMAND, COMMAND_DOUBLE, COMMAND_HOLD, COMMAND_RELEAS...
zhaquirks/thirdreality/button.py
from zigpy.profiles import zha from zigpy.quirks import CustomDevice from zigpy.zcl.clusters.general import Basic, LevelControl, MultistateInput, OnOff, Ota from zhaquirks import CustomCluster, PowerConfigurationCluster from zhaquirks.const import ( COMMAND, COMMAND_DOUBLE, COMMAND_HOLD, COMMAND_RELEAS...
0.698021
0.123709
from calm.ex import DefinitionError, ArgumentParseError class ArgumentParser(object): """ Extensible default parser for request arguments (path, query). When specifying request arguments (path, query) types via annotations, an instance of this class (or subclass) is used to parse the argument val...
calm/codec.py
from calm.ex import DefinitionError, ArgumentParseError class ArgumentParser(object): """ Extensible default parser for request arguments (path, query). When specifying request arguments (path, query) types via annotations, an instance of this class (or subclass) is used to parse the argument val...
0.91488
0.442637
import torch import torch.nn as nn import torch.nn.functional as F from functools import reduce from base.base_model import BaseModel from .backbones import mobilenetv2 from .backbones import resnet class DecoderBlock(nn.Module): def __init__(self, in_channels, out_channels, block_unit): super(DecoderBlock, self)....
models/unet.py
import torch import torch.nn as nn import torch.nn.functional as F from functools import reduce from base.base_model import BaseModel from .backbones import mobilenetv2 from .backbones import resnet class DecoderBlock(nn.Module): def __init__(self, in_channels, out_channels, block_unit): super(DecoderBlock, self)....
0.753965
0.295154
import os import time import requests import ujson as json from dotenv import load_dotenv from apscheduler.schedulers.asyncio import AsyncIOScheduler from discord.ext import commands from dhooks import Webhook, Embed, File from utils.global_utils import news_exists, matches_exists load_dotenv() vlr_news_webhook = os.g...
cogs/vlr_news.py
import os import time import requests import ujson as json from dotenv import load_dotenv from apscheduler.schedulers.asyncio import AsyncIOScheduler from discord.ext import commands from dhooks import Webhook, Embed, File from utils.global_utils import news_exists, matches_exists load_dotenv() vlr_news_webhook = os.g...
0.349755
0.06767
from pathlib import Path from denite.base.filter import Base DEFAULT_ICON = '' DIR_ICON = '' FILENAMES = { '.bash_profile': '', '.bashrc': '', '.gitignore': '', '.vimrc': '', 'dockerfile': '', 'license': '', } EXTENSIONS = { '.bash': '', '.bat': '', '.c': '', '.cc': ...
vim/rplugin/python3/denite/filter/converter/devicons.py
from pathlib import Path from denite.base.filter import Base DEFAULT_ICON = '' DIR_ICON = '' FILENAMES = { '.bash_profile': '', '.bashrc': '', '.gitignore': '', '.vimrc': '', 'dockerfile': '', 'license': '', } EXTENSIONS = { '.bash': '', '.bat': '', '.c': '', '.cc': ...
0.579995
0.229578
from app import db # Vamos criar abaixo uma classe, onde poderemos criar usuários apartir dela class User(db.Model): '''db.Model é uma classe do sqlalchemy, que traz um modelo de tabela padrão''' __tablename__ = "users" # users será o nome da minha tabela id = db.Column(db.Interger, primary_key=True) ...
Aula_flask/app/models/tables.py
from app import db # Vamos criar abaixo uma classe, onde poderemos criar usuários apartir dela class User(db.Model): '''db.Model é uma classe do sqlalchemy, que traz um modelo de tabela padrão''' __tablename__ = "users" # users será o nome da minha tabela id = db.Column(db.Interger, primary_key=True) ...
0.413359
0.107719
import pytest from todolist.core.accounts.entities.user import User from todolist.core.accounts.protocols import UserRepo from todolist.core.accounts.services import hash_service, user_service from todolist.core.accounts.services.exceptions import ( EmailNotUniqueError, UserNotFoundError, ) @pytest.fixture()...
tests/unit/core/accounts/services/user_service_test.py
import pytest from todolist.core.accounts.entities.user import User from todolist.core.accounts.protocols import UserRepo from todolist.core.accounts.services import hash_service, user_service from todolist.core.accounts.services.exceptions import ( EmailNotUniqueError, UserNotFoundError, ) @pytest.fixture()...
0.442637
0.349449
import json from .base import (BaseStorage, NotFound, BaseDocumentBucket, BaseBlobBucket, BaseKeyvalBucket) class BaseMemoryBucket(object): bucket_type = None # to be overwritten in subclasses def __init__(self, *a, **kw): super(BaseMemoryBucket, self).__init__(*a, **kw) ...
harvester/ext/storage/memory.py
import json from .base import (BaseStorage, NotFound, BaseDocumentBucket, BaseBlobBucket, BaseKeyvalBucket) class BaseMemoryBucket(object): bucket_type = None # to be overwritten in subclasses def __init__(self, *a, **kw): super(BaseMemoryBucket, self).__init__(*a, **kw) ...
0.531696
0.076718
import random from datetime import datetime import pytz import requests from base.views import log from bs4 import BeautifulSoup from django.contrib.auth.decorators import login_required from django.shortcuts import redirect, render # Create your views here. def projects(request): log(request, 'Projects') p...
projects/views.py
import random from datetime import datetime import pytz import requests from base.views import log from bs4 import BeautifulSoup from django.contrib.auth.decorators import login_required from django.shortcuts import redirect, render # Create your views here. def projects(request): log(request, 'Projects') p...
0.326271
0.179782
import sys import json import argparse import pytorch_pretrained_bert sys.path.append('.') from scripts.data_convert.text_proc import SpacyTextParser from scripts.data_convert.convert_common import STOPWORD_FILE, BERT_TOK_OPT_HELP, BERT_TOK_OPT, \ FileWrapper, readStopWords, addRetokenizedField from scripts.confi...
scripts/data_convert/msmarco_adhoc/convert_queries.py
import sys import json import argparse import pytorch_pretrained_bert sys.path.append('.') from scripts.data_convert.text_proc import SpacyTextParser from scripts.data_convert.convert_common import STOPWORD_FILE, BERT_TOK_OPT_HELP, BERT_TOK_OPT, \ FileWrapper, readStopWords, addRetokenizedField from scripts.confi...
0.209066
0.079926
"Code to make variable references plots" import os import shutil import webbrowser from collections import defaultdict # pylint:disable=too-many-locals def referencesplot(model, *, openimmediately=True): """Makes a references plot. 1) Creates the JSON file for a d3 references plot 2) Places it and the c...
gpkit/interactive/references.py
"Code to make variable references plots" import os import shutil import webbrowser from collections import defaultdict # pylint:disable=too-many-locals def referencesplot(model, *, openimmediately=True): """Makes a references plot. 1) Creates the JSON file for a d3 references plot 2) Places it and the c...
0.491212
0.224927
from collections import deque # 羊 狼 船 羊 狼 船 initial_state = [3, 3, 1, 0, 0, 0] # 初始状态 final_state = [0, 0, 0, 3, 3, 1] # 最终状态 action = [[0, -1, 0], [0, -2, 0], [-1, 0, 0], [-2, 0, 0], [-1, -1, 0], [0, 1, 1], [0, 2, 1], [1, 0, 1], [2, 0, 1], [1, 1, 1]] # 利用python的deque队列记录状态转移情况,初始化时加入初始状态。deque是可以从头尾插入和删...
DLS/DLS_WandS_2.py
from collections import deque # 羊 狼 船 羊 狼 船 initial_state = [3, 3, 1, 0, 0, 0] # 初始状态 final_state = [0, 0, 0, 3, 3, 1] # 最终状态 action = [[0, -1, 0], [0, -2, 0], [-1, 0, 0], [-2, 0, 0], [-1, -1, 0], [0, 1, 1], [0, 2, 1], [1, 0, 1], [2, 0, 1], [1, 1, 1]] # 利用python的deque队列记录状态转移情况,初始化时加入初始状态。deque是可以从头尾插入和删...
0.223377
0.593668
import logging import itertools import struct import socket import time # Packet types SERVERDATA_AUTH = 3 SERVERDATA_AUTH_RESPONSE = 2 SERVERDATA_EXECCOMMAND = 2 SERVERDATA_RESPONSE_VALUE = 0 __all__ = ['RCONPacket', 'RCONConnection'] rcon_log = logging.getLogger('rcon_lib') class RCONPacket: def __init__(sel...
geeksbot_web/rcon/rcon_lib/rcon.py
import logging import itertools import struct import socket import time # Packet types SERVERDATA_AUTH = 3 SERVERDATA_AUTH_RESPONSE = 2 SERVERDATA_EXECCOMMAND = 2 SERVERDATA_RESPONSE_VALUE = 0 __all__ = ['RCONPacket', 'RCONConnection'] rcon_log = logging.getLogger('rcon_lib') class RCONPacket: def __init__(sel...
0.560734
0.096877
from pytextgears import TextGear from .utils import * import os #API_KEY = os.environ['PYTEXTGEARS_KEY'] def return_error_list(raw_json): '''Return all json in the error list individually Args: raw_json (dict): Raw JSON output from grammar checker Return error_list (list): List of JSON dicts '''...
pytextgears/json_parser.py
from pytextgears import TextGear from .utils import * import os #API_KEY = os.environ['PYTEXTGEARS_KEY'] def return_error_list(raw_json): '''Return all json in the error list individually Args: raw_json (dict): Raw JSON output from grammar checker Return error_list (list): List of JSON dicts '''...
0.673192
0.265035
from .entry_point import EntryPoint from core.entity.corefacility_module import CorefacilityModule class SynchronizationsEntryPoint(EntryPoint): """ Allows to attach different kinds of synchronizations and select an appropriate one """ _is_parent_module_root = True """ The property is used during...
corefacility/core/entity/entry_points/synchronizations.py
from .entry_point import EntryPoint from core.entity.corefacility_module import CorefacilityModule class SynchronizationsEntryPoint(EntryPoint): """ Allows to attach different kinds of synchronizations and select an appropriate one """ _is_parent_module_root = True """ The property is used during...
0.833155
0.378
from jmessage import * from jmessage import url import json class Group(object): def __init__(self,jmessage): self.jmessage=jmessage; def build_group(self, owner_username=None, name=None, members_username=None, desc=None): group = {} if owner_username is not None: group["own...
jmessage/groups/groups.py
from jmessage import * from jmessage import url import json class Group(object): def __init__(self,jmessage): self.jmessage=jmessage; def build_group(self, owner_username=None, name=None, members_username=None, desc=None): group = {} if owner_username is not None: group["own...
0.067724
0.035344
from sikuli import Finder from org.sikuli.android import ADBScreen from org.sikuli.android import ADBDevice from pprint import pprint as pp import json from glob import glob from os.path import join, splitext, basename, relpath tmpdir = join(getBundlePath(), "screencap") base_img = join(getBundlePath(), "..", "img", "...
create-img-dict.sikuli/create-img-dict.py
from sikuli import Finder from org.sikuli.android import ADBScreen from org.sikuli.android import ADBDevice from pprint import pprint as pp import json from glob import glob from os.path import join, splitext, basename, relpath tmpdir = join(getBundlePath(), "screencap") base_img = join(getBundlePath(), "..", "img", "...
0.159774
0.094052
import random import click from torchvision import ops as tvops from ... import datautils, utils from ...defaults import GROZI_ROOT @click.group() def grozi(): ''' Commands for GroZi-120 dataset. This command group contains commands for visualizing various aspects of the GroZi-120 dataset (Merler et al....
cvpce/cli/datasets/grozi.py
import random import click from torchvision import ops as tvops from ... import datautils, utils from ...defaults import GROZI_ROOT @click.group() def grozi(): ''' Commands for GroZi-120 dataset. This command group contains commands for visualizing various aspects of the GroZi-120 dataset (Merler et al....
0.263505
0.352508
import pandas as pd import math import matplotlib.pyplot as plt import numpy as np # COMMAND ---------- # MAGIC %md # MAGIC #REGRESSION MODEL NOTES # MAGIC ## We Can Conduct a few different version of this regression model by changing the dependent and independent variables # MAGIC **Dependent Variable** # MAGIC We c...
codeSheets/SEAS6401/PGAProject/Regression_Analysis.py
import pandas as pd import math import matplotlib.pyplot as plt import numpy as np # COMMAND ---------- # MAGIC %md # MAGIC #REGRESSION MODEL NOTES # MAGIC ## We Can Conduct a few different version of this regression model by changing the dependent and independent variables # MAGIC **Dependent Variable** # MAGIC We c...
0.581778
0.6195
from __future__ import print_function class Cursor(object): def __init__(self, method, *args, **kwargs): self.iterator = PageIterator(method, args, kwargs) def pages(self, limit=0): if limit > 0: self.iterator.limit = limit return self.iterator def items(self, limit=0...
pixiv/cursor.py
from __future__ import print_function class Cursor(object): def __init__(self, method, *args, **kwargs): self.iterator = PageIterator(method, args, kwargs) def pages(self, limit=0): if limit > 0: self.iterator.limit = limit return self.iterator def items(self, limit=0...
0.617167
0.08163
"""Classes to represent inputs/outputs/parameters in a Plan.""" import copy import urllib from abc import abstractmethod from pathlib import PurePosixPath from typing import Any, List, Optional from uuid import uuid4 from renku.core.errors import ParameterError from renku.core.utils.urls import get_slug RANDOM_ID_LE...
renku/core/models/workflow/parameter.py
"""Classes to represent inputs/outputs/parameters in a Plan.""" import copy import urllib from abc import abstractmethod from pathlib import PurePosixPath from typing import Any, List, Optional from uuid import uuid4 from renku.core.errors import ParameterError from renku.core.utils.urls import get_slug RANDOM_ID_LE...
0.931678
0.257753
import flatbuffers from .. import DeferredLightInfo from .. import DeferredLightResolve from .. import DeferredShadowLightInfo class Object: pass def convertDeferredLightResolve(convertContext, data): """ Converts a DeferredLightResolve. The data map is expected to contain the following elements: - lightSet: nam...
python/DeepSeaSceneLighting/Convert/DeferredLightResolveConvert.py
import flatbuffers from .. import DeferredLightInfo from .. import DeferredLightResolve from .. import DeferredShadowLightInfo class Object: pass def convertDeferredLightResolve(convertContext, data): """ Converts a DeferredLightResolve. The data map is expected to contain the following elements: - lightSet: nam...
0.486088
0.584805
from django.http import JsonResponse, HttpResponse, HttpResponseBadRequest from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import get_user_model from django.utils import timezone from todolist.models import Post, TEXT_MAX_LENGTH from todolist.serializers import post_serializer from todoli...
todolist/views.py
from django.http import JsonResponse, HttpResponse, HttpResponseBadRequest from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import get_user_model from django.utils import timezone from todolist.models import Post, TEXT_MAX_LENGTH from todolist.serializers import post_serializer from todoli...
0.658308
0.090213
import importlib import pathlib import shutil import sys import tempfile import textwrap import unittest from ops.charm import ( CharmBase, ) from ops.framework import ( Object, ) from ops.model import ( ModelError, ) from ops.testing import Harness class TestHarness(unittest.TestCase): def test_ad...
test/test_testing.py
import importlib import pathlib import shutil import sys import tempfile import textwrap import unittest from ops.charm import ( CharmBase, ) from ops.framework import ( Object, ) from ops.model import ( ModelError, ) from ops.testing import Harness class TestHarness(unittest.TestCase): def test_ad...
0.385259
0.161849
import argparse import sys import helpers def preprocess_argv(): # Remove script from argv argv = sys.argv[1:] if len(argv): command_abbreviations = { 'l': 'list', 'u': 'update', 'n': 'new', 'd': 'delete', 'p': 'periods' } ...
cli.py
import argparse import sys import helpers def preprocess_argv(): # Remove script from argv argv = sys.argv[1:] if len(argv): command_abbreviations = { 'l': 'list', 'u': 'update', 'n': 'new', 'd': 'delete', 'p': 'periods' } ...
0.362969
0.072308
import math import re import sys from voussoirkit import pipeable def hms_to_seconds(hms) -> float: ''' Convert hh:mm:ss string to an integer or float of seconds. ''' parts = hms.split(':') seconds = 0 if len(parts) > 3: raise ValueError(f'{hms} doesn\'t match the HH:MM:SS format.') ...
voussoirkit/hms.py
import math import re import sys from voussoirkit import pipeable def hms_to_seconds(hms) -> float: ''' Convert hh:mm:ss string to an integer or float of seconds. ''' parts = hms.split(':') seconds = 0 if len(parts) > 3: raise ValueError(f'{hms} doesn\'t match the HH:MM:SS format.') ...
0.345657
0.445771
import itertools import logging import math from copy import deepcopy import numpy as np import pandas as pd from scipy.ndimage.filters import uniform_filter1d import basty.utils.misc as misc np.seterr(all="ignore") class SpatioTemporal: def __init__(self, fps, stft_cfg={}): self.stft_cfg = deepcopy(st...
basty/feature_extraction/spatiotemporal_features.py
import itertools import logging import math from copy import deepcopy import numpy as np import pandas as pd from scipy.ndimage.filters import uniform_filter1d import basty.utils.misc as misc np.seterr(all="ignore") class SpatioTemporal: def __init__(self, fps, stft_cfg={}): self.stft_cfg = deepcopy(st...
0.692954
0.335623
import datetime import unittest from dawa_facade import DawaFacade import requests_mock import os.path import os from dawa_facade.responses.replication.street import StreetEvent, StreetData class StreetTestCase(unittest.TestCase): """ :type facade: DawaFacade """ facade = None @classmethod de...
dawa_facade/tests/replication/test_streets.py
import datetime import unittest from dawa_facade import DawaFacade import requests_mock import os.path import os from dawa_facade.responses.replication.street import StreetEvent, StreetData class StreetTestCase(unittest.TestCase): """ :type facade: DawaFacade """ facade = None @classmethod de...
0.648132
0.320409
import itertools from oslo_service import service as os_service from oslo_utils import importutils as utils from vitrage.common.constants import UpdateMethod from vitrage.common.utils import opt_exists from vitrage.datasources.listener_service import ListenerService from vitrage.datasources.services import ChangesSe...
vitrage/datasources/launcher.py
import itertools from oslo_service import service as os_service from oslo_utils import importutils as utils from vitrage.common.constants import UpdateMethod from vitrage.common.utils import opt_exists from vitrage.datasources.listener_service import ListenerService from vitrage.datasources.services import ChangesSe...
0.448909
0.091018
import collections import json import numpy as np import pandas as pd import sklearn def cv_results_to_df(cv_results): """ Convert a `sklearn.grid_search.GridSearchCV.cv_results_` attribute to a tidy pandas DataFrame where each row is a hyperparameter combinatination. """ cv_results_df = pd.DataFr...
cognoml/utils.py
import collections import json import numpy as np import pandas as pd import sklearn def cv_results_to_df(cv_results): """ Convert a `sklearn.grid_search.GridSearchCV.cv_results_` attribute to a tidy pandas DataFrame where each row is a hyperparameter combinatination. """ cv_results_df = pd.DataFr...
0.793346
0.530966
import re import os from shutil import copy2 import subprocess from time import time_ns from pathlib import Path def time_add_sub(time0, time1, sub=False): time0 = list(map(int, time0.split(':'))) time1 = list(map(int, time1.split(':'))) time0 = time0[0] * 3600 + time0[1] * 60 + time0[2] time1 = time1...
connect-dl.py
import re import os from shutil import copy2 import subprocess from time import time_ns from pathlib import Path def time_add_sub(time0, time1, sub=False): time0 = list(map(int, time0.split(':'))) time1 = list(map(int, time1.split(':'))) time0 = time0[0] * 3600 + time0[1] * 60 + time0[2] time1 = time1...
0.100508
0.13681
import unittest import cellyzer.core as core import cellyzer.io as io class TestCallMessageDataSet(unittest.TestCase): @classmethod def setUpClass(cls): # before all the tests cls.user1 = "3e97992791" cls.user2 = "265034e175" cls.user3 = '329233d117' cls.callDataSet =...
tests/unit_tests/test_CallMessageDataSet.py
import unittest import cellyzer.core as core import cellyzer.io as io class TestCallMessageDataSet(unittest.TestCase): @classmethod def setUpClass(cls): # before all the tests cls.user1 = "3e97992791" cls.user2 = "265034e175" cls.user3 = '329233d117' cls.callDataSet =...
0.461259
0.321114
__author__ = '<EMAIL> (<NAME>)' import httplib2 import os import unittest import urlparse try: from urlparse import parse_qs except ImportError: from cgi import parse_qs from apiclient.discovery import build, key2param from apiclient.http import HttpMock from apiclient.http import tunnel_patch from apiclient....
client/tests/test_discovery.py
__author__ = '<EMAIL> (<NAME>)' import httplib2 import os import unittest import urlparse try: from urlparse import parse_qs except ImportError: from cgi import parse_qs from apiclient.discovery import build, key2param from apiclient.http import HttpMock from apiclient.http import tunnel_patch from apiclient....
0.437343
0.327507
from flask import render_template, request, redirect, url_for, flash from app.src.utils import get_end_path, get_dir_up, get_clean_path from app.src.utils import get_content_dir, get_pages, is_file from app.src.format import imgs_type_file from . import views @views.route('/storage/<path:path>', methods=['GET', 'POS...
app/views/storage.py
from flask import render_template, request, redirect, url_for, flash from app.src.utils import get_end_path, get_dir_up, get_clean_path from app.src.utils import get_content_dir, get_pages, is_file from app.src.format import imgs_type_file from . import views @views.route('/storage/<path:path>', methods=['GET', 'POS...
0.363308
0.082623
import engine.db_structure as db_py import os filename = "transaction.vdb" if os.path.isfile(filename): os.remove(filename) db = db_py.Database(False, filename) db.create_table("vadik_table", {"zhenya1": "int", "zhenya2": "str"}) def test_transaction(): id = db.tables[0].start_transaction() db.tables[0]....
engine_tests/transaction_journal_tests.py
import engine.db_structure as db_py import os filename = "transaction.vdb" if os.path.isfile(filename): os.remove(filename) db = db_py.Database(False, filename) db.create_table("vadik_table", {"zhenya1": "int", "zhenya2": "str"}) def test_transaction(): id = db.tables[0].start_transaction() db.tables[0]....
0.311427
0.192482
from textwrap import dedent import unittest from unittest import TestCase from heconvert.converter import * class TestKSX5002(TestCase): def test_all(self): # h2e test self.assertEqual('rsef', h2e('ㄱㄴㄷㄹ')) self.assertEqual('kiju', h2e('ㅏㅑㅓㅕ')) self.assertEqual('0123', h2e('0123'))...
test/tests.py
from textwrap import dedent import unittest from unittest import TestCase from heconvert.converter import * class TestKSX5002(TestCase): def test_all(self): # h2e test self.assertEqual('rsef', h2e('ㄱㄴㄷㄹ')) self.assertEqual('kiju', h2e('ㅏㅑㅓㅕ')) self.assertEqual('0123', h2e('0123'))...
0.354768
0.353958
import requests import json import os import sys import yaml from urlparse import urlparse from docopt import docopt config = docopt(__doc__) session_key = '' session_val = '' session_token = '' host = config['--host'] or 'http://datacatalog.worldbank.org' i = urlparse(host) if not i.netloc and not i.path: rais...
dev/ddh-test.py
import requests import json import os import sys import yaml from urlparse import urlparse from docopt import docopt config = docopt(__doc__) session_key = '' session_val = '' session_token = '' host = config['--host'] or 'http://datacatalog.worldbank.org' i = urlparse(host) if not i.netloc and not i.path: rais...
0.126704
0.047316
import io import cv2 import base64 import numpy as np from PIL import Image from os.path import dirname, join import tensorflow as tf from alibi.explainers import AnchorImage """ 模型解释(改用 alibi ) pip install alibi alibi 没有针对image regression问题的解释逻辑 """ # Load TFLite model and allocate tensors. model_file = join(dirname...
App/beauty/app/src/main/assets/python/report_lite_alibi.py
import io import cv2 import base64 import numpy as np from PIL import Image from os.path import dirname, join import tensorflow as tf from alibi.explainers import AnchorImage """ 模型解释(改用 alibi ) pip install alibi alibi 没有针对image regression问题的解释逻辑 """ # Load TFLite model and allocate tensors. model_file = join(dirname...
0.601125
0.312658
import re from yom.errors import * from yom.constants import scopes, fields class YomValidator(object): is_valid = False def validate(self): is_valid = self._validate() self.is_valid = is_valid return is_valid def cleaned_data(self): if not self.is_valid: rai...
yom/validators.py
import re from yom.errors import * from yom.constants import scopes, fields class YomValidator(object): is_valid = False def validate(self): is_valid = self._validate() self.is_valid = is_valid return is_valid def cleaned_data(self): if not self.is_valid: rai...
0.674908
0.201479
import numpy as np from masp import shoebox_room_sim as srs import time import soundfile as sf import os # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # SETUP # Room definition from baseline.cls_feature_class import create_folder room = np.array([10.2, 7.1, 3.2]) # Desired RT p...
APRI/generate_irs.py
import numpy as np from masp import shoebox_room_sim as srs import time import soundfile as sf import os # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # SETUP # Room definition from baseline.cls_feature_class import create_folder room = np.array([10.2, 7.1, 3.2]) # Desired RT p...
0.303216
0.238595