id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3278080 | import json
import os
import re
import requests
from bs4 import BeautifulSoup
from flask import Flask, redirect, render_template, request, url_for
from urllib.parse import quote_plus, urlencode
app = Flask(__name__)
CLIENT_ID = os.environ['CLIENT_ID']
CLIENT_SECRET = os.environ['CLIENT_SECRET']
REDIRECT_URI = os.envi... |
3278087 | from ac_utils.general import vfkp
def exact_match(data, method, sound_ids=None):
"""
Compares the estimated note with the reference note expecting an exact match
:param data: sound data with annotations and analysis
:param method: analysis algorithm name to compare with annotation
:param sound_ids... |
3278095 | import numpy as np
import theano as th
import theano.tensor as tt
import theano.tensor.signal.conv as sigconv
from .layer import Layer
float_x = th.config.floatX
# ############################## Input Layer ##################################
class InputLayer(Layer):
def __init__(self, inpt, img_sz, num_maps=1,... |
3278135 | import logging, os, time
import subprocess
from diana.apis import Orthanc
from diana.utils.endpoint import Containerized as C
from utils import find_resource
import pytest
# TODO: Broken and needs attention...
@pytest.mark.skip(reason="Unknown change to swarm manager?")
def test_mock_svcs():
C.start_swarm()
... |
3278158 | from yeadon.human import Human
from yeadon.ui import start_ui
from yeadon.version import __version__
try:
import mayavi
except ImportError:
pass
else:
del mayavi
from yeadon.gui import start_gui
|
3278195 | import unittest
from main import one, two
instructions = [
"forward 5",
"down 5",
"forward 8",
"up 3",
"down 8",
"forward 2",
]
class TestOne(unittest.TestCase):
def test_simple(self):
self.assertEqual(150, one(instructions))
class TestTwo(unittest.TestCase):
def test_simpl... |
3278237 | import collections as _collections
import itertools as _itertools
import six as _six
def flatten(gen):
"""Flatten an iterable.
>>> flat = flatten([(1, 2, 3), [4, 5, 6], range(7, 10)])
>>> list(flat)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
return _itertools.chain.from_iterable(gen)
def recursive_f... |
3278250 | import datetime
from .queueviastacks import QueueViaStack
class Animal:
def __init__(self, name):
self.name = name
self.arrival_time = datetime.datetime.now()
def __repr__(self):
return f"Animal({self.name})"
class Cat(Animal):
def __init__(self, name):
super().__init__... |
3278313 | from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
import logging
from typing import Dict, Any, cast
from pathlib import Path
import shutil
from scrapli import Scrapli
from scrapli.driver import NetworkDriver
from constants import USERNAME, PASSWORD, DEVICES
# logging.basicConfig(level="... |
3278333 | from ..qt.QtWebKit import QWebView, QWebSettings
from qt_ace_editor import QtAceEditor
class QtAceEditorView(QWebView):
def __init__(self, parent=None):
""" Initialize the editor window
"""
super(QtAceEditorView, self).__init__(parent)
self.ace_editor = QtAceEditor()
# XX... |
3278359 | from stix_shifter_utils.modules.base.stix_transmission.base_connector import BaseQueryConnector
class QueryConnector(BaseQueryConnector):
def __init__(self, api_client):
self.api_client = api_client
def create_query_connection(self, query):
return {"success": True, "search_id": query}
|
3278369 | import io
import os
import shutil
import subprocess
import tempfile
# An example of how to use LibreOffice and ImageMagick to convert WMF images to
# PNGs.
#
# libreoffice_wmf_conversion uses LibreOffice to convert the image to a PNG.
# This normally creates an image with a large amount of padding, so
# imagemagick_t... |
3278451 | import os
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from mock import patch
from .utils import override_settings
__all__ = ["BaseFinderTest", "FilesystemFinderTest", "AppFinderTest",
"FilesystemRegexFinderTest"]
here = os.path.abspath(os.path.dirname(os.p... |
3278475 | from .. import util
import duo_client.admin
from .base import TestAdmin
class TestUserTokens(TestAdmin):
def test_get_user_tokens_iterator(self):
""" Test to get tokens iterator by user id.
"""
generator = self.client_list.get_user_tokens_iterator(
'DU012345678901234567')
... |
3278477 | from . import database_writer_devtools
class DatabasePageWriter(object):
def __init__(self, db_connection, page_id, url):
self.conn = db_connection
self.page_id = page_id
self.url = url
def get_page_id(self):
return self.page_id
def get_url(self):
return self.url
... |
3278520 | from .nms_rotated_wrapper import obb_batched_nms, obb_nms, poly_nms
__all__ = ['obb_batched_nms', 'obb_nms', 'poly_nms']
|
3278521 | import os
import glob
class OsFs():
"""
Emulate filesystem API of pymongo (gridfs) on with standard os module
(since this project used gridfs during development).
Note: Only emulates the commands required in this project
"""
def __init__(self, base_path):
"""
:param base_path... |
3278531 | import os, sys
import constants
import utils
# -----------------------------------------------------------
# class Tile
# -----------------------------------------------------------
class Tile:
def __init__(self, mydict):
self.index = mydict["index"]
self.name = mydict["name"]... |
3278550 | from future.utils import iteritems
import pytest
import unittest
import numpy as np
import pyqg
from pyqg import diagnostic_tools as diag
def test_describe_diagnostics():
""" Test whether describe_diagnostics runs without error """
m = pyqg.QGModel(1)
m.describe_diagnostics()
def test_paramspec_diagnosti... |
3278559 | import this
import Levenshtein
import numpy as np
from scipy.fftpack import fft
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from tqdm import tqdm
hello = 'world'
np.array([1, 2, 3], dtype=int)
load_iris(True)
fft()
print('')
tqdm()
Levenshtein.jaro()
r = RandomForestClas... |
3278604 | import os
import sys
import pytest
import haystack
from rest_framework.test import APIClient
from django.core.management import call_command
from unittest.mock import patch, Mock
from readme.models import User, Item
from django.conf import settings
def pytest_configure():
# workaround to avoid django pipeline i... |
3278647 | import FWCore.ParameterSet.Config as cms
simHitTPAssocProducer = cms.EDProducer("SimHitTPAssociationProducer",
simHitSrc = cms.VInputTag(cms.InputTag('g4SimHits','MuonDTHits'),
cms.InputTag('g4SimHits','MuonCSCHits'),
cms.InputTag('g4SimHits','MuonRPCHits'),
... |
3278681 | from typing import Any
from typing_extensions import Literal
from enum import auto
from anndata import AnnData
from cellrank import logging as logg
from cellrank._key import Key
from cellrank.tl._enum import ModeEnum
from cellrank.ul._docs import d, inject_docs
from cellrank.tl._utils import _correlation_test_helper
... |
3278732 | from models.gwcnet import GwcNet_G, GwcNet_GC
from models.loss import model_loss
__models__ = {
"gwcnet-g": GwcNet_G,
"gwcnet-gc": GwcNet_GC
}
|
3278734 | import os
import numpy as np
from PIL import Image
import cv2
import _pickle as cPickle
import numpngw
import open3d as o3d
import matplotlib.pyplot as plt
data_list_file = '/home/pwl/Work/Dataset/NOCS/nocs/Real/test_list_all.txt'
data_path = '/home/pwl/Work/Dataset/NOCS/nocs/Real/'
result_path = '/home/pwl/Work/Dat... |
3278746 | import numpy as np
import os
CLASS_PATH = os.path.dirname(os.path.realpath(__file__))
DATASET_PATH = os.environ.get('DATASET_PATH', os.path.join(CLASS_PATH, '..', 'data'))
class CubicSetup:
exp_id = 0
n_nodes_phi = 64
n_nodes_theta = 96
graph_building_names = ['get_agj_matrix_for_cubemap']
# trai... |
3278774 | from cartodb_services.google.geocoder import GoogleMapsGeocoder
from cartodb_services.google.bulk_geocoder import GoogleMapsBulkGeocoder
|
3278788 | from __future__ import annotations
import pytest
from _pytest.monkeypatch import MonkeyPatch
import hypercorn.config
from hypercorn.typing import HTTPScope
@pytest.fixture(autouse=True)
def _time(monkeypatch: MonkeyPatch) -> None:
monkeypatch.setattr(hypercorn.config, "time", lambda: 5000)
@pytest.fixture(nam... |
3278817 | from __future__ import absolute_import
import os
from dataverse.settings import BASE_PATH
PICS_OF_CATS_DATASET = {
"id": "1",
"title": "This Study is about Pictures of Cats",
"author": "<NAME>",
"description": "In this study we prove there can be pictures of cats.",
}
ATOM_DATASET = os.path.join(BAS... |
3278825 | import helper
import swaggeraem
from swaggeraem.rest import ApiException
import unittest
class TestClient(unittest.TestCase):
def setUp(self):
swaggeraem.configuration.username = 'someinexistingusername'
swaggeraem.configuration.password = '<PASSWORD>'
client = swaggeraem.ApiClient('http:/... |
3278909 | import json
from textwrap import dedent
class TestRemoveHostStorageController:
def test_no_args(self, host):
result = host.run('stack remove host storage controller')
assert result.rc == 255
assert result.stderr == dedent('''\
error - "host" argument is required
{host ...} {slot=integer} [adapter=integer... |
3278914 | import util
class test_bincount:
def init(self):
for dtype in util.TYPES.SIGNED_INT:
for shape in util.gen_shapes(1, 100, min_ndim=1, iters=5):
cmd = "R = bh.random.RandomState(42); "
cmd += "a=R.random_integers(0, high=100, size=%d, dtype=%s, bohrium=BH);" % (s... |
3278921 | import os
import unittest
import numpy
import pytest
from mpi4py import MPI
from pauxy.systems.generic import Generic
from pauxy.systems.utils import get_generic_integrals
from pauxy.utils.testing import generate_hamiltonian
@pytest.mark.unit
def test_real():
numpy.random.seed(7)
nmo = 17
nelec = (4,3)
... |
3278936 | from django.db import models
from django.utils.translation import gettext_lazy as _
from web.multilingual.modelfields import MultiLingualRichTextUploadingField
class ContentBox(models.Model):
title = models.CharField(
max_length=100,
unique=True,
verbose_name=_("Title"),
)
content... |
3278937 | import time
from typing import Optional
from popupdict.gtk import *
from popupdict.query import QueryResult
from popupdict.util import Selection, logger
from .widgets import Widgets
# 弹窗
class Popup(Gtk.Window):
WINDOW_WIDTH = 400 # type: int
def __init__(self, popup_timeout: float = None, auto_play: bool ... |
3278956 | from __future__ import print_function
# third party libraries
from theano.tensor import matrix, lvector
from opendeep.log.logger import config_root_logger
from opendeep.models import Prototype, Dense, Softmax
from opendeep.optimization import AdaDelta
from opendeep.optimization.loss import Neg_LL
from opendeep.data imp... |
3278987 | from __future__ import absolute_import
from itertools import product
from six.moves import map
from functools import total_ordering
cnfClass = None
@total_ordering
class Variable(object):
def __init__(self, name, inverted=False):
self.name = name
self.inverted = inverted
def __neg__(self):
... |
3279024 | import os
import sys
import numpy as np
import random
from tqdm import tqdm
import matplotlib.pyplot as plt
from scipy import ndimage
from mpl_toolkits.mplot3d import Axes3D
from multiprocessing import Pool
import matplotlib.pyplot as plt
from glob import glob
from PIL import Image, ImageOps
import time
import psuti... |
3279027 | import os
import shutil
from django.conf import settings
from django_dynamic_fixture import G
from django_webtest import WebTest
from icekit.utils import testing
from icekit.tests.models import ImageTest
from icekit.utils.sequences import slice_sequences
from icekit.utils.pagination import describe_page_numbers, pars... |
3279030 | import numpy as np
class KalmanFilter(object):
def __init__(self, dim=2, dt=1., uncertainty_x=0.05, uncertainty_v=0.00625):
# For x: [x1, x2, ..., vx1, vx2, ...], where vx is velocity of change in x
# For z: [z1, z2, ...]
self.dim = dim
self.uncertainty_x = uncertainty_x
s... |
3279043 | from datetime import date
from mock import ANY, Mock, mock_open, patch
from nose.tools import eq_
from oauth2client.client import Error as OAuth2Error
from affiliates.base.tests import TestCase
from affiliates.links.google_analytics import AnalyticsError, AnalyticsService
class AnalyticsServiceTests(TestCase):
... |
3279053 | import os
import warnings
from enum import Enum
from wandb.errors import Error as WandbError
_API_KEY_WARNING_ISSUED = False
_SILENCE_WARNING_ISSUED = False
def is_missing_artifact_error(err: WandbError):
"""
Check if a specific W&B error is caused by a 404 on the artifact we're looking for.
"""
# T... |
3279066 | import json
import yaml
import os
from collections import OrderedDict
import re
def get_extension(file):
return os.path.splitext(file)[1]
def load(input_file_path):
''' Load schema file based on extension and return resulting dictionary. '''
ext = get_extension(input_file_path).lower()
if (ext == '.j... |
3279079 | from streamlink.plugins.tvp import TVP
from tests.plugins import PluginCanHandleUrl
class TestPluginCanHandleUrlTVP(PluginCanHandleUrl):
__plugin__ = TVP
should_match = [
'http://tvpstream.vod.tvp.pl/?channel_id=14327511',
'http://tvpstream.vod.tvp.pl/?channel_id=1455',
]
should_not_... |
3279087 | import pandas as pd
# Set Pandas display options for easier reading
pd.set_option("max_colwidth", 100)
pd.set_option("display.max_rows", 1000)
pd.set_option("display.max_columns", 9001) # there is a scrollbar and '...' just looks stupid
pd.set_option('display.float_format', lambda x: '{:,.2f}'.format(x))
|
3279099 | from spartan.util.basicutil import param_default
from .Beatlex import BeatLex
def __call__():
return BeatLex
|
3279114 | import os
import re
def create_results_dir():
results_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../results')
os.makedirs(results_root, exist_ok=True)
max_num = -1
for root, subdirs, files in os.walk(results_root):
for subdir in subdirs:
numbers = re.finda... |
3279133 | from typing import Optional
from fpipe.file.file import File
from fpipe.meta.bucket import Bucket
from fpipe.meta.path import Path
from fpipe.meta.version import Version
from fpipe.meta.prefix import Prefix
class S3File(File):
def __init__(self, bucket: str, key: str, version: Optional[str] = None):
supe... |
3279190 | import random
import numpy as np
import cv2
from PIL import Image
from PIL import ImageFilter
import PIL
import tifffile
def cv_rotate(image, angle, borderValue):
"""
rot angle, fill with borderValue
"""
# grab the dimensions of the image and then determine the
# center
(h, w) = image.shape[:... |
3279198 | from cbuild.core import logger, paths, template
from cbuild.apk import create as apk_c, sign as apk_s
import glob
import time
import pathlib
import subprocess
def genpkg(pkg, repo, arch, binpkg):
if not pkg.destdir.is_dir():
pkg.log_warn(f"cannot find pkg destdir, skipping...")
return
binpath... |
3279226 | import databases
import sqlalchemy
from fastapi_users.db import OrmarBaseUserModel, OrmarUserDatabase
from .models import UserDB
DATABASE_URL = "sqlite:///test.db"
metadata = sqlalchemy.MetaData()
database = databases.Database(DATABASE_URL)
class UserModel(OrmarBaseUserModel):
class Meta:
tablename = "u... |
3279232 | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def PrintTree(self):
print(self.data)
root = Node(10)
root.PrintTree()
Traversing a Linked List
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
... |
3279254 | from fuzzconfig import FuzzConfig
from interconnect import fuzz_interconnect
configs = [
("HPFE", (28, 0), 12, "L",
FuzzConfig(job="LMIDROUTE", device="LIFCL-40", sv="../shared/route_40.v", tiles=["CIB_R28C0:LMID"])),
("HPFW", (28, 86), 12, "R",
FuzzConfig(job="RMIDROUTE", device="LIFCL-40", sv... |
3279326 | import datetime
import io
import os
import unittest
import requests
from django.core.files.base import ContentFile
from django.test import TestCase, override_settings
from freezegun import freeze_time
from minio.error import NoSuchKey
from minio_storage.errors import MinIOError
from minio_storage.storage import Minio... |
3279404 | import pickle
import unittest
from nuplan.database.common.db import Table
from nuplan.database.nuplan_db.nuplandb import NuPlanDB
from nuplan.database.tests.nuplan_db_test_utils import get_test_nuplan_db
class TestNuPlanDB(unittest.TestCase):
"""Test main nuPlan database class."""
def setUp(self) -> None:
... |
3279407 | import argparse
import sys
import os
import yaml
from pathlib import Path
from datetime import datetime
from dcgan import DCGan
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))
from tmp_load_data import load_celeba_tfdataset
def main(_=None):
parser = argparse.ArgumentParser(description='Trai... |
3279430 | import imghdr
import json
import subprocess
from functools import cached_property
from pathlib import Path
from typing import Iterator, Optional
import albert as v0
import requests
from bs4 import BeautifulSoup
"""Search and potentially download images using Bing."""
user_agent = (
"Mozilla/5.0 (Macintosh; Intel... |
3279467 | import alpenglow.cpp as rs
import numpy as np
import alpenglow.sip as sip
class DataframeData(rs.DataframeData):
"""Python wrapper around :py:class:`alpenglow.cpp.DataframeData`.
"""
def __init__(self, df, columns={}):
super(rs.DataframeData, self).__init__()
self.columns = columns
... |
3279488 | import unittest
from quickbooks.objects.batchrequest import Fault, FaultError, BatchItemResponse, BatchItemRequest
class FaultTests(unittest.TestCase):
def test__repr__(self):
fault = Fault()
fault.type = "test"
fault.original_object = 100
fault.Error.append("error")
self... |
3279499 | import os
import warnings
import pandas as pd
from argparse import ArgumentParser
from autopandas_v2.generators.ml.traindata.generation import ArgDataGenerator, RawDataGenerator, \
FunctionSeqDataGenerator
from autopandas_v2.utils import logger
from autopandas_v2.utils.cli import subcommand, ArgNamespace
def p... |
3279529 | import defcon
from fontParts.base import BaseLayer
from fontParts.fontshell.base import RBaseObject
from fontParts.fontshell.lib import RLib
from fontParts.fontshell.glyph import RGlyph
class RLayer(RBaseObject, BaseLayer):
wrapClass = defcon.Layer
libClass = RLib
glyphClass = RGlyph
# -----------
... |
3279549 | from typing import Dict, TYPE_CHECKING
from networkx import DiGraph
from veniq.ast_framework import AST, ASTNode
from .constants import NODE, BLOCK_REASON, ORIGIN_STATEMENT, NodeId
from ._nodes_factory import NodesFactory
from ._block_extractors import BlockInfo, extract_blocks_from_statement
if TYPE_CHECKING:
fr... |
3279686 | gc = {"type": "GeometryCollection",
"geometries": [{"type": "Point",
"coordinates": [-89.33, 30.0]},
{"type": "LineString",
"coordinates": [[-89.33, 30.30],
... |
3279687 | import pandas as pd
df = pd.read_csv('preds.csv')
hash_preds = {}
for row in df.to_dict('record'):
#print(row)
#print(row['_h2_'])
hash_preds[row['_hashval_']] = row['preds']
import json
h2_hash = json.load(open('../h2_hash.json'))
hash_h2 = { hash:h2 for h2, hash in h2_hash.items() }
for hash, h2 in hash_h2... |
3279710 | from __future__ import annotations
from ..typecheck import *
from . html import span, click, alignable
from . layout import Layout
class spacer (span):
def __init__(self, width: int|None = None, min: int|None = None):
super().__init__(width, None, None)
self.flex_width = width
self.flex_width_min = min
def r... |
3279755 | from __future__ import division
import re
from collections import OrderedDict
import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import DistSamplerSeedHook, Runner, obj_from_dict
from mmdet import datasets
from mmdet.core import (CocoDistEvalmAPHook, CocoDistEvalRecallHo... |
3279835 | from next_hop import NextHop
from packet_common import ip_prefix_str
from utils import system_id_str
DEST_TYPE_NODE = 1
DEST_TYPE_PREFIX = 2
DEST_TYPE_POS_DISAGG_PREFIX = 3
DEST_TYPE_NEG_DISAGG_PREFIX = 4
def make_node_dest(system_id, name, cost, is_leaf):
return SPFDest(DEST_TYPE_NODE, system_id, name, None, set... |
3279869 | import re
from random import randint
from typing import Dict
from typing import List
from typing import Match
from typing import Optional
from retrying import retry
import apysc as ap
from apysc._display import scale_interface_helper
from apysc._display.scale_y_from_point_interface import \
ScaleYFrom... |
3279876 | import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
import xgboost as xgb
from sklearn.preprocessing import StandardScaler
import scikitplot as skplt
from sklearn.metrics import mean_squared_error
def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alph... |
3279901 | import itertools
from ..error import GraphQLError
from ..language import ast
from ..language.printer import print_ast
from ..language.visitor import Visitor, visit
from ..type.definition import (
GraphQLInterfaceType,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLUnionType,
get_named_ty... |
3279925 | import torch
import torch.nn as nn
from torchvision import datasets, transforms
from rlkit.torch import pytorch_util as ptu
from rlkit.util.io import load_local_or_remote_file
from os import path as osp
from sklearn import neighbors
import numpy as np
from torchvision.utils import save_image
from tqdm import tqdm
impor... |
3279996 | import numpy as np
import torch
from utils.hdr_toolbox import WeightFunction
from utils.hdr_toolbox import LDRStackSubSampling
from utils.hdr_toolbox import FindChromaticyScale
from utils.hdr_toolbox import gsolve
def DebevecCRF(stack,
stack_exposure,
nSamples=256,
sampling... |
3280006 | from RedditThread import RedditThread
from embeddings import WordEmbeddings
from vocabulary import Vocabulary
import numpy as np
class SemanticSimilarityHelper:
def __init__(self):
self.vocabulary = Vocabulary.deserialize('en-top100k.vocabulary.pkl.gz')
self.embeddings = WordEmbeddings.deserialize... |
3280021 | import logging
import numpy
import zmq
from numpy.lib.format import header_data_from_array_1_0
from fuel.utils import buffer_
logger = logging.getLogger(__name__)
def send_arrays(socket, arrays, stop=False):
"""Send NumPy arrays using the buffer interface and some metadata.
Parameters
----------
s... |
3280025 | from builtins import open as _orig_open
class _BkFile:
def __init__(self, file, mode, bufsize):
import os
self.__filename = file
self.__backup = file + '~'
try:
os.unlink(self.__backup)
except OSError:
pass
try:
os.rename(file, sel... |
3280033 | from six import text_type as unicode
import six
unicode # for flake8
if six.PY3:
import shutil
def is_command(cmd):
return bool(shutil.which(cmd))
def open_for_csv(*args, **kw):
kw["newline"] = ""
return open(*args, **kw)
else:
from webbrowser import _iscommand
is_com... |
3280060 | from django.conf.urls import url
from hrm import views
from django.contrib.auth.decorators import login_required
app_name = "hrm"
urlpatterns = [
url(r'^$', views.index, name = "hrm_index"),
url(r'^performance/list/$', login_required(views.ListPerformanceView.as_view()), name='perfom_list'),
u... |
3280063 | r"""
This file declares the time-dependence of the star formation history at a
given radius in the constant SFH model from Johnson et al. (2021).
"""
from .utils import constant
from .normalize import normalize
from .gradient import gradient
import math as m
import os
class static(constant):
r"""
The constant SFH... |
3280101 | import aerosandbox as asb
import aerosandbox.numpy as np
import pytest
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(palette=sns.color_palette("husl"))
"""
This test solves the 2-dimensional Rosenbrock problem constrained to a circle centered on the origin:
----------
Minimize:
(1 - x) ** 2 + (y - ... |
3280113 | import os
class EnvConfig(object):
def __init__(self):
# General flask config
self.MINDEBUG = os.environ.get("MINDEBUG", default="0") == "1"
self.DEBUG = os.environ.get("DEBUG", default="0") == "1" or self.MINDEBUG
self.JOB = os.environ.get("JOB", default="0") == "1"
self.S... |
3280145 | from poop.hfdp.factory.pizzafm.pizza import Pizza
class ChicagoStyleClamPizza(Pizza):
def __init__(self) -> None:
super().__init__()
self.name = "Chicago Style Clam Pizza"
self.doough = "Extra Thick Crust Dough"
self.sauce = "Plum Tomato Sauce"
self.toppings.append("Shredde... |
3280158 | import taichi as ti
import numpy as np
import utils
import math
from engine.mpm_solver import MPMSolver
write_to_disk = False
ti.init(arch=ti.cuda) # Try to run on GPU
gui = ti.GUI("Taichi MLS-MPM", res=512, background_color=0x112F41)
mpm = MPMSolver(res=(128, 128), unbounded=True)
mpm.add_surface_collider(point=(0... |
3280173 | from __future__ import annotations
import importlib
import inspect
import typing as t
from abc import ABC, abstractmethod
from pathlib import Path
from .helpers.search import FileSeekerBase, search_providers
if t.TYPE_CHECKING:
from .artifacts import Artifact, Artifacts
class Plugin(ABC):
_plugins: list[... |
3280178 | n, k = map(int, input().split())
a = eval("int(input())," * n)
coins = 0
for i in a[-1::-1]:
if k >= i:
count = k // i
k -= i * count
coins += count
print(coins)
|
3280185 | from ops import get_shape
import tensorflow as tf
def rotate_90_cc(inputs):
'''
Args:
inputs - 4D tensor [batch, height, width, nchannel]
Return:
rotates - 4D tensor [batch, width, height, nchannel]
rotates[i][width-k][j][l] = inputs[i][j][k][l]
'''
rotates = tf.transpose(inpu... |
3280211 | from django.core.exceptions import ImproperlyConfigured
# Want to get everything from the 'normal' models package.
from django.db.models import * # NOQA
from django.utils.version import get_docs_version
from django.contrib.gis.geos import HAS_GEOS
if not HAS_GEOS:
raise ImproperlyConfigured(
"GEOS is re... |
3280220 | import pdb
import os
import time
import numpy as np
import torch
from . import Algorithm
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
... |
3280314 | import d3d9api
from d3d9api import *
api = getD3D9API("d3d9api.xml")
f = open("d3d9_port.h","w")
print >>f, """
/**
* D3D9 portable header (windows/linux)
*
**/
#ifndef _D3D9_PORT
#define _D3D9_PORT
#ifdef WIN32
// Define call convention
#define D3D_CALL _stdcall
/**
* Include sdk provided d3d9 header
*/
#i... |
3280359 | import os
from pwtools.batch import FileTemplate
from pwtools.common import file_write, file_read
from pwtools import sql
from .testenv import testdir
pj = os.path.join
def test_placeholders():
templ_dir = pj(testdir, 'calc.templ')
templ_fn = pj(templ_dir, 'foo.in')
tgt_dir = pj(testdir, 'calc')
tgt_fn... |
3280379 | import requests
from plugins.oob import verify_request, gen_oob_domain
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''Netgear RAX43 - Unauthenticated Command Injection / Authentication Bypass Buffer Overrun via LAN Interface''',
"description": '''Netgear RAX43 ve... |
3280404 | import os
import time
from pipert.core.routine import Routine, Events
if os.environ.get('TORCHVISION', 'no') == 'yes':
from torch.multiprocessing import Event
else:
from multiprocessing import Event
import logging
class DummyCrashingRoutine(Routine):
@staticmethod
def get_constructor_parameters():
... |
3280416 | import os
import numpy as np
import geosoft.gxapi as gxapi
import geosoft.gxpy.gx as gx
import geosoft.gxpy.system as gsys
import geosoft.gxpy.surface as gxsurf
import geosoft.gxpy.vox as gxvox
import geosoft.gxpy.group as gxgrp
import geosoft.gxpy.spatialdata as gxspd
import geosoft.gxpy.view as gxview
import geosoft... |
3280429 | from pathlib import Path
from tempfile import NamedTemporaryFile
from followthemoney import model
from nomenklatura.index import Index
from nomenklatura.index.tokenizer import Tokenizer
DAIMLER = "66ce9f62af8c7d329506da41cb7c36ba058b3d28"
def test_index_build(dloader):
index = Index(dloader)
assert len(index... |
3280431 | from datetime import date
from app.models import *
from app.models.account import StudentModel
class QuestionModel(Document):
survey_id = StringField(required=True)
title = StringField(required=True)
is_objective = BooleanField(required=True)
choice_paper = ListField()
class SurveyModel(Document):
... |
3280435 | import numpy as np
import torch
class ReplayBuffer(object):
def __init__(self, max_size):
self._max_size = max_size
self._next_idx = 0
self._size = 0
self._initialized = False
self._total_steps = 0
def __len__(self):
return self._size
def _init_storage(sel... |
3280436 | import typing as t
import bytecode
from bytecode import Instr, Bytecode, Label, ConcreteBytecode, ConcreteInstr
from dataclasses import dataclass
WHY_CONTINUE = 0x0020
@dataclass(order=True, frozen=True)
class NamedLabel(Label):
name: str
@dataclass(order=True, frozen=True)
class LabelValue:
name: str
@d... |
3280443 | from .signing_mechanism import SymmetricKeySigningMechanism
# NOTE: Please import the connection_string and sastoken modules directly
# rather than through the package interface, as the modules contain many
# related items for their respective domains, which we do not wish to expose
# at length here.
|
3280454 | from SciDataTool.Functions import AxisError
def get_length(self, is_oneperiod=False, is_antiperiod=False, is_smallestperiod=False):
"""Returns the length of the axis taking symmetries into account.
Parameters
----------
self: DataLinspace
a DataLinspace object
is_oneperiod: bool
re... |
3280479 | from datetime import datetime
import requests
import pyuca
import pandas as pd
from tabula import read_pdf
def parse(bulletin_url, first_page, last_page, check=None, date=None, coord=False):
# request to find the documents
pdf = requests.get(bulletin_url)
open('bulletin.pdf', 'wb').write(pdf.content)
... |
3280482 | from rpython.rtyper import extregistry
from rpython.rtyper.extregistry import ExtRegistryEntry
from rpython.rtyper.lltypesystem.lltype import typeOf
from rpython.annotator import model as annmodel
from rpython.annotator.signature import annotation
import py, sys
class extdef(object):
def __init__(self, *args, **... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.