id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9997439 | import pickle as pkl
plotname = 'DentateGyrus'
from scvi.dataset.MouseBrain import DentateGyrus10X, DentateGyrusC1
from scvi.dataset.dataset import GeneExpressionDataset
dataset1= DentateGyrus10X()
dataset1.subsample_genes(dataset1.nb_genes)
dataset2 = DentateGyrusC1()
dataset2.subsample_genes(dataset2.nb_genes)
gene_... |
9997507 | from django.core.management.base import BaseCommand
from django.contrib.contenttypes.models import ContentType
from user.models import User
import uuid
class Command(BaseCommand):
def handle(self, *args, **options):
objects = User.objects.all()
supports = {}
for i, user in enumerate(objec... |
9997516 | import os
import numpy as np
import pandas as pd
import pytest
from barrage.api import RecordMode, RecordTransformer
from barrage.dataset import RecordDataset
from barrage.utils import io_utils
@pytest.fixture
def dataset_dir(tmpdir):
os.mkdir(os.path.join(tmpdir, "dataset"))
return str(tmpdir)
@pytest.fi... |
9997522 | from __future__ import print_function
import pandas as pd
from rdkit import Chem
from rdkit.Chem import AllChem, MolFromSmiles
from sklearn.model_selection import KFold
from data_preprocess import *
import os
np.random.seed(123)
max_atom_num = 55
K = 5
qm8_tasks = ['E1-CC2', 'E2-CC2', 'f1-CC2', 'f2-CC2'... |
9997554 | import unittest
import hcl2
from checkov.terraform.checks.resource.azure.CosmosDBHaveCMK import check
from checkov.common.models.enums import CheckResult
class TestCosmosDBHaveCMK(unittest.TestCase):
def test_failure(self):
hcl_res = hcl2.loads("""
resource "azurerm_cosmosdb_account" "db" {
... |
9997595 | import FWCore.ParameterSet.Config as cms
process = cms.Process("rpctest")
#process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.MessageLogger = cms.Service("MessageLogger",
cerr = cms.untracked.PSet(
enable = cms.untracked.bool(False)
),
debugModules = cms.untracked.vstring('rpcTriggerD... |
9997613 | expected_output = {
"memory-statistics": {
"cached-bytes": "1975",
"cached-jumbo-clusters-16k": "0",
"cached-jumbo-clusters-4k": "3",
"cached-jumbo-clusters-9k": "0",
"cached-mbuf-clusters": "714",
"cached-mbufs": "2142",
"cluster-failures": "0",
"curr... |
9997674 | from tests.package.test_python import TestPythonPackageBase
class TestPythonPy3Crossbar(TestPythonPackageBase):
__test__ = True
config = TestPythonPackageBase.config + \
"""
BR2_PACKAGE_PYTHON3=y
BR2_PACKAGE_PYTHON_CROSSBAR=y
"""
sample_scripts = ["tests/package/sample_pyth... |
9997733 | from __future__ import annotations
import os
import typing
import toolcli
from ctc import evm
if typing.TYPE_CHECKING:
from ctc import spec
def get_command_spec() -> toolcli.CommandSpec:
return {
'f': async_abi_command,
'help': 'display abi of contract',
'args': [
{'nam... |
9997738 | from collections import defaultdict
import math
MIN = 60
HOUR = 60 * MIN
DAY = 24 * HOUR
# def scale_band(x): return (x ** 2) / (2 * (x ** 2 - x) + 1)
scale_band = lambda x: x
def log_band(n, scale=1): return math.log(n + 2) / scale
bands = [scale_band(x) for x in [0, 0.1, 0.2, 0.3, 0.4, 0.5]]
VISIT_SCALE = math.lo... |
9997739 | import os
import json
import time
import torch
import operator
from functools import reduce
import matplotlib.pyplot as plt
import collections
from .utils import xmkdir
class TotalAverage():
def __init__(self):
self.reset()
def reset(self):
self.last_value = 0.
self.mass = 0.
... |
9997857 | import sys
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtGui as qtg
from PyQt5 import QtCore as qtc
class DialogBox(qtw.QMessageBox):
def __init__(self,words):
super().__init__()
self.setText("Results from your RegEx Search")
word = ""
for i in words:
word +=... |
9997885 | from torchlm.data import LandmarksWFLWConverter
from torchlm.data import Landmarks300WConverter
from torchlm.data import LandmarksCOFWConverter
from torchlm.data import LandmarksAFLWConverter
def test_wflw_converter():
converter = LandmarksWFLWConverter(
data_dir="../data/WFLW",
save_dir="../data/W... |
9997941 | import argparse
import sys
from packaging import version
import time
import util
import os
import os.path as osp
import timeit
from collections import OrderedDict
import scipy.io
import torch
import torchvision.models as models
import torch.nn.functional as F
from torch.utils import data, model_zoo
import torch.backen... |
9997948 | import torch
from mmdet.ops.iou3d.iou3d_utils import nms_gpu
def rotate_nms_torch(rbboxes,
scores,
pre_max_size=None,
post_max_size=None,
iou_threshold=0.5):
if pre_max_size is not None:
num_keeped_scores = scores.shape[0]
... |
9997975 | from random import randrange
from pathlib import Path
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
from torch.nn.utils.rnn import pad_sequence
from einops import rearrange
from tqdm import tqdm
import numpy as np
from shutil import rmtree
from nuwa_pytorch.tokenizer import token... |
9997987 | import unittest
import dask.array as da
import numpy as np
import pyproj
import xarray as xr
from xcube.core.gridmapping import GridMapping
# noinspection PyProtectedMember
GEO_CRS = pyproj.crs.CRS(4326)
# noinspection PyMethodMayBeStatic
class Coords1DGridMappingTest(unittest.TestCase):
def test_1d_j_axis_d... |
9997995 | import fbuild.config.c as c
# ------------------------------------------------------------------------------
class libutf8_h(c.Test):
header = c.header_test('libutf8.h')
|
9998038 | import pytest
from aioresponses import aioresponses
from pornhub_api import PornhubApi
from pornhub_api.backends.aiohttp import AioHttpBackend
aiohttp = pytest.importorskip("aiohttp")
@pytest.fixture(params=["ph5c66d850c33de"])
def video_id(request):
return request.param
@pytest.fixture()
def response_snapsho... |
9998047 | import unittest
import hcl2
from checkov.terraform.checks.resource.gcp.GoogleComputeDiskEncryption import check
from checkov.common.models.enums import CheckResult
class TestGoogleComputeDiskEncryption(unittest.TestCase):
def test_failure(self):
hcl_res = hcl2.loads("""
resource "google_com... |
9998078 | import torch.nn as nn
import numpy as np
import torch
import config
def loss_calculator(out_1, out_2, pixel_masks, link_masks, pixel_weights):
link_weight = config.link_weight
pixel_weight = config.pixel_weight
loss = pixel_weight * pixel_loss(out_1, pixel_masks, pixel_weights) + \
link_weight *... |
9998098 | from tflearn.datasets import titanic
titanic.download_dataset('titanic_dataset.csv')
from tflearn.data_utils import load_csv
data, labels = load_csv('titanic_dataset.csv', target_column=0,
categorical_labels=True, n_classes=2)
def preprocess(data, columns_to_ignore):
for id in sorted... |
9998151 | import os
import sys
from shapely.geometry import Polygon
from pyspark.sql import SparkSession
from pyspark.sql.functions import encode
import pandas as pd
import geopandas as gpd
import h3
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from jobs.conversion import (
coord_to_emd,
... |
9998156 | from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
import datetime
import pandas_datareader as pdr
#Scraping data
finviz_url="https://finviz.com/quote.ashx?t="
ti... |
9998258 | import jax
from functools import partial
def _treeify(f):
def _f(x, *args, **kwargs):
return jax.tree_map(lambda y: f(y, *args, **kwargs), x)
return _f
@_treeify
def _unchunk(x):
return x.reshape((-1,) + x.shape[2:])
@_treeify
def _chunk(x, chunk_size=None):
# chunk_size=None -> add just ... |
9998267 | import pytest
import fideslang as models
@pytest.mark.unit
class TestSystem:
def test_system_valid(self) -> None:
system = (
models.System(
organization_fides_key=1,
registry_id=1,
meta={"some": "meta stuff"},
fides_key="test_sys... |
9998273 | import pytest
import os
import logging
import tempfile
from ocs_ci.utility.utils import clone_repo, exec_cmd
from ocs_ci.ocs import machine, node, ocp, constants
from ocs_ci.utility import templating
from ocs_ci.framework import config
log = logging.getLogger(__name__)
@pytest.fixture(scope="class")
def clone_ibm_ch... |
9998283 | from gym_ignition.scenario import model_wrapper, model_with_file
from gym_ignition.utils.scenario import get_unique_model_name
from scenario import core as scenario
from scenario import gazebo as scenario_gazebo
from typing import List, Tuple
from os import path
class Panda(model_wrapper.ModelWrapper,
mod... |
9998298 | from .element import Element
from .navbar import Navbar
from .fontawesomeicon import FontAwesomeIcon
class View(Element):
"""Main object representing a webpage"""
def __init__(self, title=None, cl=None, style=None,
bscss="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min... |
9998346 | import torch
from . import util
# @profile
def pnqp(H, q, lower, upper, x_init=None, n_iter=20):
GAMMA = 0.1
n_batch, n, _ = H.size()
pnqp_I = 1e-11*torch.eye(n).type_as(H).expand_as(H)
def obj(x):
return 0.5*util.bquad(x, H) + util.bdot(q, x)
if x_init is None:
if n == 1:
... |
9998392 | import dash_bootstrap_components as dbc
from dash import html
from .util import make_subheading
progress = html.Div(
[
make_subheading("dbc.Progress", "progress"),
dbc.Progress("25%", value=25),
dbc.Progress(value=50, striped=True, className="my-2"),
dbc.Progress(value=75, color="s... |
9998428 | import smtplib
from django.core import mail
from django.template.loader import render_to_string
from modoboa.lib.cryptutils import get_password
from modoboa.parameters import tools as param_tools
from . import get_imapconnector, clean_attachments
def send_mail(request, form, posturl=None):
"""Email verificatio... |
9998431 | import json
import os
import random
import shutil
import socket
import tempfile
import time
import unittest
import urllib
import urllib.request
from subprocess import Popen
from urllib.error import HTTPError
def get_samples_dir():
return os.path.join(os.path.dirname(os.path.abspath(__file__)), '../samples')
cla... |
9998538 | from rest_framework import viewsets
from jobboard.models import Specialisation, Keyword
from jobboard.serializers.EmployerSerializer import EmployerSerializer
from jobboard.serializers.KeywordSerializer import KeywordSerializer
from jobboard.serializers.SpecialisationSerializer import SpecialisationSerializer
from use... |
9998640 | import random
from collections import namedtuple
from Envi import Env
Transition = # Define namedtuple
BATCH_SIZE = #Define batch size
GAMMA = # Define gamma
LEARNING_RATE = 0.001
class Memory(object):
def __init__(self, capacity: int):
# Need some code
def clear(self):
self.memory: list... |
9998677 | from sklearn.datasets import fetch_lfw_people
import numpy as np
import pdb
MALENESS_THRESHOLD = 0 # threshold at which the person is classified as a male
MIN_FACES = 5
TRAIN_CUT = 0.75
print("Fetching people with at least " + str(MIN_FACES) + " pictures.")
lfw_people = fetch_lfw_people(color=True, min_faces_per_per... |
9998679 | import contextlib
import logging
import random
import typing
from urllib.parse import quote
import aiohttp
import discord
from discord.ext import commands
logger = logging.getLogger(__name__)
class IdiotError(Exception):
pass
api_endpoints = {
"api_endpoints": {
"Generators": ("achievement", "bats... |
9998704 | import os
import KratosMultiphysics as Kratos
from KratosMultiphysics import Logger
Logger.GetDefaultOutput().SetSeverity(Logger.Severity.WARNING)
import KratosMultiphysics.KratosUnittest as KratosUnittest
import KratosMultiphysics.DEMApplication.DEM_analysis_stage
import auxiliary_functions_for_tests
this_working_di... |
9998712 | import FWCore.ParameterSet.Config as cms
from RecoBTau.JetTagComputer.MVAJetTagsFakeConditions_cfi import *
|
9998750 | import numpy as np
import csv
import os
import warnings
def read_panoptic_mapper_data_log(file_name):
""" A stored data log of the panoptic mapper and converts it into a
dictionary of numpy arrays if numeric or lists of strings otherwise. """
result = {}
if not os.path.isfile(file_name):
warni... |
9998767 | class Node():
def __init__(self,data):
self.val=data
self.left=None
self.right=None
def insert(root,node):
if root is None:
root=node
else:
if root.val<node.val:
if root.right is None:
root.right=node
else:
... |
9998777 | import mimetypes
from abc import ABC
from typing import Any, BinaryIO, Dict, Iterable, Optional
from . import exc
class VerifiableStorage(ABC):
"""A storage backend that supports object verification API
All streaming backends should be 'verifiable'.
"""
def verify_object(self, prefix: str, oid: str,... |
9998797 | import logging
import re
logger = logging.getLogger(__name__)
logger.debug('Programmstart')
import locale
import datetime
import json
import os
import threading
import time
import traceback
import sys
import pytz as pytz
import requests
try:
import paho.mqtt.client as paho
except:
logger.warning('Paho-Lib... |
9998808 | from hazelcast.protocol.codec import (
set_add_all_codec,
set_add_codec,
set_add_listener_codec,
set_clear_codec,
set_compare_and_remove_all_codec,
set_compare_and_retain_all_codec,
set_contains_all_codec,
set_contains_codec,
set_get_all_codec,
set_is_empty_codec,
set_remove_... |
9998814 | import numpy as np
import time
import random
import math
import os
import sys
from multiprocessing import Process, Queue
import _pickle as cPickle
import io
import pdb
import gizeh
def draw(shape, pixel, filename=None):
resize = pixel / 10
surface = gizeh.Surface(width=pixel, height=pixel, bg_color=(0, 0, 0))... |
9998816 | from pyvmmonitor_core.callback import Callback
from pyvmmonitor_core.weak_utils import get_weakref
def test_callback():
c = Callback()
class F(object):
def __init__(self):
self.called = None
def __call__(self, b):
self.called = b
f = F()
c.regi... |
9998817 | from typing import List, Tuple
import numpy as np
from uncertainty_wizard.quantifiers.predictive_entropy import PredictiveEntropy, entropy
from uncertainty_wizard.quantifiers.quantifier import ProblemType, UncertaintyQuantifier
class MutualInformation(UncertaintyQuantifier):
"""
A predictor & uncertainty qu... |
9998836 | from agent.Agent import Agent
from agent.examples.SumServiceAgent import SumServiceAgent
from message.Message import Message
from util.util import log_print
import pandas as pd
# The SumClientAgent class inherits from the base Agent class. It is intended
# to serve as an example in which a service agent performs so... |
9998841 | from django.contrib import admin
from .models import Lock
@admin.register(Lock)
class LockAdmin(admin.ModelAdmin):
date_hierarchy = 'creation_datetime'
list_display = ('name', 'creation_datetime', 'timeout')
|
9998999 | import argparse
import json
import logging
import math
import urllib
from typing import Any, Dict, List, Tuple
from datetime import datetime
import numpy as np
import pandas as pd
import xgboost as xgb
from pkg_resources import resource_filename
from .io import read_frame, read_model, write_predictions, read_claim, r... |
9999042 | import pytest
import torch
import sklearn.metrics
import numpy as np
from flambe.metric import Accuracy, AUC, MultiClassAUC, Perplexity, BPC, F1
from flambe.metric import BinaryRecall, BinaryPrecision, BinaryAccuracy
from flambe.metric import Recall
from pytest import approx
NUMERIC_PRECISION = 1e-2
def metric_test... |
9999071 | from __future__ import unicode_literals
from django.db import models
class Address(models.Model):
email = models.EmailField(unique=True)
enabled = models.BooleanField(default=True)
description = models.TextField(null=True)
created_on = models.DateTimeField(auto_now_add=True)
modified_on = models.... |
9999082 | from Backbones.Margin.ArcMarginProduct import ArcMarginProduct
from Backbones.Margin.CosineMarginProduct import CosineMarginProduct
from Backbones.Margin.InnerProduct import InnerProduct |
9999109 | import torch
from torchvision.models.detection.transform import GeneralizedRCNNTransform
from .dsfacedetector.face_ssd_infer import SSD
DETECTOR_THRESHOLD = 0.3
DETECTOR_MIN_SIZE = 512
DETECTOR_MAX_SIZE = 512
DETECTOR_MEAN = (104.0, 117.0, 123.0)
DETECTOR_STD = (1.0, 1.0, 1.0)
__all__ = ['Detector']
class Detector... |
9999121 | import json
import os
import redis
# initialize redis connection for local and CF deployment
def connect_redis_db(redis_service_name = 'p-redis'):
if os.environ.get('VCAP_SERVICES') is None: # running locally
DB_HOST = 'localhost'
DB_PORT = 6379
DB_PW = ''
REDIS_DB = 1
else: ... |
9999131 | import logging
from django.db import transaction, connection
from huey import crontab
from huey.contrib.djhuey import db_task, db_periodic_task
from abyssal_modules.metrics import COUNTER_MODULES_CREATED
from abyssal_modules.models.modules import Module
from abyssal_modules.models.attributes import ModuleAttribute, ... |
9999149 | from copy import deepcopy
from typing import NewType
import torch
from injector import Injector, Module, inject, multiprovider, provider, singleton
from mcp.config.parser import ExperimentConfig
from mcp.config.task import TaskType
from mcp.data.dataset.dataset import DatasetMetadata
from mcp.data.dataset.transforms ... |
9999150 | from malaya_speech.utils import (
check_file,
load_graph,
generate_session,
nodes_session,
)
from malaya_speech.model.tf import FastSpeechSplit
from malaya_speech import speaker_vector, gender
def load(model, module, f0_mode='pyworld', quantized=False, **kwargs):
path = check_file(
file=mo... |
9999215 | import numpy as np
from emukit.test_functions import sixhumpcamel_function
def test_sixhumpcamel_minima():
"""
Test some known values at minima
"""
sixhumpcamel, _ = sixhumpcamel_function()
minimum = -1.0316 # value of function at minima
assert np.isclose(sixhumpcamel(np.array([[0.0898, -0.71... |
9999228 | from datetime import datetime
from functools import partial
import pandas as pd
from matplotlib import pyplot as plt
from src.backtester import BackTester
from src.pricer import read_price_df
from src.finta.ta import TA
from src.orders.order import Order, OrderStatus, OrderSide
# Strategy rules:
# Bu... |
9999242 | import unittest
from dojo import get_painted_nodes, get_both_nodes, main
class DojoTest(unittest.TestCase):
def test_get_painted(self):
self.assertEqual(get_painted_nodes([1,2,3],2,3), {2})
def test_get_painted2(self):
self.assertEqual(get_painted_nodes([1,2,3],1,3), {1})
def test_get_pa... |
9999265 | from collections import defaultdict
from eventsourcing.domain.model.events import subscribe, unsubscribe
from quantdsl.domain.model.call_dependencies import CallDependenciesRepository
from quantdsl.domain.model.call_dependents import CallDependentsRepository
from quantdsl.domain.model.call_requirement import CallRequir... |
9999268 | import numpy as np
import chainer
from chainerpruner.masks.normmask import NormMask
from chainerpruner import Graph
class SimpleNet(chainer.Chain):
def __init__(self):
super(SimpleNet, self).__init__()
with self.init_scope():
self.conv1 = chainer.links.Convolution2D(1, 10, 3)
... |
9999303 | from __future__ import absolute_import
from confu.platform import Platform
from confu.tools.toolchains import UnixToolchain
import confu.globals
import confu.platform
import os
class NaClToolchain(UnixToolchain):
def __init__(self, target, toolchain):
super(NaClToolchain, self).__init__(target)
a... |
9999310 | DATABASE_ENGINE = "sqlite3"
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
INSTALLED_APPS = [
"django.contrib.contenttypes",
"django.contrib.auth",
"actistream",
"actistream.tests",
]
USE_TZ = True
SECRET_KEY = "psst"
TEMPLATES = [... |
9999321 | from pymtl import *
from lizard.bitutil import clog2, clog2nz
from lizard.util.rtl.interface import Interface, UseInterface
from lizard.util.rtl.method import MethodSpec
from lizard.util.rtl.types import canonicalize_type
class AsynchronousRAMInterface(Interface):
def __init__(s,
dtype,
... |
9999339 | from django.contrib.sitemaps import views
from django.urls import path
urlpatterns = [
path(
'sitemap-without-entries/sitemap.xml', views.sitemap,
{'sitemaps': {}}, name='django.contrib.sitemaps.views.sitemap',
),
]
|
9999343 | import cupy as cp
import numpy as np
import pytest
from cupy import testing
from cupyx.scipy import ndimage as ndi
from skimage import data
from cucim.skimage import color
from cucim.skimage.morphology import binary, grey, selem
from cucim.skimage.util import img_as_bool
img = color.rgb2gray(cp.array(data.astronaut()... |
9999403 | from os.path import dirname, basename, isfile, join
from RePoE.parser import Parser_Module
import glob
import inspect
import importlib
def _get_child_classes(module, parent_class):
child_classes = []
for name, obj in inspect.getmembers(module):
if inspect.isclass(obj) and obj.__bases__[0] == parent_cl... |
9999450 | from .base import *
from direct.interval.IntervalGlobal import (LerpPosInterval, LerpQuatInterval,
LerpScaleInterval, LerpQuatScaleInterval, Parallel)
class ViewManager:
def __init__(self):
GD.set_default("view", "persp")
self._lerp_interval = None
self._transition_done = True
... |
9999476 | import komand
from .schema import ConnectionSchema
# Custom imports below
import requests
from requests import Session, Request
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import logging
from copy import copy
import re
from komand.exceptions import ConnectionTestException, PluginException
... |
9999525 | from django.contrib.auth.models import AbstractUser, Group
from django.db import models
from django.utils import timezone
from jsonfield import JSONField
from simple_history.models import HistoricalRecords
import django.db.models.options as options
from django.conf import settings
from django.db.models import F, Func, ... |
9999540 | from typing import Dict
from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import]
# Disable insecure warnings
requests.packages.urllib3.disable_warnings()
# CONSTANTS
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
class pXScoring:
"""
Class to handle all current and future scoring for PerimeterX object... |
9999546 | from django.db.models import DecimalField, DurationField, Func
class IntervalToSeconds(Func):
function = ''
template = """
EXTRACT(day from %(expressions)s) * 86400 +
EXTRACT(hour from %(expressions)s) * 3600 +
EXTRACT(minute from %(expressions)s) * 60 +
EXTRACT(second from %(expressions)s)
... |
9999601 | from Adafruit_I2C import Adafruit_I2C
import time
ADDR_ADC121 = 0x50
REG_ADDR_RESULT = 0x00
REG_ADDR_ALERT = 0x01
REG_ADDR_CONFIG = 0x02
REG_ADDR_LIMITL = 0x03
REG_ADDR_LIMITH = 0x04
REG_ADDR_HYST = 0x05
REG_ADDR_CONVL = 0x06
REG_ADDR_CONVH = 0x07
getData = int()
analogVal = int()
i2c = Adafruit_I2C(ADDR_ADC121) ... |
9999604 | from typing import Dict, List, Tuple
from .dataset import Dataset
import torch
import random
class DualLabeledDataset(Dataset):
def __init__(self, kwargs):
super(DualLabeledDataset, self).__init__(kwargs)
self.kwargs = kwargs
self.datasets = {'train':kwargs['train_dataset'],
... |
9999619 | import math
from river import stats, utils
from . import base
class PS(base.InternalMetric):
r"""Partition Separation (PS).
The PS index [^1] was originally developed for fuzzy clustering. This index
only comprises a measure of separation between prototypes. Although classified
as a batch clusterin... |
9999620 | import json
import sys
import string
from libpgm.graphskeleton import GraphSkeleton
from libpgm.tablecpdfactorization import TableCPDFactorization
from libpgm.pgmlearner import PGMLearner
text = open("../unifiedMLData2.json")
data=text.read()
printable = set(string.printable)
asciiData=filter(lambda x: x in printable... |
9999622 | import numpy as np
from numpy.testing import assert_allclose
import pytest
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib.testing.decorators import image_comparison, check_figures_equal
@image_comparison(['polar_axes'], style='default', tol=0.012)
def test_polar_annotations():
# Yo... |
9999624 | import time
import sys,os
sys.path.append(os.path.realpath('.'))
from openrgb import OpenRGB
client = OpenRGB('localhost', 6742)
for device in client.devices():
print('{} - {}'.format(device.name, device.type))
for mode in device.modes:
print('* {} - {}'.format(mode['value'], mode['name']))
prin... |
9999640 | import asyncio
import os
import socket
from multiprocessing import Process
from time import sleep
import pytest
import uvicorn
from hypercorn.asyncio import serve as hypercorn_serve
from hypercorn.run import Config as HypercornConfig
from .app_1 import app
from .app_2 import app_2
from .app_3 import app_3
from .app_4... |
9999661 | from typing import Dict, List, Optional
import databases
import pytest
import sqlalchemy
import ormar
from tests.settings import DATABASE_URL
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
class BaseMeta(ormar.ModelMeta):
metadata = metadata
database = database
class Chart(o... |
9999679 | import pytest
from .factories import ItemFactory
pytestmark = pytest.mark.django_db
def test___str__(product, order, item):
assert order.__str__() == f"Pedido {order.id}"
assert str(order) == f"Pedido {order.id}"
assert item.__str__() == str(item.id)
assert str(item) == str(item.id)
def test_orde... |
9999690 | import pickle
from sklearn import mixture
import numpy as np
import re
import urlparse
# local includes
from src.algorithms.algorithm import Algorithm
from src.utils.geo import haversine, bb_center
from src.utils.schema import get_twitter_schema
import statsmodels.sandbox.distributions.extras as ext
import math
import ... |
9999706 | from __future__ import annotations
from .arabic import ARABIC_NUMBERS, ARABIC_PUNCTUATIONS
from .english import ENGLISH_NUMBERS, ENGLISH_PUNCTUATIONS
SPACE: str = " "
""" Space character """
EMPTY: str = ""
""" Empty character """
PUNCTUATIONS: list[str] = ARABIC_PUNCTUATIONS + ENGLISH_PUNCTUATIONS
""" Arabic and Eng... |
9999763 | class SearchHotelsData:
def __init__(self, destination, check_in, check_out, adults_num, kids_num):
self.destination = destination
self.check_in = check_in
self.check_out = check_out
self.adults_num = adults_num
self.kids_num = kids_num
|
9999799 | import hmac
import hashlib
import json
import codecs
import time
import requests
def hook(satsale_secret, invoice, order_id):
key = codecs.decode(satsale_secret, "hex")
# Calculate a secret that is required to send back to the
# woocommerce gateway, proving we did not modify id nor amount.
secret_see... |
9999827 | from .models import User
from social.pipeline.partial import partial
@partial
def check_for_user(user, *args, **kwargs):
if not User.objects.filter(username=user.username).exists():
new_user = User(username=user.username)
new_user.save()
return
|
9999855 | import os
DIRNAME = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'database.db', # Or path to database file if using sqlite3.
'USER': '', ... |
9999860 | from ..mapper import PropertyMapper, ApiInterfaceBase
from ..mapper.types import Timestamp, AnyType
__all__ = ['Bold', 'BoldInterface']
class BoldInterface(ApiInterfaceBase):
start: int
end: int
class Bold(PropertyMapper, BoldInterface):
pass
|
9999873 | USERS = {
"haho0032": {
"sn": "Hoerberg",
"givenName": "Hans",
"eduPersonScopedAffiliation": "<EMAIL>",
"eduPersonPrincipalName": "<EMAIL>",
"uid": "haho",
"eduPersonTargetedID": "one!for!all",
"c": "SE",
"o": "Example Co.",
"ou": "IT",
... |
9999915 | from __future__ import division
import os
import time
import iotbx.pdb
import mmtbx.f_model
from scitbx.array_family import flex
import run_tests
def run(prefix):
"""
Exercise standard (cctbx-based restraints) refinement with all defaults.
"""
xrs_good,xrs_poor,f_obs,r_free_flags = run_tests.setup_helix_examp... |
9999922 | import os
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from openbiolink.graph_creation import graphCreationConfig as gcConst
from openbiolink.gui import gui as gui
class SplitFrame(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.cont... |
9999951 | import argparse
import json
import os
import urllib.error
from urllib.parse import urljoin
from urllib.request import Request, urlopen
token_env_key = "GITLAB_TOKEN"
parser = argparse.ArgumentParser()
parser.add_argument("base_url", nargs="?", default="https://gitlab.com/")
parser.add_argument(
"--token",
d... |
9999975 | from app import app, db, sentry
from flask import g, render_template, make_response, redirect, request
import version
import libforget.version
from libforget.auth import get_viewer_session, set_session_cookie
@app.before_request
def load_viewer():
g.viewer = get_viewer_session()
if g.viewer and sentry:
... |
9999986 | from __future__ import division
import pytest
import logging
import os
from eigenproblems import *
from eigensolvers import *
from helpers import is_diagonal_matrix
def test_assert_eigenproblems_were_defined():
"""
Check that `available_eigenproblems` is not the empty set and that
a few known eigenproblem... |
9999988 | from typing import List
from vespa.package import (
Document,
Field,
Schema,
FieldSet,
RankProfile,
HNSW,
ApplicationPackage,
QueryProfile,
QueryProfileType,
QueryTypeField,
)
from vespa.query import QueryModel, AND, RankProfile as Ranking
class TextSearch(ApplicationPackage):... |
11400106 | import os
import sys
from IocManager import IocManager
from infrastructure.api.decorators.Endpoint import endpoint
from infrastructure.utils.Utils import Utils
from models.configs.ApplicationConfig import ApplicationConfig
def controller(namespace=None, route=None, exclude=None):
if exclude is None:
excl... |
11400140 | import os
import sys
import datetime
import re
CROARING_DIR = 'CRoaring'
SRC_DIR = os.path.join(CROARING_DIR, 'src')
INCLUDE_DIR = os.path.join(CROARING_DIR, 'include', 'roaring')
SRC_FILE = 'roaring.c'
INCLUDE_FILE = 'roaring.h'
LICENSE_TXT = '''Copyright %s The CRoaring authors
Licensed under the Apache License, V... |
11400145 | from setuptools import setup
setup(
name="pytest-warnings",
description='pytest plugin to list Python warnings in pytest report',
long_description=open("README.rst").read(),
license="MIT license",
version='0.3.1',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/fschulz... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.