id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9906129 | from bs4 import BeautifulSoup
import logging
import mistune
import os
# from tsar import LOG_FOLDER
from tsar import LOG_FOLDER
from tsar.doctypes.doctype import DocType, update_dict, BASE_SCHEMA, BASE_MAPPING
from tsar.lib import parse_lib
from logging import FileHandler
handler = FileHandler(os.path.join(LOG_FOLDER... |
9906136 | import os
from utils import lov_ods_api as LOVODSAPI
os.environ['DJANGO_SETTINGS_MODULE'] = 'chatbot_app.settings'
class TestLOVODSApi(object):
def test_LOV_ODS_class_query(self):
result_set = LOVODSAPI.term_request('Administrative-Region', term_type='class', language='en')
assert result_set
... |
9906140 | from page_object import PageObject
class Page(PageObject):
def define_elements(self):
self.text_field(name='text_field_id', identifier={'id': 'text_field_id'})
self.text_field(name='text_field_class', identifier={'class': 'text_field_class'})
self.text_field(name='text_field_css', identif... |
9906219 | from .fairness import efficiency_gap, dem_advantage, rep_advantage, lost_votes
from .compactness import reock, convex_hull, polsby_popper, center_distance, bounding_hulls, bounding_circles
from .equality import equality
from .competitiveness import competitiveness
from collections import defaultdict
limits = defaultd... |
9906236 | import os
import sys
import ast
import json
import types
import inspect
import collections
FirstObservation = collections.namedtuple("FirstObservation",
["id", "type_id", "canonical_name", "str", "repr", "classification", "members"])
AttributeLookup = collections.namedtuple("AttributeLookup",
["object_id", "a... |
9906238 | from datetime import datetime
from sqlalchemy import Column, Integer, String, Text, DateTime
from lessweb import Model
from lessweb.plugin.database import DbModel
class Pager(Model):
pageNo: int = 1
pageSize: int = 10
total: int = 0
totalPage: int = 1
def slice(self, ordered_query):
self.t... |
9906257 | from asyncio_channel import create_channel, create_multiple
import asyncio
import pytest
@pytest.mark.asyncio
async def test_multiple_closed():
"""
GIVEN
Closed multiple.
WHEN
Channel is added to ChannelMultiple.
EXPECT
Return False.
"""
src = create_channel()
src.... |
9906276 | from copy import deepcopy
import numpy as np
import torch
from torch import nn
# from pytorch_pretrained_bert.modeling import BertModel
from transformers import BertConfig, RobertaConfig, RobertaModel, BertModel
class BertEncoder(nn.Module):
def __init__(self, cfg):
super(BertEncoder, self).__... |
9906279 | from .base_enums import AvatarColor
class BackgroundColor(AvatarColor):
"""Background colors. You can use any other color using its hex code"""
__install__ = True
__enum_path__ = 'background_colors.py'
DEFAULT = '#65C9FF'
BLACK = '#262E33'
WHITE = '#FFFFFF'
|
9906281 | from click.testing import CliRunner
import click
from importlib import import_module
def run_cli_help(app, cmd=None):
runner = CliRunner()
if cmd:
result = runner.invoke(app.cli, [cmd, "--help"])
else:
result = runner.invoke(app.cli, ["--help"])
return result.output
def get_app_info... |
9906282 | import argparse
import json
import logging
from os.path import join, exists
import numpy as np
import tensorflow as tf
from tqdm import tqdm
from debias.datasets import triviaqa_cp
from debias.models.model_dir import ModelDir
from debias.utils import py_utils, ops
from triviaqa_cp import triviaqa_cp_evaluation
def ... |
9906361 | from fluent.core.widget import RenderWidget
class Spacer(RenderWidget):
def __init__(self, size):
super(Spacer, self).__init__(size=size)
|
9906371 | def extractMoonlightTranslations(item):
"""
Moonlight Translations
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
tagmap = [
('Discovering my Disciple Wants to Eat Me After Raising Him', 'Dis... |
9906404 | from collections.abc import Iterable
import torch
from pixelflow.transforms import Transform
from pixelflow.utils import sum_except_batch
from pixelflow.transforms.functional import get_mixture_params, get_matching_multivariate_mixture_params_2d
from pixelflow.transforms.functional import splines, cmol_transform, multi... |
9906409 | import FWCore.ParameterSet.Config as cms
process = cms.Process("DEADLOCKTEST")
process.source = cms.Source("EmptySource")
process.maxEvents.input = 20000
process.a = cms.EDAnalyzer("ConsumingOneSharedResourceAnalyzer",
valueMustMatch = cms.untracked.int32(1),
... |
9906422 | import sys
import os
from numba.cuda.cudadrv.libs import test
from numba.cuda.cudadrv.nvvm import NVVM
def run_test():
if not test():
return False
nvvm = NVVM()
print("NVVM version", nvvm.get_version())
return nvvm.get_version() is not None
sys.exit(0 if run_test() else 1)
|
9906441 | from django_tgbot.state_manager import state_types
class TransitionCondition:
def __init__(self, from_states=None, message_types=None, update_types=None, exclude_message_types=None,
exclude_update_types=None):
"""
Leave message_types / update_types for accepting all.
:para... |
9906492 | import time
import boto3
from boto3.dynamodb.conditions import Key
import numpy as np
# lambda setting
grad_tb_name = "ml-grads"
model_tb_name = "ml-models"
model_size = 30
def np2str(arr):
return str(arr.tolist()).strip('[]')
def str2np(str, shape):
return np.array([float(x) for x in str... |
9906514 | import os
import logging
import shutil
import torch
import torch.nn.functional as F
from torch.utils.data.sampler import Sampler
import math
import numpy as np
from collections import defaultdict
import cv2
from easydict import EasyDict
import yaml
from .logger import logger
class AverageMeter(object):
"""Compute... |
9906553 | from copy import deepcopy
from convlab2.util.multiwoz.multiwoz_slot_trans import REF_SYS_DA
def delexicalize_da(da, requestable):
delexicalized_da = []
counter = {}
for intent, domain, slot, value in da:
if intent in requestable:
v = '?'
else:
if slot=='none':
... |
9906560 | from typing import Optional, Any, Dict
import aiohttp
from aiohttp import ClientConnectorError
from loguru import logger
from app.utils.admin_tools.admins_notify import notify_admins
DEFAULT_DB_URL = "http://rasp.gstu.by/rasp_df/db/"
class API:
def __init__(self, url: Optional[str] = None):
self.db_ur... |
9906607 | from typing import Any, List
import pytest
from src.domain.userManagment.userSchema import UserCreateSchema, UserDBSchema, UserUpdateSchema
from src.domain.userManagment.userService import UserService
from src.infrastructure.database.models.user import UserModel
USER_MODEL = UserModel(
user_id=1,
email="<EMA... |
9906661 | import pandas as pd
import numpy as np
from functools import partial
from janitor import clean_names
#Download Data
# ------------------------------------------------------------
# Adelie penguin data from: https://doi.org/10.6073/pasta/abc50eed9138b75f54eaada0841b9b86
uri_adelie = "https://portal.edirepository.org/n... |
9906685 | class BindingManagerDataErrorEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.BindingManagerBase.DataError event.
BindingManagerDataErrorEventArgs(exception: Exception)
"""
@staticmethod
def __new__(self,exception):
""" __new__(cls: type,exception: Exception) """
pass
Exce... |
9906705 | def get_url(*parts):
return "{}/{}/".format(base, "/".join(parts))
protocol = "http"
domain = "api.platform.xixiang000.com"
base = "{}://{}".format(protocol, domain)
login_url = get_url("login")
list_company_url = get_url("list", "company")
list_menu_url = get_url("list", "getMenu")
list_url = get_url("list... |
9906710 | import httplib
import itertools
import array
import StringIO
import socket
import errno
import os
import tempfile
import unittest
TestCase = unittest.TestCase
from test import test_support
here = os.path.dirname(__file__)
# Self-signed cert file for 'localhost'
CERT_localhost = os.path.join(here, 'keycert.pem')
# Se... |
9906711 | from flask import jsonify
from flask_apiblueprint import APIBlueprint
from sample_api import User, Media
from sample_api.views.v1 import api_v1
remapping = {'/users/list/': '/users/'}
api_v2 = APIBlueprint(
'api_v2',
__name__,
subdomain='',
url_prefix='/api/v2',
inherit_from=api_v1,
remappin... |
9906719 | import numpy as np
import unittest
from finmag.native import llg as native_llg
from test_jacobean_computation import setup_llg_params_near_one
from finmag.util.time_counter import counter
class NativeLlgTests(unittest.TestCase):
def test_llg_performance(self):
# Unfortunately 100000 nodes is not enough t... |
9906721 | import sys
import os
import json
from subprocess import Popen, PIPE
# Import this way to produce a more useful error message.
try:
import yaml
except ImportError:
print('Unable to import YAML module: please install PyYAML', file=sys.stderr)
sys.exit(1)
__all__ = ['check_unwanted_files', 'load_yaml', 'read... |
9906722 | import utils
class MerkleNode(object):
""" Repersents a node of merkle tree.
Args:
left (MerkleNode object): a left subtree.
right (MerkleNode object): a right subtree.
data (byte): value of node.
Attributes:
left (MerkleNode object): a left subtree.
right (Merkl... |
9906747 | from sympy import (
Symbol, Wild, sin, cos, exp, sqrt, pi, Function, Derivative,
Integer, Eq, symbols, Add, I, Float, log, Rational,
Lambda, atan2, cse, cot, tan, S, Tuple, Basic, Dict,
Piecewise, oo, Mul, factor, nsimplify, zoo, Subs, RootOf,
AccumBounds, Matrix, zeros, ZeroMatrix)
from sympy.core.... |
9906748 | import param
import numpy as np
from ...element import HLine, VLine, HSpan, VSpan, Tiles
from ..mixins import GeomMixin
from .element import ElementPlot
class ShapePlot(ElementPlot):
# The plotly shape type ("line", "rect", etc.)
_shape_type = None
style_opts = ['opacity', 'fillcolor', 'line_color', 'li... |
9906764 | from .util import get_settings_from_svg, get_blueprint_from_svg, pretty_print_settings, save_svg, print_blueprint_entity_count
from .building_settings import BUILDING_GENERIC_TERMS, BUILDING_SIZES
from .example_data import EXAMPLE_SETTINGS, EXAMPLE_BLUEPRINT
from .visualizer import draw_blueprint, get_blueprint_cache, ... |
9906790 | import urllib.request, urllib.error, urllib.parse
import json
import datetime
import csv
import time
def request_until_succeed(url, return_none_if_400=False):
req = urllib.request.Request(url)
success = False
while success is False:
try:
response = urllib.request.urlopen(req)
... |
9906808 | def fpow(a, b, p):
r = 1
while b != 0:
if b & 1 == 1:
r = r * a % p
a = a * a % p
b >>= 1
return r
def msqrt(n, p):
if n == 0:
return 0
q = p - 1
s = 0
z = 2
while ~q & 1 != 0:
q >>= 1
s += 1
if s == 1:
return fpow(n, (p + 1) // 4, p)
while fpow(z, (p - 1) // 2, p) == 1:
z += 1
c = fpow(z... |
9906858 | import requests
import json
from insightconnect_plugin_runtime.exceptions import PluginException
import base64
class RequestHelper(object):
def __init__(self, session, logger):
"""
Creates a new instance of RequestHelper
:param session: Session object available to Komand actions/triggers, ... |
9906860 | from concurrent import futures
from itertools import islice
from typing import Any, Callable, Iterable, Iterator, Set, TypeVar
_T = TypeVar("_T")
class ThreadPoolExecutor(futures.ThreadPoolExecutor):
_max_workers: int
@property
def max_workers(self) -> int:
return self._max_workers
def imap... |
9906906 | import torch
import torch.nn as nn
from network import Network
from lib.modules.layers import LSTMLayer, FullyConnectedLayer
class LSTMNetwork(Network):
"""
LSTM neural network (with multiple layers).
Args:
network_config (dict): dictionary containing network configuration parameters,
... |
9906951 | r"""
The extended Theis solution in 2D
=================================
We provide an extended theis solution, that incorporates the effectes of a
heterogeneous transmissivity field on a pumping test.
In the following this extended solution is compared to the standard theis
solution for well flow. You can nicely see... |
9906992 | import astropy.units as u
import numpy as np
__all__ = ['search_code_mpc']
def search_code_mpc():
"""Reads the MPC Observer Database.
Returns
-------
observatories : `dict`
A python dictionary with all the sites as Astropy EarthLocation objects.
"""
from astropy.coordinates import Ea... |
9907058 | from multiprocessing import Process, Queue
import time
def f(q):
time.sleep(10)
q.put([42, None, 'hello'])
if __name__ == '__main__':
q = Queue()
p = Process(target=f, args=(q,))
p.start()
print("waiting")
print(q.get()) # prints "[42, None, 'hello']"
p.join()
|
9907064 | from typing import Tuple
from hypothesis import given
from gon.base import Angle
from tests.utils import (equivalence,
not_raises)
from . import strategies
@given(strategies.angles_pairs)
def test_basic(angles_pair: Tuple[Angle, Angle]) -> None:
first, second = angles_pair
result =... |
9907112 | from rest_framework.test import APITestCase, APIRequestFactory,\
force_authenticate
from django.core.urlresolvers import reverse
from api.v2.views import SizeViewSet
from api.tests.factories import ProviderFactory, UserFactory,\
AnonymousUserFactory, SizeFactory, IdentityFactory
from .base import APISanityTes... |
9907138 | import cv2
import common
import datetime
import os
import numpy as np
SOURCE_IMG_FILE_FOLDER = '../../../dataset/facedata/umdface/JPEGImages/'
CROP_IMG_FILE_FOLDER = '../../../dataset/facedata/umdface/annoImages/'
CROP_IMG_FILE_FOLDER_DRAW = '../../../dataset/facedata/umdface/cropImg/'
LABEL_FILE_FOLDER = '../../../da... |
9907184 | import os
import pytest
from django.conf import settings
from django.core.management import call_command
from pytest_django.migrations import DisableMigrations
from thenewboston.accounts.manage import create_account
from thenewboston.blocks.block import generate_block
from thenewboston.constants.network import PRIMARY... |
9907188 | import json
import pandas as pd
from ..algoNetgenBase import AlgorithmNetgenBase
from DataToNetwork.BuildResponseNetwork import simMatrixToNetwork
from .. import jobTracker
import ResponseDataCache
"""compute edges based on similarity matrix"""
def getAttrType(val):
if isinstance(val, int) == True:
retur... |
9907220 | import typing
from typing import Any, Optional, Text, Dict, List, Type
import numpy as np
import scipy
from rich import print
from rich.markdown import Markdown
from rasa.nlu.components import Component
from rasa.nlu.config import RasaNLUModelConfig
from rasa.shared.nlu.training_data.training_data import TrainingData
f... |
9907235 | from collections import defaultdict, namedtuple
Task = namedtuple('Task', ['x', 'y', 'task_info'])
|
9907237 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class GRU2D(nn.Module):
"""2D GRU Cell"""
def __init__(self, in_dim, hidden_dim, bias=True):
super(GRU2D, self).__init__()
self.x_to_intermediate = nn.Linear(in_dim, 3 * hidden_dim, bias=bias)
self.h_to_int... |
9907243 | import logging
import os
import torch
from tensorboardX import SummaryWriter
import NVLL.argparser
from NVLL.util.gpu_flag import device
def set_seed(args):
torch.manual_seed(args.seed)
if device == torch.device("cuda"):
torch.cuda.manual_seed(args.seed)
def set_save_name_log_nvdm(args):
args.... |
9907249 | import datetime as dt
from typing import Any, ClassVar, Dict, List, Optional, Union
from clabe.types import Clabe
from cuenca_validations.types import digits
from pydantic import conint, constr
from pydantic.dataclasses import dataclass
from ..auth import CUENTA_FIELDNAMES
from ..types import (
Curp,
EntidadF... |
9907262 | import torch.nn as nn
from latent_level import LatentLevel
from lib.modules.networks import LSTMNetwork
from lib.modules.latent_variables import FullyConnectedLatentVariable
class LSTMLatentLevel(LatentLevel):
"""
Latent level with LSTM encoding and decoding functions.
Args:
level_config (dict): ... |
9907364 | import unittest
import_error = False
try:
from .. import logutils
except ImportError:
import_error = True
logutils = None
class TestCase00(unittest.TestCase):
def test_import(self):
self.assertFalse(import_error)
|
9907415 | import torch
import ocnn
class FullOctree2Voxel(torch.nn.Module):
def __init__(self, depth):
super(FullOctree2Voxel, self).__init__()
self.depth = depth
def forward(self, data):
height = 2 ** (3 * self.depth)
channel = data.size(1)
out = data.view(channel, -1, height) # (1, C, H, 1) -> (C, b... |
9907416 | from typing import Any, Dict, List, Optional
from nucleus.pydantic_base import DictCompatibleModel
class DatasetInfo(DictCompatibleModel):
"""High-level :class:`Dataset` information
Attributes:
dataset_id: Nucleus-generated dataset ID
name: User-defined name of dataset
length: Number... |
9907421 | from __future__ import annotations
import typing as t
import keyword
import logging
from collections import namedtuple
from collections import defaultdict
from collections import OrderedDict
from functools import partial
from prestring import PreString
from prestring.python import Module
from prestring.utils import Laz... |
9907455 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import fnmatch
import re
class ImportantManager(object):
def __init__(self, globlist):
if globlist:
self.globlist_re = re.compile(
"(" + "|".join([fnmatch.translate(g)... |
9907459 | import unittest
import torch
import torch.nn as nn
from code_soup.common.vision.models import SimpleCnnClassifier
class TestSimpleCnnClassifier(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.model = SimpleCnnClassifier(input_shape=(3, 32, 32), num_labels=10)
def test_step(sel... |
9907565 | import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demoblog.settings')
application = get_wsgi_application()
|
9907604 | from tool.runners.python import SubmissionPy
from collections import defaultdict
class DavidSubmission(SubmissionPy):
def run(self, s):
"""
:param s: input in string format
:return: solution flag
"""
l = sorted([int(x) for x in s.split("\n")])
l = [0] + l + [l[-1]+... |
9907637 | from utils import cpp, table_reader
def to_camel_case(snake_str):
components = snake_str.split('_')
return components[0] + ''.join(x.title() for x in components[1:])
def main():
fields = table_reader.csv_to_list_of_tuples(
csv_filepath="ast_fields.csv",
)
header_writer = cpp.HeaderWrite... |
9907695 | import unittest
import duplicates
class TestRemoveShared(unittest.TestCase):
"""Tests for function duplicates.remove_shared."""
def test_general_case(self):
"""
Test remove_shared where there are items that
appear in both lists, and items that appear in
only one or the other l... |
9907698 | import numpy as np
from scipy.linalg import inv
from js.data.plyParse import PlyParse
import os.path, re, json, random, argparse
import subprocess as subp
from js.geometry.rotations import Quaternion
from js.utils.plot.colors import colorScheme
from helpers import *
import binascii
def SamplePair(inputPath, outlier, n... |
9907754 | import pytest
from blight import action, tool
@pytest.mark.parametrize(
("action_class", "tool_class", "should_run_on"),
[
(action.Action, tool.CC, True),
(action.CCAction, tool.CC, True),
(action.CCAction, tool.CXX, False),
(action.CXXAction, tool.CXX, True),
(action.... |
9907760 | import datetime as dt
import os
import pathlib
from django.apps import apps
from . import command
from . import database
from . import exceptions
from . import settings
from .utils import print_msg
DT_FORMAT = '%Y_%m_%d_%H_%M_%S_%f'
def _make_dump_config(*, exclude_models=None, pre_dump_hooks=None):
"""Make a ... |
9907818 | from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
def main():
driver = webdriver.Chrome()
driver.get('https://v.taobao.com/v/content/live?catetype=704&from=taonvlang')
soup = BeautifulSoup(driver.page_source, 'lxml')
for img_tag in soup.body.s... |
9907833 | import os
from copy import deepcopy
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision.models import densenet121
from wilds.common.data_loaders import get_eval_loader
from wilds.datasets.camelyon17_data... |
9907865 | import json
import os
import shutil
import sys
import tempfile
import unittest
from unittest.mock import patch
from ray import tune
from ray.ml.utils.remote_storage import upload_to_uri, delete_at_uri
from ray.tune.cloud import TrialCheckpoint
class TrialCheckpointApiTest(unittest.TestCase):
def setUp(self) -> N... |
9907874 | import pandas as pd
import os
from app.db.session import SessionLocal,engine
db = SessionLocal()
sql = """
SELECT TABLE_NAME FROM information_schema.`TABLES` WHERE TABLE_SCHEMA = 'DWDB' AND TABLE_NAME != 'alembic_version'
"""
rows = db.execute(sql).fetchall()
for table in rows:
table_name = table[0]
sql = ... |
9907878 | from subprocess import Popen, PIPE, DEVNULL
import sys
# There are 3+ command line arguments:
# 1) the file to update
# 2) the file's previous state, to check if things changed at all
# 3) the file's parents that need to be updated as well
FILE = sys.argv[1]
OLD_STATE = sys.argv[2]
PARENTS = [p for p in sys.argv[3:]]... |
9907880 | import setuptools
from os import path
import sirms
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setuptools.setup(
name="sirms",
version=sirms.__version__,
author="<NAME>",
author_email="<... |
9907915 | import torch
import torch.nn as nn
import torch
from torch.autograd import Variable
import copy
from transformers.modeling_bert import BertLayerNorm
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss, MSELoss
# from transformers import (WEIGHTS_NAME, AdamW, get_linear_schedule_with_warmup,
# ... |
9907919 | from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools import ttLib
from fontTools import designspaceLib
from fontTools.feaLib.builder import addOpenTypeFeaturesFromString
from fontTools.ttLib.tables import _f_v_a_r, _g_l_y_f
from fontTools.ttLib.tables import ... |
9907943 | import logging
import synapse.common as s_common
import synapse.tests.utils as s_t_utils
logger = logging.getLogger(__name__)
class RiskModelTest(s_t_utils.SynTest):
async def test_model_risk(self):
async with self.getTestCore() as core:
attk = s_common.guid()
camp = s_common.g... |
9908010 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import *
import misc.utils as utils
from misc.model import AttModel
from torch.nn.parameter import Parameter
import pdb
cl... |
9908022 | import numpy as np
import numba as nb
# Adapted from https://github.com/GridTools/gt4py/blob/1caca893034a18d5df1522ed251486659f846589/tests/test_integration/stencil_definitions.py#L194
@nb.jit(nopython=True, parallel=True, fastmath=True)
def hdiff(in_field, out_field, coeff):
I, J, K = out_field.shape[0], out_fie... |
9908051 | import turtle
import time
screen=turtle.Screen()
screen.setup(420,320)
screen.bgcolor('black')
clr=['red','green','blue','yellow','purple']
t = turtle.Pen()
t.ht()
for x in range(5):
t.color(clr[x])
t.forward(200)
t.right(144)
turtle.Screen().exitonclick() |
9908064 | import featureflow as ff
import zounds
import numpy as np
from torch import nn, optim
from random import choice
import argparse
class Layer(nn.Module):
"""
A single layer of our simple autoencoder
"""
def __init__(self, in_size, out_size):
super(Layer, self).__init__()
self.linear = n... |
9908069 | from __future__ import absolute_import, division, unicode_literals
import sys
import os
import json
import re
import html5lib
from . import support
from . import test_tokenizer
p = html5lib.HTMLParser()
unnamespaceExpected = re.compile(r'^(\|\s*)<html ([^>]+)>', re.M).sub
def main(out_path):
if not os.path.ex... |
9908127 | import caffe
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
class NormLayer(caffe.Layer):
def setup(self, bottom, top):
# check input pair
if len(bottom) != 1:
raise Exception("Need one input.")
def reshape(self, bottom, top):
top[0].reshape(*... |
9908129 | import os
from io import StringIO
from unittest import mock
from xml.dom import pulldom
from django.conf import settings
from django.test import TestCase, override_settings
from wagtail.core.models import Page
from wagtail_wordpress_import.functions import node_to_dict
from wagtail_wordpress_import.importers.wordpress... |
9908139 | class SpectrumOptions:
def addam(self, af="", aa="", ab="", ac="", ad="", amin="", **kwargs):
"""Specifies the acceleration spectrum computation constants for the
APDL Command: ADDAM
analysis of shock resistance of shipboard structures.
Parameters
----------
af
... |
9908148 | a = [
1, 2, 3]
b = [
x + 1
for x in range(3)]
c = [[[
1
]]]
d = [[[
4]]]
e = [[
1], 2, 3]
def foo(x, y):
pass
foo(
a,
b)
if (a and
b):
pass
|
9908220 | from .conv_fkaconv import Convolution_FKAConv
from .conv_convpoint import Convolution_ConvPoint
from .max_pooling import max_pool
from .interpolation import interpolate |
9908276 | from django.conf.urls import url
from .views import ajaximage
urlpatterns = [
url(
r'^upload/(?P<upload_to>.*)/(?P<max_width>\d+)/(?P<max_height>\d+)/(?P<crop>\d+)/(?P<storage>[\w\-.]+)?/',
ajaximage,
name='ajaximage',
)
]
|
9908283 | import os
import markdown
index_content = """
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vega@3"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@2"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed@3"></script>
<style>
.code {
padding: 10px;
mar... |
9908293 | import re
import random
import numpy as np
import os.path
import scipy.misc
import shutil
import zipfile
import time
import tensorflow as tf
from glob import glob
from urllib.request import urlretrieve
from tqdm import tqdm
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=1, tota... |
9908308 | from selenium import webdriver
from bs4 import BeautifulSoup
browser = webdriver.PhantomJS("phantomjs.exe")
browser.get("https://protonmail.com/")
page = BeautifulSoup(browser.page_source,"lxml")
images = page.findAll("img")
for image in images:
print(image.get('src'))
browser.close() |
9908325 | import os
from keras.preprocessing.image import ImageDataGenerator
import pandas as pd
class Dataset:
"""Class for implementing dataset handling"""
def __init__(self, database_dir, data_type='ADP', size=321, batch_size=16):
self.data_type = data_type
self.size = size
self.batch_size = ... |
9908328 | from typing import List, Optional
from pystratum_backend.RoutineLoaderWorker import RoutineLoaderWorker
from pystratum_backend.StratumStyle import StratumStyle
class VoidRoutineLoaderWorker(RoutineLoaderWorker):
"""
Routine loader worker that does nothing.
"""
# -------------------------------------... |
9908339 | import pandas as pd
import pytest
from pandas.testing import assert_frame_equal
from powersimdata.design.generation.clean_capacity_scaling import (
add_new_capacities_collaborative,
add_new_capacities_independent,
add_shortfall_to_targets,
)
def test_independent_new_capacity():
area_names = ["Pacific... |
9908343 | import numpy as np
from typing import Tuple, List
import tensorflow as tf
from tensorflow import Tensor
import string
from decompose.distributions.distribution import DrawType, UpdateType
from decompose.distributions.cenNormal import CenNormal
from decompose.likelihoods.likelihood import Likelihood
from decompose.dist... |
9908352 | import streamlit as st
from streamlit_option_menu import option_menu
# import your app modules here
from apps import osm_names
st.set_page_config(page_title="Search Geographic Names", layout="wide")
# A dictionary of apps in the format of {"App title": "App icon"}
# More icons can be found here: https://icons.getboo... |
9908376 | import sys
from numpy import *
import numpy as np
import itertools
import time
# math helpers
from math import *
class PackedVector(object):
_name_to_idx = {} # store parameter blocks.
_views = []
def __init__(self, *shapes, **shapemap):
# *shapes : list of arguments ,not know the length of it.
... |
9908448 | import pyparsing as pp
from .base import BaseParser
from .property import Property
from css2video.constants import RuleType
class StyleParseException(Exception):
"""Raised when there is an exception while parsing the style rule"""
pass
class Style(BaseParser):
"""Parse a CSS style rule"""
ParseExc... |
9908450 | import tensorflow as tf
### Tensorflow v1.15.2
#tf.compat.v1.enable_eager_execution()
graph_def_file="frozen_inference_graph_257_os16.pb"
input_arrays=["ImageTensor"]
output_arrays=['ArgMax']
input_tensor={"ImageTensor":[1,257,257,3]}
# Weight Quantization - Input/Output=float32
#converter = tf.lite.TFLiteConverter.... |
9908456 | import torch
from torch import nn, Tensor
from ..._internally_replaced_utils import load_state_dict_from_url
from ...ops.misc import ConvNormActivation, SqueezeExcitation
from ..mobilenetv3 import InvertedResidual, InvertedResidualConfig, MobileNetV3,\
model_urls, _mobilenet_v3_conf
from torch.quantization import Q... |
9908477 | import pytest
from geomeppy.geom.surfaces import get_adjacencies
from geomeppy.geom.surfaces import set_coords
@pytest.fixture
def shadow_intersecting():
shadow_blocks = [
{
"name": "PN1001_Bld1004_EL24",
"coordinates": [
(-83635.2890999997, -100958.99369999953),
... |
9908493 | import sys
import clr
clr.AddReference('Lunar.Core')
clr.AddReference('Lunar.Server')
clr.AddReference('System')
import npc_common
from Lunar.Server.Utilities import *
from Lunar.Server.World.BehaviorDefinition import *
from Lunar.Server.World.Actors import *
import random
class CombatNPCState(IActorState[NPC]):
def... |
9908552 | import math
import torch
from torch.distributions.utils import broadcast_all
import pyro
from pyro import poutine
from pyro.poutine.util import prune_subsample_sites
from pyro.util import warn_if_nan
from pyro.infer.util import torch_item
from pyro.contrib.util import lexpand, rexpand
class MutualInformation(object... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.