id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1621320 | from heapq import heappush,heappop
#create function for heap
def heap_sort(array):
heap = []
for element in array:
heappush(heap, element)
ordered = []
# element left in the top heap
while heap:
ordered.append(heappop(heap))
return ordered
# array
array = [14,22,15,3,27,... |
1621336 | import logging
import sys
import subprocess
import json
import queue
import threading
import shutil
import pyaudio
import snowboydecoder
from speech_recognizer import AudioInputDevice
import avs
from audio_player import AudioDevice
class MplayerAudioDevice(AudioDevice):
def __init__(self, binary_path, options=N... |
1621381 | from .kitti import KittiDataset
from .nuscenes import NuScenesDataset
from .lyft import LyftDataset
dataset_factory = {
"KITTI": KittiDataset,
"NUSC": NuScenesDataset,
"LYFT": LyftDataset,
}
def get_dataset(dataset_name):
return dataset_factory[dataset_name]
|
1621389 | import os
import shutil
import stat
import pprint
import random
import sys
import logging
import time
import datetime
import functools
import platform
import re
import pbcommand.cli.utils as U
from pbcommand.models import ResourceTypes, TaskTypes
from pbcommand.common_options import add_log_debug_option
from pbcommand... |
1621405 | class Siamese(tf.keras.Model):
def __init__(self, shared_conv):
super().__init__(self, name="siamese")
self.conv = shared_conv
self.dot = Dot(axes=-1, normalize=True)
def call(self, inputs):
i1, i2 = inputs
x1 = self.conv(i1)
x2 = self.conv(i2)
return sel... |
1621430 | import json
import base64
import typing
import tempfile
import re
from datetime import datetime
from datetime import timezone
import falcon
from mitmproxy import ctx
from mitmproxy import connections
from mitmproxy import version
from mitmproxy.utils import strutils
from mitmproxy.net.http import cookies
from mitm... |
1621518 | from utils import *
class Counter:
def __init__(self, data):
self.__countResult=0
self.__data=data
self.__parse()
def __parse(self):
self.__startCounting()
def __startCounting(self):
for g in groupeData(self.__data):
self.__countYes(g)
def __countYes(... |
1621584 | from gui.creator import load_bot_config
from gui.creator import load_building_pos
from gui.creator import write_building_pos, write_bot_config
from gui.creator import button
from tkinter import Label, Frame, Text, Scrollbar, Canvas, LabelFrame, Toplevel, Entry, Button
from tkinter import N, W, END, NSEW, INSERT, LEFT
... |
1621591 | import angr
import binascii
def main():
p = angr.Project("fake", auto_load_libs=False)
state = p.factory.blank_state(addr=0x4004AC)
inp = state.solver.BVS('inp', 8*8)
state.regs.rax = inp
simgr= p.factory.simulation_manager(state)
simgr.explore(find=0x400684)
found = simgr.found[0]
#... |
1621631 | import gzip
import json
import os
import random
import shutil
from contextlib import closing
import pandas as pd
def generate_sample_data():
random.seed(42)
files = {}
for month in range(1, 13):
lines = []
for suffix_id in range(1000):
lines.append({
'id': mont... |
1621652 | expected_output = {'bridge-domain': 1000,
'peers': {1: {'peer-address': '192.168.255.3', 's': 'Y', 'vc-id': 1000},
2: {'peer-address': '192.168.255.1', 's': 'Y', 'vc-id': 1000}},
'signaling': 'LDP',
'state': 'up',
'type': 'multipoint',
'vfi-name': 'vpls',
'vpn-id': 1000}
|
1621657 | import os
import scaper
import jams
os.chdir('..')
# FIXTURES
# Paths to files for testing
FG_PATH = 'tests/data/audio/foreground'
BG_PATH = 'tests/data/audio/background'
ALT_FG_PATH = 'tests/data/audio_alt_path/foreground'
ALT_BG_PATH = 'tests/data/audio_alt_path/background'
REG_NAME = 'soundscape_20200501'
# REG_... |
1621691 | import uuid
import json
from gbdxtools.vector_styles import CircleStyle, LineStyle, FillStyle
class VectorLayer(object):
""" Abstract constructor for a vector layer knowing how to render itself as javascript.
Args:
styles (list): list of styles for which to create layers
"""
def __i... |
1621746 | import os
import re
import numpy as np
import trimesh
def save_mesh(mesh, save_path):
if isinstance(mesh.visual, trimesh.visual.texture.TextureVisuals):
save_path = os.path.join(os.path.dirname(save_path),
os.path.basename(os.path.splitext(save_path)[0]),
... |
1621786 | import math
import time
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, preprocessing
from cpca import CPCA
from ccpca import CCPCA
dataset = datasets.load_wine()
X = dataset.data
y = dataset.target
X = preprocessing.scale(X)
cpca = CPCA()
# manual alpha selection
# cpca.fit(fg=X[... |
1621804 | import torch
import torch.nn as nn
from torch.nn import init
class SupervisedGraphSage(nn.Module):
def __init__(self, num_classes, enc):
super(SupervisedGraphSage, self).__init__()
self.enc = enc
self.xent = nn.CrossEntropyLoss()
self.weight = nn.Parameter(torch.FloatTensor(num_cl... |
1621826 | from typing import Dict, Tuple, Union
from tensorflow.keras.layers import Concatenate, Dense, Dropout, GlobalAveragePooling1D, Input
from tensorflow.keras.models import Model
from tensorflow.python.keras.losses import Loss
from tensorflow.python.keras.optimizers import Optimizer
from marketml.models.time import Time2... |
1621872 | from .header import *
from .test import TestAgent
'''
Pre-training and Fine-tuning the GPT2
In pre-training stage, GPTModel + lm _head
In Fine-tuning stage, GPTModel + Transformer_matrix + lm_head
'''
class PFGPT2(nn.Module):
def __init__(self, vocab_size, unk_id, sep_id, topk, topp,
config_pat... |
1621917 | import urllib2
from bs4 import BeautifulSoup
import pyisbn
import re
import time
import mechanize
def infibeam(isbn):
i_link = "http://www.infibeam.com/Books/search?q="+isbn
br = mechanize.Browser()
#br.set_all_readonly(False) # allow everything to be written to
br.set_handle_robots(False) # ignore robots
br.... |
1621961 | import glob
import json
import os
import sys
from copy import deepcopy
from distutils.version import LooseVersion
from typing import Optional, Union
import click
import networkx as nx
from requests import RequestException
from demisto_sdk.commands.common import constants
from demisto_sdk.commands.common.constants imp... |
1621962 | from circus.controller import Controller as _Controller
from circus.green.sighandler import SysHandler
from zmq.green.eventloop import ioloop, zmqstream
class Controller(_Controller):
def _init_syshandler(self):
self.sys_hdl = SysHandler(self)
def _init_stream(self):
self.stream = zmqstream... |
1621967 | import pyclesperanto_prototype as cle
import numpy as np
def test_touch_matrix_to_mesh():
gpu_touch_matrix = cle.push(np.asarray([
[0, 0, 0],
[0, 0, 0],
[0, 1, 0]
]))
gpu_point_list = cle.push(np.asarray([
[1, 4],
... |
1622129 | from OpenGL.GL import *
from OpenGL.error import NullFunctionError
class Framebuffer:
def __init__(self):
self.FBO = glGenFramebuffers(1)
def checkComplete(self):
if glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE:
raise RuntimeError('Error when creating... |
1622144 | import yaml
import os
import sys
dir = sys.argv[1]
files = os.listdir(dir)
def process(filename):
print("Processing %s" % filename)
(base, ext) = os.path.splitext(filename)
ICONV='iconv -f iso8859-1 -t utf-8 "%(base)s%(ext)s" > "%(base)s.utf8%(ext)s"' % vars()
print("Running",ICONV)
os.system(ICONV)
... |
1622155 | import os
import openpyxl
import pytest
from openpyxl import load_workbook
from viadot.tasks.open_apis.uk_carbon_intensity import StatsToCSV, StatsToExcel
TEST_FILE_PATH = "/home/viadot/tests/uk_carbon_intensity_test.csv"
TEST_FILE_PATH_EXCEL = "/home/viadot/tests/uk_carbon_intensity_test.xlsx"
@pytest.fixture(sco... |
1622158 | import asyncio
import json
from pathlib import Path
import pytest
from fastapi import APIRouter, FastAPI
from httpx import AsyncClient
from meilisearch_python_async import Client
from meilisearch_python_async.task import wait_for_task
from meilisearch_fastapi._config import get_config
from meilisearch_fastapi.routes ... |
1622172 | import os, sys
os.system('pkg install tor')
os.system('pip2 install torrequest')
os.system('pip2 install urllib')
os.system('pip2 install bs4')
os.system('pip2 install requests')
os.system('python2 blog_pack.py')
|
1622213 | import socket
import re
def validateipv4ip(address):
try:
socket.inet_aton(address)
except socket.error:
print ("wrong IPv4 IP",address)
def validateipv6ip(address):
### for IPv6 IP address validation
try:
socket.inet_pton(socket.AF_INET6,address)
except socket.error:
... |
1622289 | from nes_py import NESEnv
import tqdm
env = NESEnv('./nes_py/tests/games/super-mario-bros-1.nes')
done = True
try:
for i in tqdm.tqdm(range(5000)):
if done:
state = env.reset()
done = False
else:
state, reward, done, info = env.step(env.action_space.sample())
... |
1622300 | from adventofcode.util.helpers import grid_to_string
from adventofcode.year_2021.day_25_2021 import part_one, get_values, do_step
test_input = [
'v...>>.vv>',
'.vv>>.vv..',
'>>.>v>...v',
'>>v>>.>.v.',
'v>v.vv.v..',
'>.>>..v...',
'.vv..>.>v.',
'v.v..>>v.v',
'....v..v.>',
]
step_1 = ... |
1622317 | from PIL import Image
import pytest
from yoga.image.encoders import webp
from yoga.image.encoders import webp_lossless
class Test_is_lossless_webp(object):
def test_with_lossy_webp(self):
image_bytes = open("test/images/alpha.lossy.webp", "rb").read()
assert webp_lossless.is_lossless_webp(image_b... |
1622342 | from pudzu.charts import *
from pudzu.sandbox.bamboo import *
from PIL import ImageEnhance
df = pd.read_csv("datasets/euchristmas.csv").set_index("country")
FONT = sans
PALETTE = {
"D25": VegaPalette10.BLUE,
"J7": VegaPalette10.GREEN,
"J6": VegaPalette10.ORANGE,
"N": VegaPalette10.RED
}
DESCRIPTIONS =... |
1622354 | from data_reader import OneWorldAllEntityinKBIterateLoader
from utils import oneworld_entiredataset_loader_for_encoding_entities, KBIndexerWithFaiss, BiEncoderTopXRetriever
from utils import parse_duidx2encoded_emb_2_dui2emb
from model import WrappedModel_for_entityencoding
from encoders import InKBAllEntitiesEncoder, ... |
1622357 | import base64
import hashlib
from django import template
register = template.Library()
@register.simple_tag
def ssh_to_fingerprint(line):
try:
key = base64.b64decode(line.strip().split()[1].encode('ascii'))
fp_plain = hashlib.md5(key).hexdigest()
return ':'.join(a + b for a, b in zip(fp_... |
1622358 | from bs4 import BeautifulSoup
import requests
source = requests.get('http://www.example.com/').text
soup = BeautifulSoup(source, 'lxml') # Using lxml => Run pip install lxml
# Find with <div> tag
article = soup.find('div')
print(article.prettify())
# Grab a Class
summary = article.find('div', class_='entry_content')... |
1622364 | import json
import time
import random
import paho.mqtt.client as mqtt
from . import Adaptor
class MQTTAdaptor(Adaptor):
""" Provide pubsub events over MQTT """
key = 'mqtt'
connected = False
loop_started = False
callbacks = {}
def connect(self):
""" Make mqtt connection and setup br... |
1622408 | version_info = (6, 3, 4, 'dev0')
__version__ = '.'.join(map(str, version_info))
kernel_protocol_version_info = (5, 1)
kernel_protocol_version = '%s.%s' % kernel_protocol_version_info
|
1622451 | from gym.spaces import Box
from ray.rllib.agents.dqn.distributional_q_tf_model import \
DistributionalQTFModel
from ray.rllib.agents.dqn.dqn_torch_model import \
DQNTorchModel
from ray.rllib.models.tf.fcnet import FullyConnectedNetwork
from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFC
f... |
1622480 | from fairness.metrics.Metric import Metric
class Diff(Metric):
def __init__(self, metric1, metric2):
Metric.__init__(self)
self.metric1 = metric1
self.metric2 = metric2
self.name = "diff:" + self.metric1.get_name() + 'to' + self.metric2.get_name()
def calc(self, actua... |
1622483 | import os
import sys
import mock
import pytest
from program_synthesis.karel import arguments
from program_synthesis.karel.dataset import dataset
from program_synthesis.karel.dataset import edit_data_loader
from program_synthesis.karel.models import karel_edit_model
@pytest.fixture
def args():
with mock.patch('s... |
1622497 | import numpy as np
import matplotlib.pyplot as plt
def insert_zeros(trace, tt=None):
"""Insert zero locations in data trace and tt vector based on linear fit"""
if tt is None:
tt = np.arange(len(trace))
# Find zeros
zc_idx = np.where(np.diff(np.signbit(trace)))[0]
x1 = tt[zc_idx]
x2... |
1622528 | from django.test import TestCase
from django.test.client import Client
from core.group.models import Group
from mozdns.tests.utils import create_fake_zone
from core.registration.static.models import StaticReg
from systems.tests.utils import create_fake_host
class KVApiTests(TestCase):
def setUp(self):
s... |
1622650 | import spacy
# Importe le Matcher
from spacy.____ import ____
nlp = spacy.load("fr_core_news_sm")
doc = nlp("Le constructeur Citröen présente la e-Méhari Courrèges au public.")
# Initialise le matcher avec le vocabulaire partagé
matcher = ____(____.____)
# Crée un motif qui recherche les deux tokens : "e-Méhari" et... |
1622711 | import subprocess
import sys
from distutils.version import LooseVersion
reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
installed_packages = [r.decode().split('==')[0] for r in reqs.split()]
if 'torch' in installed_packages:
from rlcard.agents.dqn_agent import DQNAgent as DQNAgent
from... |
1622716 | import cv2
import numpy as np
import caffe
def get_landmark_net():
net_file = './landmark.prototxt'
caffe_model = './landmark.caffemodel'
caffe.set_mode_gpu()
net = caffe.Net(net_file, caffe_model, caffe.TEST)
return net
def get_pose_landmarks(net , img):
halfheight = img.shape[0] * 0.5
... |
1622730 | import numpy as np
from toolkit.methods.pnpl import CvxPnPL, DLT, EPnPL, OPnPL
from toolkit.suites import parse_arguments, PnPLReal
from toolkit.datasets import Linemod, Occlusion
# reproducibility is a great thing
np.random.seed(0)
np.random.seed(42)
# parse console arguments
args = parse_arguments()
# Just a lo... |
1622757 | from collections import Counter, defaultdict
from typing import Dict
from allennlp.data.instance import Instance
from allennlp.data.fields import Field, TextField, LabelField, SequenceLabelField
from allennlp.data.token_indexers import TokenIndexer, SingleIdTokenIndexer
from allennlp.data.tokenizers import Token
from ... |
1622760 | import json
import os
import pytz
def _bool_convert(value):
truthy = {"t", "true", "on", "y", "yes", "1", 1, 1.0, True}
falsy = {"f", "false", "off", "n", "no", "0", 0, 0.0, False}
if isinstance(value, str):
value = value.lower()
if value in truthy:
return True
if value in falsy:
... |
1622761 | import numpy as np
fwhm_m = 2 * np.sqrt(2 * np.log(2))
def fwhm(sigma):
"""
Get full width at half maximum (FWHM) for a provided sigma /
standard deviation, assuming a Gaussian distribution.
"""
return fwhm_m * sigma
def gaussian(x_mean, x_std, shape):
return np.random.normal(x_mean, x_... |
1622781 | import unittest
import asyncio
import dns.resolver
import os
COLLECTOR_USER = os.getenv('COLLECTOR_USER')
if COLLECTOR_USER is None:
COLLECTOR_USER = "root"
my_resolver = dns.resolver.Resolver(configure=False)
my_resolver.nameservers = ['127.0.0.1']
my_resolver.port = 5553
my_resolver.timeout = 20
my_resolver.li... |
1622791 | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
__all__ = ['get_drug_target_data', 'LincsClient', 'load_lincs_csv']
import os
import sys
import json
import logging
import requests
from io import StringIO, BytesIO
from indra.util import read_unicode_csv_fileobj
f... |
1622851 | from django.urls import reverse
from django.conf import settings
from django.contrib.auth.hashers import check_password
from django.core.mail import EmailMultiAlternatives
from rest_framework import status
from restapi import models
from .base import APITestCaseExtended
from ..utils import decrypt_with_db_secret, get_... |
1622878 | import os
import numpy as np
import matplotlib.pyplot as plt
from . import helper_generic as hlp
from . import helper_site_response as sr
from . import helper_signal_processing as sig
from PySeismoSoil.class_frequency_spectrum import Frequency_Spectrum as FS
from PySeismoSoil.class_Vs_profile import Vs_Profile
class... |
1622880 | import random
from tree import AVLTree, SDPTree, GraphicalTree
avl_tree = AVLTree()
# sdp_tree = SDPTree()
random.seed(0)
# arr = random.sample(range(100), 100)
arr = range(10)
for i in arr:
avl_tree.add(10 - i)
# sdp_tree.add_sdp_rec(i)
g_tree = GraphicalTree(avl_tree, "Mega_tree", 1920, 1080)
print("n=100... |
1622895 | import os
import tempfile
import unittest
from pyepw.epw import Comments1, EPW
class TestComments1(unittest.TestCase):
def setUp(self):
self.fd, self.path = tempfile.mkstemp()
def tearDown(self):
os.remove(self.path)
def test_create_comments_1(self):
obj = Comments1()
v... |
1622914 | import torch
import itertools
from .cut_semantic_mask_model import CUTSemanticMaskModel
from . import networks
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
from .modules import loss
from util.iter_calculator import IterCalculator
from util.network_group import NetworkGroup
cla... |
1622962 | class WorkflowTranslator(object):
"""Base class for translators."""
def __init__(self):
pass
def translate(self, wf):
raise NotImplementedError("Needs implementation in derived classes.")
@staticmethod
def get_translator(service_name):
from popper.translators.translator_dr... |
1622963 | from google.cloud import storage
import gcsfs
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.externals import joblib
import pandas as pd
import numpy as np
from time import time
import re
cleanup_re = re.compile('[^a-z]+')
def cleanup(sen... |
1622976 | from django.conf.urls import url
from experiments import views
urlpatterns = [
url(r'^goal/(?P<goal_name>[^/]+)/(?P<cache_buster>[^/]+)?$', views.record_experiment_goal, name="experiment_goal"),
url(r'^confirm_human/$', views.confirm_human, name="experiment_confirm_human"),
url(r'^change_alternative/(?P<ex... |
1623017 | from unittest import TestCase
from collections import namedtuple
import rx
from cyclotron import Component
from cyclotron.rx import run
class RunnerTestCase(TestCase):
def test_run_1snk(self):
''' Creates a cycle with one sink driver.
'''
MainDrivers = namedtuple('MainDrivers', ['drv1'])... |
1623053 | import typing
import numpy as np
import pytest
from ebonite.core.objects import Model, ModelWrapper
from ebonite.core.objects.artifacts import Blobs
from ebonite.core.objects.core import EvaluationResults
from ebonite.core.objects.metric import Metric
from ebonite.core.objects.wrapper import PickleModelIO
class Eva... |
1623064 | from ..factory import Method
class setCustomLanguagePack(Method):
info = None # type: "languagePackInfo"
strings = None # type: "vector<languagePackString>"
|
1623066 | import redis
from board import Board
class RedisBoard(Board):
"""This will create a message board that is backed by Redis."""
def __init__(self, *args, **kwargs):
"""Creates the Redis connection."""
self.redis = redis.Redis(*args, **kwargs)
def set_owner(self, owner):
self.owner ... |
1623078 | import numpy as np
from rllab.core.serializable import Serializable
from rllab.exploration_strategies.base import ExplorationStrategy
from sandbox.rocky.tf.spaces.box import Box
from sandbox.gkahn.gcg.utils import schedules
class GaussianStrategy(ExplorationStrategy, Serializable):
"""
Add gaussian noise
... |
1623090 | import os
import json
import luigi
from . import check_components as component_tasks
from ..cluster_tasks import WorkflowBase
from ..paintera import unique_block_labels as unique_tasks
from ..paintera import label_block_mapping as mapping_tasks
from ..utils import volume_utils as vu
# TODO fail if check does not pas... |
1623099 | import sys,os
import pandas as pd
import fnmatch
import pyarrow as pa
import pyarrow.parquet as pq
import datetime
defaultcols=['store_code_uc','upc','units','price','feature','display','dma_code','retailer_code','upc_ver_uc','week_end']
# This is the main interface
# This pre-processes files directly downloaded from... |
1623105 | import ipaddress
import re
from django.contrib import messages
from django.contrib.admin.options import IncorrectLookupParameters
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from ralph.admin.filters import (
ChoicesListFilter,
SEARCH_OR_SEPARATORS_REGEX,
TextListF... |
1623135 | import FWCore.ParameterSet.Config as cms
dtTTrigResidualCorrection = cms.EDAnalyzer("DTTTrigCorrection",
dbLabel = cms.untracked.string(''),
correctionAlgo = cms.string('DTTTrigResidualCorrection'),
correctionAlgoConfig = cms.PSet(
residualsRootFile = cms.string(''),
#rootBaseDir = cms.untr... |
1623158 | import logging
from typing import Optional, Union
from redbot.core import commands, bank
from redbot.core.i18n import Translator
from redbot.core.commands import Context
from .converter import RoleHierarchyConverter
from .abc import RoleToolsMixin, roletools
log = logging.getLogger("red.Trusty-cogs.RoleTools")
_ = T... |
1623160 | import sys
from .helper import PillowTestCase
from PIL import Image
X = 255
class TestLibPack(PillowTestCase):
def assert_pack(self, mode, rawmode, data, *pixels):
"""
data - either raw bytes with data or just number of bytes in rawmode.
"""
im = Image.new(mode, (len(pixels), 1... |
1623164 | from will.utils import warn
from will.backends.storage.redis_backend import RedisStorage
warn(
"""Deprecation - will.storage.redis_storage has been moved to will.backends.storage.redis_backend,
and will be removed in version 2.2. Please update your paths accordingly!"""
)
|
1623205 | import unittest
from katas.beta.find_the_middle_element import gimme
class GimmeTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(gimme([2, 3, 1]), 0)
def test_equals_2(self):
self.assertEqual(gimme([5, 10, 14]), 1)
|
1623216 | import megengine.module as M
import megengine.functional as F
class FlowHead(M.Module):
def __init__(self, input_dim=128, hidden_dim=256):
super(FlowHead, self).__init__()
self.conv1 = M.Conv2d(input_dim, hidden_dim, 3, padding=1)
self.conv2 = M.Conv2d(hidden_dim, 2, 3, padding=1)
... |
1623220 | from __future__ import absolute_import
import inspect
import types
import warnings
import weakref
from functools import partial
from logging import getLogger
from eventlet.event import Event
from nameko.exceptions import IncorrectSignature
_log = getLogger(__name__)
ENTRYPOINT_EXTENSIONS_ATTR = 'nameko_entrypoin... |
1623337 | import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
import os
file_path = os.path.dirname(__file__)
sys.path.append(os.path.join(file_path, '../../super_module'))
sys.path.append(os.path.join(file_path, '../'))
sys.path.append(file_path)
import super_class
import mobilenetv2_super
import mobil... |
1623344 | from nitorch import spatial, io
from nitorch.core import py, dtypes
import torch
import os
def convert(inp, meta=None, dtype=None, casting='unsafe', format=None, output=None):
"""Convert a volume.
Parameters
----------
inp : str
A path to a volume file.
meta : sequence of (key, value)
... |
1623357 | import pygame as pg
class CoinDebris(object):
"""
Coin that appears when you hit the question block.
"""
def __init__(self, x_pos, y_pos):
self.rect = pg.Rect(x_pos, y_pos, 16, 28)
self.y_vel = -2
self.y_offset = 0
self.moving_up = True
self.current_image = ... |
1623370 | from mock import MagicMock
import pyaem
from pyaem import bagofrequests as bag
import unittest
from .util import HandlersMatcher
class TestPackageManager(unittest.TestCase):
def setUp(self):
self.package_manager = pyaem.packagemanager.PackageManager('http://localhost:4502', debug=True)
bag.reque... |
1623417 | import pytest
import pglet
from pglet import Link, Text
'''
def test_button_primary_must_be_bool():
with pytest.raises(Exception):
Button(id="button1", text="My button", primary="1")
'''
def test_link_add():
l = Link(value="search", url="http://google.com", align="left", new_window=True)
assert i... |
1623425 | r"""
Solve Ginzburg-Landau equation on (-50, 50)x(-50, 50) with periodic bcs
u_t = div(grad(u)) + u - (1+1.5i)*u*|u|**2 (1)
Use Fourier basis V and find u in VxV such that
(v, u_t) = (v, div(grad(u))+ u) - (v, (1+1.5i)*u*|u|**2) for all v in VxV
"""
from sympy import symbols, exp
import matplotl... |
1623497 | import pytest
import numpy as np
import time
from ding.utils.time_helper import build_time_helper, WatchDog, TimeWrapperTime, EasyTimer
@pytest.mark.unittest
class TestTimeHelper:
def test_naive(self):
class NaiveObject(object):
pass
cfg = NaiveObject()
setattr(cfg, 'common'... |
1623517 | from cx_Oracle import CLOB
from django.contrib.gis.db.backends.base.adapter import WKTAdapter
from django.contrib.gis.geos import GeometryCollection, Polygon
class OracleSpatialAdapter(WKTAdapter):
input_size = CLOB
def __init__(self, geom):
"""
Oracle requires that polygon rings are in prop... |
1623529 | import customers as c
import util as u
matrix = [[]]
silhouettesList = []
centroids = []
def __init__(mat, cents):
global matrix
matrix = mat
global centroids
centroids = cents
def averageSilhouettes(clusters, matrix, centroids):
__init__(matrix, centroids)
silhouettes = 0.0
for i ... |
1623556 | import taco.common.exceptions
class AutoScalerWrapperException(taco.common.exceptions.DataDictException):
pass
# --- Table ---
class TargetRegistrationException(AutoScalerWrapperException):
def __init__(self, service_namespace, resource_id, exc):
super().__init__('Failed to register auto scaler',
... |
1623614 | from django.core.exceptions import ValidationError
from django.test import TestCase
from kolibri.core.device.models import DeviceSettings
from kolibri.core.utils.cache import process_cache as cache
class DeviceSettingsTestCase(TestCase):
def test_singleton(self):
cache.clear()
DeviceSettings.obje... |
1623624 | import os
class IMDB(object):
def __init__(self, benchmark_name, image_subset_name, dataset_path, cache_path=None):
"""
basic information about an image database
:param name: name of image database will be used for any output
:param dataset_path: dataset path store images and image... |
1623636 | import rematbal.matbal as mb
import numpy as np
from scipy.optimize import fsolve
import pandas as pd
def mbal_inner_calc(dict, P, Pres_calc, We, aquifer_pres, step):
Np, Wp, Gp, N, Wei, pvt_oil_pressure, pvt_oil_Bo, pvt_oil_Bg, pvt_oil_Rs, Rsb, \
Bti, Bgi, Pi, m, Boi, cw, Swi, cf, Rsi, Bw, Winj, Bwinj, Ginj, ... |
1623649 | import ast
import csv
import io
import json
import logging
import os
from datetime import datetime
from typing import Dict, Any
import xmind
from dateutil.parser import parse as parse_datetime_str
from jinja2 import Template
from .checking import SUPPORTED_IDS
from .result import QueryStatus
from .sites import Maigre... |
1623684 | import FWCore.ParameterSet.Config as cms
process = cms.Process("dump")
process.load("L1TriggerConfig.RPCTriggerConfig.L1RPCHsbConfig_cff")
process.l1RPCHsbConfig.hsb0Mask=cms.vint32(0, 1, 2, 3, 0, 1, 2, 3)
process.l1RPCHsbConfig.hsb1Mask=cms.vint32(1, 2, 3, 0, 1, 2, 3, 0)
#useGlobalTag = 'IDEAL_31X'
#process.load('C... |
1623715 | from scipy import interpolate
from pylab import *
from skimage import color
Rg, Gg, Bg = (207., 40., 57.)
texture_input = 'texture1.jpg'
def get_boundary_points(x, y):
tck, u = interpolate.splprep([x, y], s=0, per=1)
unew = np.linspace(u.min(), u.max(), 1000)
xnew, ynew = interpolate.splev(unew, tck, de... |
1623820 | import logging
import re
from django.apps import apps
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.contrib.admin import AdminSite
from django.contrib.admin.models import LogEntry
from django.contrib.admin.views.main import Chan... |
1623829 | from turbogears.database import PackageHub
# import some basic SQLObject classes for declaring the data model
# (see http://www.sqlobject.org/SQLObject.html#declaring-the-class)
from sqlobject import SQLObject, SQLObjectNotFound, RelatedJoin
# import some datatypes for table columns from SQLObject
# (see http://www.sql... |
1623830 | from typing import Iterator
def func(x: int):
"""Function."""
def gen() -> Iterator[int]:
"""Generator."""
yield 1
class C:
"""Class."""
|
1623862 | import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
import os
import suds
from suds.client import Client
from suds.sax.element import Element
import urllib
import urlparse
import base64
from datetime import date
try:
from pysimplesoap.client import SoapClient
except:
# Ju... |
1623872 | from typing import Optional, Union, Callable
import numpy as np
from caput import memh5
from cora.util.cosmology import Cosmology
from cora.util import units, cubicspline as cs
from draco.core import containers
from ..util.nputil import FloatArrayLike
class InterpolatedFunction(memh5.BasicCont):
"""A containe... |
1623910 | from tardis.utilities.simulators.periodicvalue import PeriodicValue
from unittest import TestCase
import yaml
class TestPeriodicValue(TestCase):
def setUp(self) -> None:
self.simulator = PeriodicValue(period=3600, amplitude=0.5, offset=0.5, phase=0)
def test_get_value(self):
self.assertIsIns... |
1623930 | import importlib
import time
from abc import ABCMeta, abstractmethod
import numpy as np
from scipy.spatial.distance import jensenshannon
from scipy.stats import gaussian_kde
from ..core.prior import PriorDict
from ..core.sampler.base_sampler import SamplerError
from ..core.utils import logger, reflect
from ..gw.sourc... |
1623936 | from datetime import datetime
from aiogithub import objects
from aiogithub.objects.response import BaseResponseObject
from aiogithub.utils import return_key
class ReviewComment(BaseResponseObject):
_url = 'repos/{login}/{repo}/pulls/comments/{id}'
@staticmethod
def _get_key_mappings():
return {
... |
1623959 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.cross_decomposition import CCA
from sklearn.metrics import confusion_matrix
import functools
def find_correlation_cca_method1(signal, reference_signals, n_components=2):
r"""
Perform canonical correlation analysis (CCA)
Reference: https://git... |
1623981 | import argparse
import tensorflow as tf
import json
import numpy as np
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
import sys
from scipy import stats
import time
import h5py
import matplotlib.pyplot as plt
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.