code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import unittest
from app import create_app, db
from app.businesses.models import Category
from app.config import TestingConfig
from app.consts import MESSAGE_ENTITY_NOT_FOUND
class CategoryTestCase(unittest.TestCase):
"""This class represents the category test case"""
def setUp(self):
"""Define test... | tests/test_api_category.py | import unittest
from app import create_app, db
from app.businesses.models import Category
from app.config import TestingConfig
from app.consts import MESSAGE_ENTITY_NOT_FOUND
class CategoryTestCase(unittest.TestCase):
"""This class represents the category test case"""
def setUp(self):
"""Define test... | 0.685318 | 0.244126 |
import math
import numpy as np
from tqdm import tqdm
import seaborn as sns
import pandas as pd
from subprocess import call
import matplotlib.pyplot as plt
from pushestpy.utils import utils
plt.rcParams.update({'font.size': 36})
def wrap_to_pi(arr):
arr_wrap = (arr + math.pi) % (2 * math.pi) - math.pi
ret... | push_estimation/pushestpy/src/pushestpy/eval/quant_plotter.py |
import math
import numpy as np
from tqdm import tqdm
import seaborn as sns
import pandas as pd
from subprocess import call
import matplotlib.pyplot as plt
from pushestpy.utils import utils
plt.rcParams.update({'font.size': 36})
def wrap_to_pi(arr):
arr_wrap = (arr + math.pi) % (2 * math.pi) - math.pi
ret... | 0.479747 | 0.341775 |
import os
import pdb
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
from configs.defaults import get_cfg_defaults
from datasets.Ego4DKeyframeLocalisation import Ego4DKeyframeLocalisation
from torch.utils.data import DataLoader
from models.video_model_builder im... | state-change-localization-classification/bmn/Ego4D_keyframe_localisation/misc/train.py | import os
import pdb
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
from configs.defaults import get_cfg_defaults
from datasets.Ego4DKeyframeLocalisation import Ego4DKeyframeLocalisation
from torch.utils.data import DataLoader
from models.video_model_builder im... | 0.728652 | 0.287468 |
import os
import sys
sys.path.append('./_model')
from env import *
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--env', help='Specifies which environment to run.', required=True)
parser.add_argument(
'--engine',
help='NN backend to use',
default='OneDNN',
required=False)
pars... | examples/study.cases/openspiel/run-dvracer.py | import os
import sys
sys.path.append('./_model')
from env import *
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--env', help='Specifies which environment to run.', required=True)
parser.add_argument(
'--engine',
help='NN backend to use',
default='OneDNN',
required=False)
pars... | 0.457137 | 0.165728 |
Code adapted from https://github.com/r1ch88/SlowFastNetworks."""
# pylint: disable=line-too-long,too-many-lines,missing-docstring,arguments-differ,unused-argument
__all__ = ['SlowFast', 'slowfast_4x16_resnet50_kinetics400', 'slowfast_8x8_resnet50_kinetics400',
'slowfast_4x16_resnet101_kinetics400', 'slowfas... | gluoncv/model_zoo/action_recognition/slowfast.py | Code adapted from https://github.com/r1ch88/SlowFastNetworks."""
# pylint: disable=line-too-long,too-many-lines,missing-docstring,arguments-differ,unused-argument
__all__ = ['SlowFast', 'slowfast_4x16_resnet50_kinetics400', 'slowfast_8x8_resnet50_kinetics400',
'slowfast_4x16_resnet101_kinetics400', 'slowfas... | 0.954308 | 0.435241 |
from flask import Blueprint, request
from ..auth import admin_only, authenticate, get_current_user
from ..exceptions import ApiException, Unauthorized
from ..result import ApiResult
from ..models import Plan, User, db
from ..schemas import UserSchema
from .plans import plans_schema, plan_schema
bp = Blueprint("users"... | api/controllers/users.py | from flask import Blueprint, request
from ..auth import admin_only, authenticate, get_current_user
from ..exceptions import ApiException, Unauthorized
from ..result import ApiResult
from ..models import Plan, User, db
from ..schemas import UserSchema
from .plans import plans_schema, plan_schema
bp = Blueprint("users"... | 0.393269 | 0.057098 |
import json
import logging
from datetime import date
# Django Imports
from django.conf import settings
from django.test import TestCase
from django.utils import dateformat
# 3rd Party Libraries
from rest_framework.renderers import JSONRenderer
# Ghostwriter Libraries
from ghostwriter.factories import GenerateMockPro... | ghostwriter/reporting/tests/test_serializers.py | import json
import logging
from datetime import date
# Django Imports
from django.conf import settings
from django.test import TestCase
from django.utils import dateformat
# 3rd Party Libraries
from rest_framework.renderers import JSONRenderer
# Ghostwriter Libraries
from ghostwriter.factories import GenerateMockPro... | 0.513912 | 0.254387 |
import argparse
import sys
from collections import defaultdict
from presig import presig as ps
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input",
help="A MAF file (or MAF-like file)", required=True, dest="maf")
parser.add_argument("-s", "--signatures",
... | label_ssv_with_sig.py | import argparse
import sys
from collections import defaultdict
from presig import presig as ps
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input",
help="A MAF file (or MAF-like file)", required=True, dest="maf")
parser.add_argument("-s", "--signatures",
... | 0.354098 | 0.344278 |
import asyncio
import json
import logging
import requests
import scrypted_sdk
from scrypted_sdk import ScryptedDeviceBase
from scrypted_sdk.types import Settings, DeviceProvider, DeviceDiscovery, ScryptedInterface, ScryptedDeviceType
from .arlo import Arlo
from .arlo.logging import logger as arlo_lib_logger
from .cam... | plugins/arlo/src/arlo_plugin/provider.py | import asyncio
import json
import logging
import requests
import scrypted_sdk
from scrypted_sdk import ScryptedDeviceBase
from scrypted_sdk.types import Settings, DeviceProvider, DeviceDiscovery, ScryptedInterface, ScryptedDeviceType
from .arlo import Arlo
from .arlo.logging import logger as arlo_lib_logger
from .cam... | 0.59843 | 0.095181 |
import torch
import torchani
import unittest
import os
import pickle
import math
import random
path = os.path.dirname(os.path.realpath(__file__))
N = 97
class TestEnergies(unittest.TestCase):
def setUp(self):
self.tolerance = 5e-5
builtins = torchani.neurochem.Builtins()
self.aev_comput... | tests/test_energies.py | import torch
import torchani
import unittest
import os
import pickle
import math
import random
path = os.path.dirname(os.path.realpath(__file__))
N = 97
class TestEnergies(unittest.TestCase):
def setUp(self):
self.tolerance = 5e-5
builtins = torchani.neurochem.Builtins()
self.aev_comput... | 0.720073 | 0.556159 |
from abc import ABC
from msal import ConfidentialClientApplication
from .app_credentials import AppCredentials
class CertificateAppCredentials(AppCredentials, ABC):
"""
AppCredentials implementation using a certificate.
See:
https://github.com/AzureAD/microsoft-authentication-library-for-python/wi... | samples/python/13.core-bot/envs/chat_bot_02/Lib/site-packages/botframework/connector/auth/certificate_app_credentials.py |
from abc import ABC
from msal import ConfidentialClientApplication
from .app_credentials import AppCredentials
class CertificateAppCredentials(AppCredentials, ABC):
"""
AppCredentials implementation using a certificate.
See:
https://github.com/AzureAD/microsoft-authentication-library-for-python/wi... | 0.844521 | 0.133528 |
from typing import Callable, Optional
import numpy as np
from ._typing import NDArray
def phi1D(
x: NDArray,
B: NDArray,
fun: Callable[[NDArray], NDArray],
) -> NDArray:
"""
The function phi1D is called by phi2D.
It aims at applying a function ``fun`` after multiplying each row
of B by x... | mapie/aggregation_functions.py | from typing import Callable, Optional
import numpy as np
from ._typing import NDArray
def phi1D(
x: NDArray,
B: NDArray,
fun: Callable[[NDArray], NDArray],
) -> NDArray:
"""
The function phi1D is called by phi2D.
It aims at applying a function ``fun`` after multiplying each row
of B by x... | 0.947076 | 0.826677 |
import re
import unittest
from scrubadub.filth import Filth, MergedFilth
from scrubadub.exceptions import InvalidReplaceWith, FilthMergeError
class FilthTestCase(unittest.TestCase):
def test_disallowed_replace_with(self):
"""replace_with should fail gracefully"""
filth = Filth()
with self... | tests/test_filth.py | import re
import unittest
from scrubadub.filth import Filth, MergedFilth
from scrubadub.exceptions import InvalidReplaceWith, FilthMergeError
class FilthTestCase(unittest.TestCase):
def test_disallowed_replace_with(self):
"""replace_with should fail gracefully"""
filth = Filth()
with self... | 0.66072 | 0.380673 |
from unittest.mock import patch
import pytest
from fibratus.apidefs.sys import STD_OUTPUT_HANDLE, GENERIC_READ, GENERIC_WRITE, \
FILE_SHARE_READ, CONSOLE_TEXTMODE_BUFFER, FILE_SHARE_WRITE, INVALID_HANDLE_VALUE, COORD, SMALL_RECT, CHAR_INFO, \
CONSOLE_SCREEN_BUFFER_INFO
from fibratus.errors import TermInitiali... | tests/unit/term.py | from unittest.mock import patch
import pytest
from fibratus.apidefs.sys import STD_OUTPUT_HANDLE, GENERIC_READ, GENERIC_WRITE, \
FILE_SHARE_READ, CONSOLE_TEXTMODE_BUFFER, FILE_SHARE_WRITE, INVALID_HANDLE_VALUE, COORD, SMALL_RECT, CHAR_INFO, \
CONSOLE_SCREEN_BUFFER_INFO
from fibratus.errors import TermInitiali... | 0.345878 | 0.188287 |
from turtle import color
import numpy as numpy
from mpl_toolkits.mplot3d import Axes3D
import matplotlib as matplotlib
import matplotlib.pyplot as pyplot
from matplotlib import gridspec
from algorithm.peeling import peeling_to_structure
from algorithm.fuzzy import samples_to_fuzzy_projection
FONTSIZE = 22
FIGSIZE = ... | algorithm/plots.py | from turtle import color
import numpy as numpy
from mpl_toolkits.mplot3d import Axes3D
import matplotlib as matplotlib
import matplotlib.pyplot as pyplot
from matplotlib import gridspec
from algorithm.peeling import peeling_to_structure
from algorithm.fuzzy import samples_to_fuzzy_projection
FONTSIZE = 22
FIGSIZE = ... | 0.425128 | 0.379148 |
import six
from oslo_utils import excutils
from dcorch.common.i18n import _
class OrchestratorException(Exception):
"""Base Orchestrator Exception.
To correctly use this class, inherit from it and define
a 'message' property. That message will get printf'd
with the keyword arguments provided to the... | dcorch/common/exceptions.py | import six
from oslo_utils import excutils
from dcorch.common.i18n import _
class OrchestratorException(Exception):
"""Base Orchestrator Exception.
To correctly use this class, inherit from it and define
a 'message' property. That message will get printf'd
with the keyword arguments provided to the... | 0.505371 | 0.078607 |
from PIL import Image
# DO NOT SEE HERE! IT WORKED!
class MatrixSunday:
__image_src = None
__image_dst = None
def de_scramble(self, path_src: str, path_dst: str, data: list):
self.__image_src = Image.open(path_src, 'r')
self.__process(data)
self.__image_dst.save(path_dst)
... | manga_py/crypt/sunday_webry_com.py | from PIL import Image
# DO NOT SEE HERE! IT WORKED!
class MatrixSunday:
__image_src = None
__image_dst = None
def de_scramble(self, path_src: str, path_dst: str, data: list):
self.__image_src = Image.open(path_src, 'r')
self.__process(data)
self.__image_dst.save(path_dst)
... | 0.385143 | 0.294177 |
import time
from pathlib import Path
import colorcet as cc
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.feature_selection import VarianceThreshold
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import... | experiments/genes/gene_connectome_mv.py | import time
from pathlib import Path
import colorcet as cc
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.feature_selection import VarianceThreshold
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import... | 0.355216 | 0.362236 |
import magma as m
ARRAY2 = m.Array[2, m.Bit]
ARRAY4 = m.Array[4, m.Bit]
def test_bits_basic():
"""
Basic bits tests
"""
bits_2 = m.Bits[2]
bits_in_2 = m.In(m.Bits[2])
bits_out_2 = m.Out(m.Bits[2])
assert bits_2 == m.Bits[2]
assert bits_in_2 == m.In(bits_2)
assert bits_out_2 == m.O... | tests/test_type/test_bits.py | import magma as m
ARRAY2 = m.Array[2, m.Bit]
ARRAY4 = m.Array[4, m.Bit]
def test_bits_basic():
"""
Basic bits tests
"""
bits_2 = m.Bits[2]
bits_in_2 = m.In(m.Bits[2])
bits_out_2 = m.Out(m.Bits[2])
assert bits_2 == m.Bits[2]
assert bits_in_2 == m.In(bits_2)
assert bits_out_2 == m.O... | 0.591369 | 0.858125 |
import os
import queue
import threading
from tkinter import *
from tkinter import ttk
import tkinter.tix as tix
from dao.db2_dao import DB2Dao
from dao.db_source_dao import DBSourceDao
from dao.mysql_dao import MysqlDao
from dao.output_config_dao import OutputConfigDao
from ui.win_config import ConfigWindow
from ui.win... | MybatisGeneratorGUI/ui/win_table_choice.py | import os
import queue
import threading
from tkinter import *
from tkinter import ttk
import tkinter.tix as tix
from dao.db2_dao import DB2Dao
from dao.db_source_dao import DBSourceDao
from dao.mysql_dao import MysqlDao
from dao.output_config_dao import OutputConfigDao
from ui.win_config import ConfigWindow
from ui.win... | 0.262653 | 0.068506 |
from __future__ import unicode_literals
import unittest
from datetime import datetime, date
from dateutil.tz import tzutc
from soql import attributes
from soql import NullSalesforceColumnError
from soql import Model
class RelatedModel(Model):
id = attributes.Integer('Id')
class RelationshipTest(unittest.TestC... | tests/test_attributes.py | from __future__ import unicode_literals
import unittest
from datetime import datetime, date
from dateutil.tz import tzutc
from soql import attributes
from soql import NullSalesforceColumnError
from soql import Model
class RelatedModel(Model):
id = attributes.Integer('Id')
class RelationshipTest(unittest.TestC... | 0.719581 | 0.404743 |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views import View
from django.contrib import messages
from django.contrib.auth import login, authenticate, logout
from django.db import transaction, IntegrityError
from core.forms.forms import CustomUserCreationForm, PersonF... | escalate/core/views/login.py | from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views import View
from django.contrib import messages
from django.contrib.auth import login, authenticate, logout
from django.db import transaction, IntegrityError
from core.forms.forms import CustomUserCreationForm, PersonF... | 0.474631 | 0.048361 |
import asyncio
import base64
import io
import json
import queue
import re
import tarfile
from abc import abstractmethod
from concurrent.futures.thread import ThreadPoolExecutor
from os.path import basename
from typing import List, Dict, Callable, Union
from urllib.parse import urlparse
import docker
impo... | cincanregistry/remotes/_remote_registry.py | import asyncio
import base64
import io
import json
import queue
import re
import tarfile
from abc import abstractmethod
from concurrent.futures.thread import ThreadPoolExecutor
from os.path import basename
from typing import List, Dict, Callable, Union
from urllib.parse import urlparse
import docker
impo... | 0.572842 | 0.071397 |
import pytest
from unittest.mock import Mock, patch
import pandas as pd
from gretel_client.client import get_cloud_client, Client
from gretel_client import projects
from gretel_client.projects import Project
@pytest.fixture()
def client():
return get_cloud_client("api", "<KEY>")
def test_iter_records(client: ... | tests/src/gretel_client/unit/test_projects.py | import pytest
from unittest.mock import Mock, patch
import pandas as pd
from gretel_client.client import get_cloud_client, Client
from gretel_client import projects
from gretel_client.projects import Project
@pytest.fixture()
def client():
return get_cloud_client("api", "<KEY>")
def test_iter_records(client: ... | 0.475118 | 0.44903 |
from typing import Any, Callable, Dict, Generic, List, Optional, Type, TypeVar
from ordered_set import OrderedSet
from pydantic import ValidationError
from pydantic.main import BaseModel
T = TypeVar("T", bound=BaseModel)
class BaseInstantiableUnion(Generic[T]):
_base: Type[T]
_members: OrderedSet[Type[T]]
... | packman/utils/union.py | from typing import Any, Callable, Dict, Generic, List, Optional, Type, TypeVar
from ordered_set import OrderedSet
from pydantic import ValidationError
from pydantic.main import BaseModel
T = TypeVar("T", bound=BaseModel)
class BaseInstantiableUnion(Generic[T]):
_base: Type[T]
_members: OrderedSet[Type[T]]
... | 0.758421 | 0.286868 |
import sys, getopt,re
def red_depth(wigfile,step):
fr_wig = [r1.strip().split("\t") for r1 in open(wigfile).readlines()]
nw=len(fr_wig);wg_dict={}
for pw in range(nw):
par=fr_wig[pw][0]
if wg_dict.has_key(par):
wg_dict[par].append(fr_wig[pw])
else:
wg_dict[p... | pipeline/prepare_GROseq_data.py |
import sys, getopt,re
def red_depth(wigfile,step):
fr_wig = [r1.strip().split("\t") for r1 in open(wigfile).readlines()]
nw=len(fr_wig);wg_dict={}
for pw in range(nw):
par=fr_wig[pw][0]
if wg_dict.has_key(par):
wg_dict[par].append(fr_wig[pw])
else:
wg_dict[p... | 0.143008 | 0.267378 |
import argparse
import numpy as np
import pickle
import random
import os
from ogb.lsc import MAG240MDataset
from collections import defaultdict
from cleora import train_cleora
from tqdm import tqdm
from coders import get_vcoder
from root import ROOT
def get_parser():
parser = argparse.ArgumentParser()
parser.... | src/compute_institutions_sketches.py | import argparse
import numpy as np
import pickle
import random
import os
from ogb.lsc import MAG240MDataset
from collections import defaultdict
from cleora import train_cleora
from tqdm import tqdm
from coders import get_vcoder
from root import ROOT
def get_parser():
parser = argparse.ArgumentParser()
parser.... | 0.359477 | 0.117724 |
import os
import boto3, json
from datastore import PipelineOpsStore
from helper import AwsHelper, SQSHelper
PIPELINE_OPS_TABLE = os.environ.get("PIPELINE_OPS_TABLE", None)
SQS_QUEUE_ARN = os.environ.get("SQS_QUEUE_ARN", None)
if not PIPELINE_OPS_TABLE or not SQS_QUEUE_ARN:
raise ValueError("Missing arguments."... | code/metadata/pipeline.py | import os
import boto3, json
from datastore import PipelineOpsStore
from helper import AwsHelper, SQSHelper
PIPELINE_OPS_TABLE = os.environ.get("PIPELINE_OPS_TABLE", None)
SQS_QUEUE_ARN = os.environ.get("SQS_QUEUE_ARN", None)
if not PIPELINE_OPS_TABLE or not SQS_QUEUE_ARN:
raise ValueError("Missing arguments."... | 0.202759 | 0.121087 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | lib/pymedphys/_experimental/chartchecks/helpers.py |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | 0.813609 | 0.507873 |
import scrapy
import re
import os
import urllib
import pymysql
import sys
from scrapy.selector import Selector
from scrapy.http import HtmlResponse, Request
from webCrawler_scrapy.items import LrldSpiderItem
class LrldSpider(scrapy.spiders.Spider):
name = 'lrld'
allowed_domains = ["bnu.edu.cn"]
start_urls... | webCrawler_scrapy/spiders/lrldSpider.py | import scrapy
import re
import os
import urllib
import pymysql
import sys
from scrapy.selector import Selector
from scrapy.http import HtmlResponse, Request
from webCrawler_scrapy.items import LrldSpiderItem
class LrldSpider(scrapy.spiders.Spider):
name = 'lrld'
allowed_domains = ["bnu.edu.cn"]
start_urls... | 0.064957 | 0.096877 |
import os
import random
import json
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.template.loader import render_to_string
import pdfkit
def generate_pattern_sets():
source = os.path.join(settings.BASE_DIR, 'core', 'static', 'patterns', 'pattern_sourc... | application/core/management/commands/generate_fill_pattern1.py | import os
import random
import json
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.template.loader import render_to_string
import pdfkit
def generate_pattern_sets():
source = os.path.join(settings.BASE_DIR, 'core', 'static', 'patterns', 'pattern_sourc... | 0.181046 | 0.14814 |
# type: ignore
from importlib import reload
from logging import ERROR
from os import environ
from unittest import TestCase
from unittest.mock import Mock, patch
from opentelemetry import trace
from opentelemetry.baggage.propagation import W3CBaggagePropagator
from opentelemetry.context.context import Context
from op... | opentelemetry-api/tests/propagators/test_propagators.py |
# type: ignore
from importlib import reload
from logging import ERROR
from os import environ
from unittest import TestCase
from unittest.mock import Mock, patch
from opentelemetry import trace
from opentelemetry.baggage.propagation import W3CBaggagePropagator
from opentelemetry.context.context import Context
from op... | 0.73659 | 0.409221 |
from cleo import Command
import os
import shutil
import zipfile
from ..exceptions import ProjectLimitReached
class NewCommand(Command):
"""
Creates a new Masonite project
new
{name? : Name of your Masonite project}
{target? : Path of you Masonite project}
{--b|--branch=False : Spe... | src/masonite/commands/NewCommand.py | from cleo import Command
import os
import shutil
import zipfile
from ..exceptions import ProjectLimitReached
class NewCommand(Command):
"""
Creates a new Masonite project
new
{name? : Name of your Masonite project}
{target? : Path of you Masonite project}
{--b|--branch=False : Spe... | 0.401805 | 0.105073 |
import boto3
from kines import constants, date_util
import click
from terminaltables import SingleTable
import base64
from textwrap import wrap
import time
UTF_8 = "utf-8"
WAIT_FOR_SECONDS = 2
def walk(
stream_name,
shard_id,
sequence_number=None,
get_records_limit=5,
follow=False,
latest=Fal... | kines/read_util.py | import boto3
from kines import constants, date_util
import click
from terminaltables import SingleTable
import base64
from textwrap import wrap
import time
UTF_8 = "utf-8"
WAIT_FOR_SECONDS = 2
def walk(
stream_name,
shard_id,
sequence_number=None,
get_records_limit=5,
follow=False,
latest=Fal... | 0.286868 | 0.122839 |
from django.conf.urls import url, include
from django.views.generic.base import TemplateView, RedirectView
from django.conf import settings
import xgds_core.views as views
urlpatterns = [url(r'^update_session', views.update_session, {}, 'update_session'),
url(r'^update_cookie', views.update_cookie, {}... | xgds_core/urls.py |
from django.conf.urls import url, include
from django.views.generic.base import TemplateView, RedirectView
from django.conf import settings
import xgds_core.views as views
urlpatterns = [url(r'^update_session', views.update_session, {}, 'update_session'),
url(r'^update_cookie', views.update_cookie, {}... | 0.371251 | 0.112405 |
import argparse
import os
from typing import Any, Dict, List, Tuple
import multiprocessing as mp
import tqdm
import pandas as pd
import numpy as np
import scipy.interpolate
from tensorboard.backend.event_processing import event_accumulator
def interpolation(df: pd.DataFrame, total_epoch: int) -> pd.DataFrame:
s... | tools/read_tb.py | import argparse
import os
from typing import Any, Dict, List, Tuple
import multiprocessing as mp
import tqdm
import pandas as pd
import numpy as np
import scipy.interpolate
from tensorboard.backend.event_processing import event_accumulator
def interpolation(df: pd.DataFrame, total_epoch: int) -> pd.DataFrame:
s... | 0.611498 | 0.126111 |
from unittest import TestCase, mock
from mbed_tools.targets.get_target import get_target_by_board_type, get_target_by_name
from mbed_tools.targets.exceptions import TargetError
from mbed_tools.targets._internal.target_attributes import TargetAttributesError
class TestGetTarget(TestCase):
@mock.patch("mbed_tools.t... | tests/targets/test_get_target.py | from unittest import TestCase, mock
from mbed_tools.targets.get_target import get_target_by_board_type, get_target_by_name
from mbed_tools.targets.exceptions import TargetError
from mbed_tools.targets._internal.target_attributes import TargetAttributesError
class TestGetTarget(TestCase):
@mock.patch("mbed_tools.t... | 0.801858 | 0.285565 |
from django.db import IntegrityError
from django.test import TestCase
from forkit.tests.models import Author, Post, Blog, Tag
__all__ = ('ForkModelObjectTestCase',)
class ForkModelObjectTestCase(TestCase):
fixtures = ['test_data.json']
def setUp(self):
self.author = Author.objects.get(pk=1)
s... | forkit/tests/fork.py | from django.db import IntegrityError
from django.test import TestCase
from forkit.tests.models import Author, Post, Blog, Tag
__all__ = ('ForkModelObjectTestCase',)
class ForkModelObjectTestCase(TestCase):
fixtures = ['test_data.json']
def setUp(self):
self.author = Author.objects.get(pk=1)
s... | 0.490968 | 0.356951 |
import sys
import os
import csv
from absl import app
from absl import flags
from jax import random
from jax.api import grad
from jax.api import jit
from jax.experimental import optimizers
import jax.numpy as np
import numpy
import neural_tangents as nt
from neural_tangents import stax
from examples import datasets
from... | make_ntk.py | import sys
import os
import csv
from absl import app
from absl import flags
from jax import random
from jax.api import grad
from jax.api import jit
from jax.experimental import optimizers
import jax.numpy as np
import numpy
import neural_tangents as nt
from neural_tangents import stax
from examples import datasets
from... | 0.362292 | 0.250746 |
from collections import defaultdict, deque
import logging
from time import time, sleep
LOG = logging.getLogger(__name__)
class Collector(object):
"""
Collector continuously runs in the background and collects information
(usually from host_os) for later aggregation
"""
def __init__(self, interval... | zabby/hostos/collectors.py | from collections import defaultdict, deque
import logging
from time import time, sleep
LOG = logging.getLogger(__name__)
class Collector(object):
"""
Collector continuously runs in the background and collects information
(usually from host_os) for later aggregation
"""
def __init__(self, interval... | 0.797951 | 0.192615 |
import json
import os
from datapackage import Package
import pandas as pd
from oemof.tabular.datapackage import building
def add(buses, sensitivities, datapackage_dir):
"""
"""
commodities = {}
bus_elements = {}
bio_potential = (
Package(
"https://raw.githubusercontent.com/Z... | scripts/biomass.py | import json
import os
from datapackage import Package
import pandas as pd
from oemof.tabular.datapackage import building
def add(buses, sensitivities, datapackage_dir):
"""
"""
commodities = {}
bus_elements = {}
bio_potential = (
Package(
"https://raw.githubusercontent.com/Z... | 0.459076 | 0.294995 |
import numpy as np
from scipy.linalg import lu_factor, lu_solve
from .eq_tools import build_equations, get_rows, get_new_col, get_left_stability_idx, ftran2eta
#TODO: build method can further improved if we reuse all matricies - note LU factorization is slower if matrix is not contnignous
class time_equations():
... | SCLPsolver/subroutines/equation_tools/calc_equations.py |
import numpy as np
from scipy.linalg import lu_factor, lu_solve
from .eq_tools import build_equations, get_rows, get_new_col, get_left_stability_idx, ftran2eta
#TODO: build method can further improved if we reuse all matricies - note LU factorization is slower if matrix is not contnignous
class time_equations():
... | 0.208018 | 0.239083 |
import argparse, cv2, time, os, subprocess, json
from argparse import RawTextHelpFormatter
from prettytable import PrettyTable
import numpy as np
import matplotlib.pyplot as plt
def separator():
print('-----------------------------------------------------------------------------------------------------------')
sep... | video-metrics.py | import argparse, cv2, time, os, subprocess, json
from argparse import RawTextHelpFormatter
from prettytable import PrettyTable
import numpy as np
import matplotlib.pyplot as plt
def separator():
print('-----------------------------------------------------------------------------------------------------------')
sep... | 0.464416 | 0.297036 |
USER_CREATED_SUCCESSFULLY = "User Created Successfully"
ADMIN_CREATED_SUCCESSFULLY = "Admin Created Successfully"
ADMIN_LOGGEDIN_SUCCESSFULLY = 'Admin Loggedin Successfully'
INCORRECT_PASSWORD = '<PASSWORD>'
INCORRECT_EMAIL = 'Incorrect Email'
PROFILE_PIC_IS_REQUIRED = "Profile Pic Is Required"
VALIDATION_COMPLETED = "... | mongodb_tryndx-master/constants/messages.py | USER_CREATED_SUCCESSFULLY = "User Created Successfully"
ADMIN_CREATED_SUCCESSFULLY = "Admin Created Successfully"
ADMIN_LOGGEDIN_SUCCESSFULLY = 'Admin Loggedin Successfully'
INCORRECT_PASSWORD = '<PASSWORD>'
INCORRECT_EMAIL = 'Incorrect Email'
PROFILE_PIC_IS_REQUIRED = "Profile Pic Is Required"
VALIDATION_COMPLETED = "... | 0.156266 | 0.03138 |
import datetime
from collections import defaultdict
from typing import TYPE_CHECKING, Dict, Iterator, List, Optional, Set, Tuple
from django.contrib.auth.base_user import AbstractBaseUser
from django.db import models
from django.db.models import Q, QuerySet
from django.utils.timezone import now
from paikkala.excs imp... | paikkala/models/programs.py | import datetime
from collections import defaultdict
from typing import TYPE_CHECKING, Dict, Iterator, List, Optional, Set, Tuple
from django.contrib.auth.base_user import AbstractBaseUser
from django.db import models
from django.db.models import Q, QuerySet
from django.utils.timezone import now
from paikkala.excs imp... | 0.878184 | 0.193986 |
from xml.etree import ElementTree
from dimagi.utils.couch.database import get_db
from casexml.apps.case.models import CommCareCase
from corehq.apps.commtrack import const
from corehq.apps.commtrack.models import (
CommtrackConfig, CommtrackActionConfig, LocationType, RequisitionActions,
CommtrackRequisitionConf... | corehq/apps/commtrack/util.py | from xml.etree import ElementTree
from dimagi.utils.couch.database import get_db
from casexml.apps.case.models import CommCareCase
from corehq.apps.commtrack import const
from corehq.apps.commtrack.models import (
CommtrackConfig, CommtrackActionConfig, LocationType, RequisitionActions,
CommtrackRequisitionConf... | 0.485356 | 0.199327 |
from django.db import models
from django.urls import reverse
from django.conf import settings
class Team(models.Model):
date = models.DateField()
duty = models.JSONField(blank=True, null=True)
def __str__(self):
return self.date
class Event(models.Model):
user = models.ForeignKey(settings.AU... | duties/models.py | from django.db import models
from django.urls import reverse
from django.conf import settings
class Team(models.Model):
date = models.DateField()
duty = models.JSONField(blank=True, null=True)
def __str__(self):
return self.date
class Event(models.Model):
user = models.ForeignKey(settings.AU... | 0.582254 | 0.424889 |
import grpc
import google.protobuf.empty_pb2 as google_dot_protobuf_dot_empty__pb2
import pysolveengine.svc_jobs_pb2 as svc__jobs__pb2
class JobStub(object):
"""A service for creating new jobs with the solveEngine
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
... | pysolveengine/svc_jobs_pb2_grpc.py | import grpc
import google.protobuf.empty_pb2 as google_dot_protobuf_dot_empty__pb2
import pysolveengine.svc_jobs_pb2 as svc__jobs__pb2
class JobStub(object):
"""A service for creating new jobs with the solveEngine
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
... | 0.598782 | 0.040541 |
import pytest
from ...product.models import ProductType
from ..utils import associate_attribute_values_to_instance
def test_associate_attribute_to_non_product_instance(color_attribute):
instance = ProductType()
attribute = color_attribute
value = color_attribute.values.first()
with pytest.raises(Ass... | saleor/attribute/tests/test_utils.py | import pytest
from ...product.models import ProductType
from ..utils import associate_attribute_values_to_instance
def test_associate_attribute_to_non_product_instance(color_attribute):
instance = ProductType()
attribute = color_attribute
value = color_attribute.values.first()
with pytest.raises(Ass... | 0.870652 | 0.759671 |
__author__ = "<NAME> <<EMAIL>>"
import logging
import Queue
import threading
import time
from osstrends.database import MongoDatabase
from osstrends.github import GitHubSearcher, RateLimitException
from osstrends.locations import load_locations
logger = logging.getLogger(__name__)
class DataPipeline(object):
... | osstrends/pipeline.py |
__author__ = "<NAME> <<EMAIL>>"
import logging
import Queue
import threading
import time
from osstrends.database import MongoDatabase
from osstrends.github import GitHubSearcher, RateLimitException
from osstrends.locations import load_locations
logger = logging.getLogger(__name__)
class DataPipeline(object):
... | 0.573917 | 0.127952 |
from datetime import date, datetime, timedelta
import typing
class Defendant:
def __init__(self, first:str, last:str, birthdate):
'''This takes three arguments: a firstname, lastname, and birthdate.
The names should be non-zero-length strings without whitespace. The
birthdate
shou... | src/defendant.py | from datetime import date, datetime, timedelta
import typing
class Defendant:
def __init__(self, first:str, last:str, birthdate):
'''This takes three arguments: a firstname, lastname, and birthdate.
The names should be non-zero-length strings without whitespace. The
birthdate
shou... | 0.856272 | 0.470615 |
import pprint
import re # noqa: F401
import six
from simscale_sdk.configuration import Configuration
class WindConditions(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
open... | simscale_sdk/models/wind_conditions.py | import pprint
import re # noqa: F401
import six
from simscale_sdk.configuration import Configuration
class WindConditions(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
open... | 0.732592 | 0.283781 |
from __future__ import absolute_import
from profiling import sortkeys
from profiling.profiler import Profiler
from profiling.sampling.samplers import ItimerSampler, Sampler
from profiling.stats import (
RecordingStatistics, VoidRecordingStatistics as void)
from profiling.viewer import fmt, StatisticsTable
__all_... | profiling/sampling/__init__.py | from __future__ import absolute_import
from profiling import sortkeys
from profiling.profiler import Profiler
from profiling.sampling.samplers import ItimerSampler, Sampler
from profiling.stats import (
RecordingStatistics, VoidRecordingStatistics as void)
from profiling.viewer import fmt, StatisticsTable
__all_... | 0.840717 | 0.206474 |
import re
from collections import deque
from functools import wraps
from stacker.errors import StackerSyntaxError
from stacker.scope import Scope
__all__ = ['Stacker', 'Procedure']
class Procedure (object):
def __init__(self, inp, name, scope):
self.inp = inp
self.name = name
self.scope... | stacker/lang.py | import re
from collections import deque
from functools import wraps
from stacker.errors import StackerSyntaxError
from stacker.scope import Scope
__all__ = ['Stacker', 'Procedure']
class Procedure (object):
def __init__(self, inp, name, scope):
self.inp = inp
self.name = name
self.scope... | 0.566858 | 0.152442 |
from flask import Flask, request, session, url_for
from flask_cors import CORS
from flask_principal import Principal, identity_loaded, RoleNeed
from werkzeug.utils import redirect
from requests_toolbelt.adapters import appengine
from google.appengine.ext import ndb
from user.model import User
appengine.monkeypatch()
... | python/main.py | from flask import Flask, request, session, url_for
from flask_cors import CORS
from flask_principal import Principal, identity_loaded, RoleNeed
from werkzeug.utils import redirect
from requests_toolbelt.adapters import appengine
from google.appengine.ext import ndb
from user.model import User
appengine.monkeypatch()
... | 0.327776 | 0.040788 |
import os
import logging
class CommandCheck(object):
def __init__(self, options=None, parser=None, config_data=None, io_handler=None):
self.options = options
self.parser = parser
self.data = config_data
self.io_handle = io_handler
def login(self):
if 'aws' not in self... | libs/command_checker.py |
import os
import logging
class CommandCheck(object):
def __init__(self, options=None, parser=None, config_data=None, io_handler=None):
self.options = options
self.parser = parser
self.data = config_data
self.io_handle = io_handler
def login(self):
if 'aws' not in self... | 0.261237 | 0.054727 |
import numpy as np
from pygsti.baseobjs.label import Label
from pygsti.circuits.circuit import Circuit
from pygsti.modelmembers.operations import ComposedOp, EmbeddedOp
from pygsti.models.localnoisemodel import LocalNoiseModel
from pygsti.models.modelconstruction import create_crosstalk_free_model
from pygsti.processo... | test/unit/objects/test_localnoisemodel.py | import numpy as np
from pygsti.baseobjs.label import Label
from pygsti.circuits.circuit import Circuit
from pygsti.modelmembers.operations import ComposedOp, EmbeddedOp
from pygsti.models.localnoisemodel import LocalNoiseModel
from pygsti.models.modelconstruction import create_crosstalk_free_model
from pygsti.processo... | 0.621541 | 0.527742 |
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
from omfit_classes import omfit_eqdsk, omfit_gapy
import scipy,sys,os
import time
from scipy.interpolate import interp1d
plt.style.use('/home/sciortino/SPARC/sparc_plots.mplstyle')
# Make sure that package home is added to sys.path
sys.path.append('../')
impo... | examples/test_FSA.py | import numpy as np
import matplotlib.pyplot as plt
plt.ion()
from omfit_classes import omfit_eqdsk, omfit_gapy
import scipy,sys,os
import time
from scipy.interpolate import interp1d
plt.style.use('/home/sciortino/SPARC/sparc_plots.mplstyle')
# Make sure that package home is added to sys.path
sys.path.append('../')
impo... | 0.508056 | 0.339882 |
import random
message_len = 64
half_message_len = 32
string_len = 48
character_len = 8
rounds = 16
key_len = 56
sbox1 = [[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
[0, 15, 7, 4, 14,2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
[4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
[15, 12, 8... | DESAlgorithm.py | import random
message_len = 64
half_message_len = 32
string_len = 48
character_len = 8
rounds = 16
key_len = 56
sbox1 = [[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
[0, 15, 7, 4, 14,2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
[4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
[15, 12, 8... | 0.232571 | 0.348146 |
__all__ = ('main')
import sys
import os
import tempfile
import argparse
if __name__ == '__main__' and not getattr(sys, 'frozen', False):
_rp = os.environ.get('RAYPATH')
if not _rp:
print('No RAYPATH, unable to find support library'); sys.exit(-1)
for _p in _rp.split(os.path.pathsep):
if os.path.isdir(os.path.jo... | scripts/phisto.py | __all__ = ('main')
import sys
import os
import tempfile
import argparse
if __name__ == '__main__' and not getattr(sys, 'frozen', False):
_rp = os.environ.get('RAYPATH')
if not _rp:
print('No RAYPATH, unable to find support library'); sys.exit(-1)
for _p in _rp.split(os.path.pathsep):
if os.path.isdir(os.path.jo... | 0.085227 | 0.085901 |
import tkinter as tk
from PIL import Image, ImageTk
import numpy as np
class CutPlaneViewer(tk.Frame):
def __init__(self,master,img,row,col,plusCallback=None,minusCallback=None):
self._defaultSize=256
self._defaultHeight = 1
tk.Frame.__init__(self,master)
self.grid(row=row,... | CutPlaneViewer.py | import tkinter as tk
from PIL import Image, ImageTk
import numpy as np
class CutPlaneViewer(tk.Frame):
def __init__(self,master,img,row,col,plusCallback=None,minusCallback=None):
self._defaultSize=256
self._defaultHeight = 1
tk.Frame.__init__(self,master)
self.grid(row=row,... | 0.349533 | 0.102934 |
import csv
import sys
import warnings
from pprint import pprint
from statistics import mean, stdev
# Import the official evaluation scripts
sys.path.append('data/deft_corpus/evaluation/program')
from evaluation_sub1 import get_gold_and_pred_labels as task1_get_labels
from evaluation_sub1 import evaluate as task1_evalu... | defx/util/official_evaluation.py | import csv
import sys
import warnings
from pprint import pprint
from statistics import mean, stdev
# Import the official evaluation scripts
sys.path.append('data/deft_corpus/evaluation/program')
from evaluation_sub1 import get_gold_and_pred_labels as task1_get_labels
from evaluation_sub1 import evaluate as task1_evalu... | 0.4856 | 0.269641 |
from __future__ import division
from builtins import dict
from Bio import SeqIO
import os
import sys
import gzip
import pickle
import random
import logging
import numpy as np
from shutil import copyfileobj
def phred_to_prob(q):
"""Convert a phred score (Sanger or modern Illumina) in probabilty
Given a ph... | iss/util.py |
from __future__ import division
from builtins import dict
from Bio import SeqIO
import os
import sys
import gzip
import pickle
import random
import logging
import numpy as np
from shutil import copyfileobj
def phred_to_prob(q):
"""Convert a phred score (Sanger or modern Illumina) in probabilty
Given a ph... | 0.667256 | 0.402744 |
import numpy as np
from functools import partial
from collections import namedtuple
import jax
import jax.numpy as jnp
from jax import value_and_grad
from jax.scipy import stats
import optax
from jax.scipy.special import logsumexp
from jax.lax import stop_gradient
from jax.experimental.host_callback import id_tap
fro... | cartpole/omd.py | import numpy as np
from functools import partial
from collections import namedtuple
import jax
import jax.numpy as jnp
from jax import value_and_grad
from jax.scipy import stats
import optax
from jax.scipy.special import logsumexp
from jax.lax import stop_gradient
from jax.experimental.host_callback import id_tap
fro... | 0.647798 | 0.29542 |
from typing import Union
import json
from urllib.parse import quote
import httpx
from logzero import logger
# fmt: off
async def atranslate(
text: str,
from_lang: str = "auto",
to_lang: str = "zh",
proxies: Union[str, dict] = None,
timeout: Union[float, httpx.Timeout] = 10,
... | itranslate/atranslate.py | from typing import Union
import json
from urllib.parse import quote
import httpx
from logzero import logger
# fmt: off
async def atranslate(
text: str,
from_lang: str = "auto",
to_lang: str = "zh",
proxies: Union[str, dict] = None,
timeout: Union[float, httpx.Timeout] = 10,
... | 0.60054 | 0.221603 |
from pixiedust.display.chart.renderers import PixiedustRenderer
from ..baseChartDisplay import BaseChartDisplay
from six import with_metaclass
from abc import ABCMeta
import pixiedust
myLogger = pixiedust.getLogger(__name__)
@PixiedustRenderer(rendererId="mapbox")
class MapBoxBaseDisplay(with_metaclass(ABCMeta, Bas... | pixiedust/display/chart/renderers/mapbox/mapBoxBaseDisplay.py |
from pixiedust.display.chart.renderers import PixiedustRenderer
from ..baseChartDisplay import BaseChartDisplay
from six import with_metaclass
from abc import ABCMeta
import pixiedust
myLogger = pixiedust.getLogger(__name__)
@PixiedustRenderer(rendererId="mapbox")
class MapBoxBaseDisplay(with_metaclass(ABCMeta, Bas... | 0.672762 | 0.14069 |
from floodsystem.stationdata import build_station_list, update_water_levels
from floodsystem.flood import stations_highest_rel_level
from floodsystem.plot import plot_water_level_with_fit
from floodsystem.datafetcher import fetch_measure_levels
from floodsystem.analysis import polyfit
import datetime
import matplotlib
... | Task2G.py | from floodsystem.stationdata import build_station_list, update_water_levels
from floodsystem.flood import stations_highest_rel_level
from floodsystem.plot import plot_water_level_with_fit
from floodsystem.datafetcher import fetch_measure_levels
from floodsystem.analysis import polyfit
import datetime
import matplotlib
... | 0.505859 | 0.515437 |
from __future__ import print_function
import random
from crypto_data import crypto_data
from moneywagon import get_block, push_tx, get_single_transaction, watch_mempool
from .core import to_rawtx
from moneywagon.services import BitpayInsight, ChainSo, LocalBitcoinsChain, BlockDozer
class NetworkReplay(object):
de... | moneywagon/network_replay.py | from __future__ import print_function
import random
from crypto_data import crypto_data
from moneywagon import get_block, push_tx, get_single_transaction, watch_mempool
from .core import to_rawtx
from moneywagon.services import BitpayInsight, ChainSo, LocalBitcoinsChain, BlockDozer
class NetworkReplay(object):
de... | 0.482917 | 0.14978 |
import numpy as np
from autoscalingsim.utils.metric.metric_categories.size import Size
class ParametersDistribution:
""" Empirical distribution of parameters to instantiate configurations of resource utils that themselves represent distributions (Gauss) """
@classmethod
def from_dict(cls, config : dict)... | experimentgenerator/parameters_distribution.py | import numpy as np
from autoscalingsim.utils.metric.metric_categories.size import Size
class ParametersDistribution:
""" Empirical distribution of parameters to instantiate configurations of resource utils that themselves represent distributions (Gauss) """
@classmethod
def from_dict(cls, config : dict)... | 0.844537 | 0.481271 |
import numpy as np
import sys
import time
from dataset_list import FilelistReader
from dataset_mxnet import MxReader
from dataset_multi import MultiDataset
from mt_loader import MultiThreadLoader
from util.config import Config
def get_WebFace(config, count = -1):
ds = FilelistReader(config.get('WebFace').prefix,... | dataset/dataset_all.py | import numpy as np
import sys
import time
from dataset_list import FilelistReader
from dataset_mxnet import MxReader
from dataset_multi import MultiDataset
from mt_loader import MultiThreadLoader
from util.config import Config
def get_WebFace(config, count = -1):
ds = FilelistReader(config.get('WebFace').prefix,... | 0.068905 | 0.131591 |
from xml.dom.minidom import parse
from lib.Functions import asciify
class XmlDataFormatException(Exception):
"""Xml file is not valid """
pass
class XmlDocument(object):
"""Provides a basic interface to an XML file"""
def __init__(self, filename):
self._xml_doc = parse(filename)
... | module/XmlParser.py |
from xml.dom.minidom import parse
from lib.Functions import asciify
class XmlDataFormatException(Exception):
"""Xml file is not valid """
pass
class XmlDocument(object):
"""Provides a basic interface to an XML file"""
def __init__(self, filename):
self._xml_doc = parse(filename)
... | 0.465387 | 0.095392 |
from OpenGL.GL import *
from pathlib import Path
import glfw
import numpy
import pygameboycore
import sys
import time
GB_WIDTH = 160
GB_HEIGHT = 144
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
class PyGameboyColor(object):
def __init__(self, width, height):
if not glfw.init():
raise Exception('can... | pygameboycolor/pygameboy.py | from OpenGL.GL import *
from pathlib import Path
import glfw
import numpy
import pygameboycore
import sys
import time
GB_WIDTH = 160
GB_HEIGHT = 144
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
class PyGameboyColor(object):
def __init__(self, width, height):
if not glfw.init():
raise Exception('can... | 0.442877 | 0.095729 |
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http: // www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# di... | helpers/draw.py |
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http: // www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# di... | 0.588771 | 0.483405 |
import datetime
from SSCClient.core import SSCClient
from SSCClient.utils import func_extract_all_project_names
from collections import defaultdict
if __name__ == "__main__":
ssc_client = SSCClient("https://192.168.1.1/ssc")
# ssc_client.set_auth_token("<KEY>")
ssc_client.set_auth_cookie("E58BC67EEB87A6BA... | demo.py | import datetime
from SSCClient.core import SSCClient
from SSCClient.utils import func_extract_all_project_names
from collections import defaultdict
if __name__ == "__main__":
ssc_client = SSCClient("https://192.168.1.1/ssc")
# ssc_client.set_auth_token("<KEY>")
ssc_client.set_auth_cookie("E58BC67EEB87A6BA... | 0.173113 | 0.080466 |
import argparse
import logging
import urllib.parse
from .version import __version__
class ArgumentFormatter(
argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter
):
pass
def log_level(arg):
if arg == "error":
return logging.ERROR
elif arg == "warn":
return log... | mllp_http/main.py | import argparse
import logging
import urllib.parse
from .version import __version__
class ArgumentFormatter(
argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter
):
pass
def log_level(arg):
if arg == "error":
return logging.ERROR
elif arg == "warn":
return log... | 0.494873 | 0.10325 |
import csv
import multiprocessing as mp
from xmlrpc import client as xmlrpclib
from scriptconfig import URL, DB, UID, PSW, WORKERS
# ==================================== P R O D U C T S ====================================
def update_product(pid, data_pool, create_ids, write_ids, uom_ids, category_ids, location_id... | 46_product.py |
import csv
import multiprocessing as mp
from xmlrpc import client as xmlrpclib
from scriptconfig import URL, DB, UID, PSW, WORKERS
# ==================================== P R O D U C T S ====================================
def update_product(pid, data_pool, create_ids, write_ids, uom_ids, category_ids, location_id... | 0.203787 | 0.110136 |
from unittest import TestCase
from parameterized import parameterized
from backuppy.cli.input import ask_confirm, ask_option, ask_any
try:
from unittest.mock import patch
except ImportError:
from mock import patch
class AskConfirmTest(TestCase):
@parameterized.expand([
(True, 'Foo (y/n): ', 'y'... | backuppy/tests/cli/test_input.py | from unittest import TestCase
from parameterized import parameterized
from backuppy.cli.input import ask_confirm, ask_option, ask_any
try:
from unittest.mock import patch
except ImportError:
from mock import patch
class AskConfirmTest(TestCase):
@parameterized.expand([
(True, 'Foo (y/n): ', 'y'... | 0.688364 | 0.419588 |
"""Setup script for jupyter_contrib_nbextensions."""
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
from __future__ import print_function
import os
from glob import glob
from setuptools import ... | setup.py | """Setup script for jupyter_contrib_nbextensions."""
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
from __future__ import print_function
import os
from glob import glob
from setuptools import ... | 0.664649 | 0.200186 |
import os
import platform
from retriever.lib.defaults import DATA_DIR
from retriever.lib.models import Engine
class engine(Engine):
"""Engine instance for Microsoft Access."""
name = "Microsoft Access"
instructions = ("Create a database in Microsoft Access, close Access."
"\nThen sel... | retriever/engines/msaccess.py | import os
import platform
from retriever.lib.defaults import DATA_DIR
from retriever.lib.models import Engine
class engine(Engine):
"""Engine instance for Microsoft Access."""
name = "Microsoft Access"
instructions = ("Create a database in Microsoft Access, close Access."
"\nThen sel... | 0.460532 | 0.160661 |
import pandas as pd
from typing import Dict, List, Any
from .errors import MissingFieldError
class DocReadUtils:
"""This is created as a Mixin for others to easily add to their classes"""
@classmethod
def get_field(self, field: str, doc: Dict, missing_treatment="raise_error"):
"""
For nes... | relevanceai/utils/doc_utils/read_utils.py | import pandas as pd
from typing import Dict, List, Any
from .errors import MissingFieldError
class DocReadUtils:
"""This is created as a Mixin for others to easily add to their classes"""
@classmethod
def get_field(self, field: str, doc: Dict, missing_treatment="raise_error"):
"""
For nes... | 0.803444 | 0.369799 |
import numpy as np
from pygmo import hypervolume
from scipy.spatial.distance import pdist, squareform
from sklearn.datasets import make_regression
from sklearn.datasets.samples_generator import make_blobs
from sklearn.gaussian_process.kernels import Matern
from sklearn.utils import check_random_state
from csrank.const... | csrank/dataset_reader/objectranking/object_ranking_data_generator.py | import numpy as np
from pygmo import hypervolume
from scipy.spatial.distance import pdist, squareform
from sklearn.datasets import make_regression
from sklearn.datasets.samples_generator import make_blobs
from sklearn.gaussian_process.kernels import Matern
from sklearn.utils import check_random_state
from csrank.const... | 0.837354 | 0.488649 |
import uuid
import math
from . import MAX
def split(input_file, chunk_size):
""" 分割大文件为小文件,并且将小文件数据排序
:param input_file: 输入文件
:param chunk_size: 块大小
:return: 小文件列表
"""
temp_files = []
chunk = []
with open(input_file, 'r') as f:
while True:
line = f.readline()
... | samples/ch01/a1_3_file_merge_sort_1.py |
import uuid
import math
from . import MAX
def split(input_file, chunk_size):
""" 分割大文件为小文件,并且将小文件数据排序
:param input_file: 输入文件
:param chunk_size: 块大小
:return: 小文件列表
"""
temp_files = []
chunk = []
with open(input_file, 'r') as f:
while True:
line = f.readline()
... | 0.169028 | 0.228232 |
from __future__ import annotations
import re
from abc import ABC, abstractmethod
from datetime import timedelta
from typing import TYPE_CHECKING, Union, Any, List
from .base import get_generator_response, EventManager, CacheBased
from .punishments import get_relevant_punishment
if TYPE_CHECKING:
from disnake.ext... | disnakeSuperUtils/messagefilter.py | from __future__ import annotations
import re
from abc import ABC, abstractmethod
from datetime import timedelta
from typing import TYPE_CHECKING, Union, Any, List
from .base import get_generator_response, EventManager, CacheBased
from .punishments import get_relevant_punishment
if TYPE_CHECKING:
from disnake.ext... | 0.842604 | 0.122996 |
import os
from collections import namedtuple
import xml.etree.ElementTree as ET
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
Stats = namedtuple("Stats", ["size"])
Text = namedtuple("Text", ["text", "stats"])
Meta = namedtuple("Meta"... | wahlprogramme/database.py | import os
from collections import namedtuple
import xml.etree.ElementTree as ET
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
Stats = namedtuple("Stats", ["size"])
Text = namedtuple("Text", ["text", "stats"])
Meta = namedtuple("Meta"... | 0.611498 | 0.155687 |
import spacy
from spacy.kb import KnowledgeBase
from collections import defaultdict
def get_prior_probs(candidates, alias_dict):
"""
Get prior probabilities of all candidates for a mention
:param candidates: the list of candidates for a company mention
:param alias_dict:
:return:
"""
pri... | src/probs_kb.py | import spacy
from spacy.kb import KnowledgeBase
from collections import defaultdict
def get_prior_probs(candidates, alias_dict):
"""
Get prior probabilities of all candidates for a mention
:param candidates: the list of candidates for a company mention
:param alias_dict:
:return:
"""
pri... | 0.593963 | 0.248893 |
"""Tests of grpc_reflection.v1alpha.reflection."""
import unittest
from google.protobuf.descriptor_pool import DescriptorPool
import grpc
from grpc_reflection.v1alpha import reflection
from grpc_reflection.v1alpha.proto_reflection_descriptor_database import \
ProtoReflectionDescriptorDatabase
from src.proto.grpc... | src/python/grpcio_tests/tests/reflection/_reflection_client_test.py | """Tests of grpc_reflection.v1alpha.reflection."""
import unittest
from google.protobuf.descriptor_pool import DescriptorPool
import grpc
from grpc_reflection.v1alpha import reflection
from grpc_reflection.v1alpha.proto_reflection_descriptor_database import \
ProtoReflectionDescriptorDatabase
from src.proto.grpc... | 0.565059 | 0.280004 |
class ConfigMeta(type):
def __new__(mcls, name, bases, cdict):
_config_keys = []
_defaults = {}
_default_values = {}
_re_keys = []
_re_patterns = {}
_re_defaults = {}
_export_keys = []
def _getattr(self, name):
if name in self._config_keys... | lament/meta.py | class ConfigMeta(type):
def __new__(mcls, name, bases, cdict):
_config_keys = []
_defaults = {}
_default_values = {}
_re_keys = []
_re_patterns = {}
_re_defaults = {}
_export_keys = []
def _getattr(self, name):
if name in self._config_keys... | 0.288669 | 0.062474 |
import configparser
# CONFIG
dwh_cfg = configparser.ConfigParser()
dwh_cfg.read('dwh.cfg')
IAM_ROLE_ARN = dwh_cfg.get('IAM', 'IAM_ROLE_ARN')
S3_LOG_DATA = dwh_cfg.get('S3', 'LOG_DATA')
S3_LOG_JSON = dwh_cfg.get('S3', 'LOG_JSON')
S3_SONG_DATA = dwh_cfg.get('S3', 'SONG_DATA')
# DROP TABLES
staging_events_table_drop ... | sql_queries.py | import configparser
# CONFIG
dwh_cfg = configparser.ConfigParser()
dwh_cfg.read('dwh.cfg')
IAM_ROLE_ARN = dwh_cfg.get('IAM', 'IAM_ROLE_ARN')
S3_LOG_DATA = dwh_cfg.get('S3', 'LOG_DATA')
S3_LOG_JSON = dwh_cfg.get('S3', 'LOG_JSON')
S3_SONG_DATA = dwh_cfg.get('S3', 'SONG_DATA')
# DROP TABLES
staging_events_table_drop ... | 0.147218 | 0.053874 |
tinynumbers = [
[0b11111,0b11111],
[0b11111],
[0b10111,0b11101],
[0b10101,0b11111],
[0b11110,0b00011],
[0b11101,0b10111],
[0b11111,0b00111],
[0b10000,0b11111],
[0b10101,0b10101],
[0b11100,0b11111]
]
# add japanese
font = {
32: [0x00, 0x00, 0x00, 0x00, 0x00], # (space)
... | library/microdotphat/font.py |
tinynumbers = [
[0b11111,0b11111],
[0b11111],
[0b10111,0b11101],
[0b10101,0b11111],
[0b11110,0b00011],
[0b11101,0b10111],
[0b11111,0b00111],
[0b10000,0b11111],
[0b10101,0b10101],
[0b11100,0b11111]
]
# add japanese
font = {
32: [0x00, 0x00, 0x00, 0x00, 0x00], # (space)
... | 0.185062 | 0.771843 |
import re
import time
from w3af.plugins.tests.helper import PluginTest, PluginConfig, MockResponse
from w3af.core.data.parsers.doc.url import URL
class ReDosMockResponse(MockResponse):
def get_response(self, http_request, uri, response_headers):
"""
Overwrite the mock response with one simple obj... | packages/w3af/w3af/plugins/tests/audit/test_redos.py | import re
import time
from w3af.plugins.tests.helper import PluginTest, PluginConfig, MockResponse
from w3af.core.data.parsers.doc.url import URL
class ReDosMockResponse(MockResponse):
def get_response(self, http_request, uri, response_headers):
"""
Overwrite the mock response with one simple obj... | 0.600891 | 0.183118 |
# Draw sphere with QUAD_STRIP
# Controls: UP/DOWN - scale up/down
# LEFT/RIGHT - rotate left/right
# F1 - Toggle surface as SMOOTH or FLAT
# Python imports
from math import *
# OpenGL imports for python
try:
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
ex... | sphere.py |
# Draw sphere with QUAD_STRIP
# Controls: UP/DOWN - scale up/down
# LEFT/RIGHT - rotate left/right
# F1 - Toggle surface as SMOOTH or FLAT
# Python imports
from math import *
# OpenGL imports for python
try:
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
ex... | 0.860633 | 0.420957 |
from django.test import TestCase
from bugal.base.models import Bank, Contact, User
from bugal.base.serializers import BankModelSerializer
class BankModelTest(TestCase):
"""Test Bank model"""
def setUp(self):
self.bank0 = Bank.objects.create(
name="NAB",
description="Natio... | bugal/base/tests/test_models.py | from django.test import TestCase
from bugal.base.models import Bank, Contact, User
from bugal.base.serializers import BankModelSerializer
class BankModelTest(TestCase):
"""Test Bank model"""
def setUp(self):
self.bank0 = Bank.objects.create(
name="NAB",
description="Natio... | 0.616705 | 0.277561 |
import pandas as pd
import json
from bson import json_util
df1 = pd.read_csv('C:/Users/hp/Desktop/Airbnb-Database/Tables/Availabilty Table.csv')
rec = json_util.loads(json.dumps(df1.to_dict(orient='records')))
with open('C:/Users/hp/Desktop/Airbnb-Database/MongoDbCollections/Availabilty Table.json', 'w') as outfile:
... | csv_to_json.py | import pandas as pd
import json
from bson import json_util
df1 = pd.read_csv('C:/Users/hp/Desktop/Airbnb-Database/Tables/Availabilty Table.csv')
rec = json_util.loads(json.dumps(df1.to_dict(orient='records')))
with open('C:/Users/hp/Desktop/Airbnb-Database/MongoDbCollections/Availabilty Table.json', 'w') as outfile:
... | 0.069601 | 0.053132 |
from datetime import datetime, timedelta
from typing import Optional
from fastapi import Depends
from jose import JWTError, jwt
from passlib.context import CryptContext
from rubrix.server.security.settings import settings
from .dao import UsersDAO, create_users_dao
from .model import User
class UsersService:
""... | src/rubrix/server/users/service.py | from datetime import datetime, timedelta
from typing import Optional
from fastapi import Depends
from jose import JWTError, jwt
from passlib.context import CryptContext
from rubrix.server.security.settings import settings
from .dao import UsersDAO, create_users_dao
from .model import User
class UsersService:
""... | 0.907982 | 0.10859 |
import time
import argparse
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
REMOTE_DIR = 'uploaded-from-drive-uploader'
# cre... | watcher.py | import time
import argparse
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
REMOTE_DIR = 'uploaded-from-drive-uploader'
# cre... | 0.350088 | 0.062075 |
from __future__ import unicode_literals, division, absolute_import, print_function
from datetime import datetime
import unittest
import os
import asn1crypto.x509
from oscrypto import asymmetric
from asn1crypto.util import timezone
from ocspbuilder import OCSPResponseBuilder
from ._unittest_compat import patch
patch... | tests/test_ocsp_response_builder.py | from __future__ import unicode_literals, division, absolute_import, print_function
from datetime import datetime
import unittest
import os
import asn1crypto.x509
from oscrypto import asymmetric
from asn1crypto.util import timezone
from ocspbuilder import OCSPResponseBuilder
from ._unittest_compat import patch
patch... | 0.594316 | 0.243828 |
import numpy as np
from matchms import calculate_scores
from matchms.networking.networking_functions import get_top_hits
from matchms.similarity import FingerprintSimilarity
from .test_SimilarityNetwork import create_dummy_spectrums
def create_dummy_scores():
spectrums = create_dummy_spectrums()
references = ... | tests/test_networking_functions.py | import numpy as np
from matchms import calculate_scores
from matchms.networking.networking_functions import get_top_hits
from matchms.similarity import FingerprintSimilarity
from .test_SimilarityNetwork import create_dummy_spectrums
def create_dummy_scores():
spectrums = create_dummy_spectrums()
references = ... | 0.754553 | 0.642937 |
import functools
import math
import multiprocessing
from contextlib import contextmanager, ExitStack
from functools import partial
from math import log2
from random import random
import torch
import torch.nn.functional as F
import trainer.losses as L
import numpy as np
from kornia.filters import filter2d
from linear_... | codes/models/stylegan/stylegan2_lucidrains.py | import functools
import math
import multiprocessing
from contextlib import contextmanager, ExitStack
from functools import partial
from math import log2
from random import random
import torch
import torch.nn.functional as F
import trainer.losses as L
import numpy as np
from kornia.filters import filter2d
from linear_... | 0.830009 | 0.403185 |
import json
import sys
import string
import unidecode
from torch import Tensor
from torch.nn import CosineSimilarity
from flair.models import SequenceTagger
from flair.data import Sentence, Token
import requests
from simstring.feature_extractor.character_ngram import CharacterNgramFeatureExtractor
from simstring.mea... | amstel/tagger_neural_fulldoc_disambig.py | import json
import sys
import string
import unidecode
from torch import Tensor
from torch.nn import CosineSimilarity
from flair.models import SequenceTagger
from flair.data import Sentence, Token
import requests
from simstring.feature_extractor.character_ngram import CharacterNgramFeatureExtractor
from simstring.mea... | 0.133443 | 0.220468 |
from pathlib import Path
p_functions = Path("game/upl/upl_scripts/")
func_list = []
for f in p_functions.glob("*.py"):
if "__" in str(f):
continue
with open(f, "r") as f_file:
func = f_file.read()
fname = func.split("class ")[1].split(":")[0]
if len(s := func.split('"""function')) ... | util/write_upl_docs.py | from pathlib import Path
p_functions = Path("game/upl/upl_scripts/")
func_list = []
for f in p_functions.glob("*.py"):
if "__" in str(f):
continue
with open(f, "r") as f_file:
func = f_file.read()
fname = func.split("class ")[1].split(":")[0]
if len(s := func.split('"""function')) ... | 0.410756 | 0.238905 |