id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11555764 | class Solution:
def findDiagonalOrder(self, matrix):
i, j, d, res, n, m = 0, 0, 1, [], len(matrix), len(matrix and matrix[0])
while i < n and j < m:
res.append(matrix[i][j])
if j + 1 < m and (i == 0 and d == 1) or (i == n - 1 and d == -1): j, d = j + 1, -d
elif i... |
11555790 | import glob
from utils import load_from_file
import numpy as np
import pandas as pd
fnames = glob.glob("/users/mscherbela/runs/jaxtest/conv/test9/*/results.bz2")
all_data = []
for f in fnames:
data = load_from_file(f)
d = data['config']
E_eval_mean = data['E_eval_mean']
d['Eval_mean_of_std'] = np.mean(... |
11555816 | from ir_axioms.model import base, context
# Re-export sub-modules.
Query = base.Query
Document = base.Document
TextDocument = base.TextDocument
RankedDocument = base.RankedDocument
RankedTextDocument = base.RankedTextDocument
JudgedRankedDocument = base.JudgedRankedDocument
JudgedRankedTextDocument = base.JudgedRanked... |
11555818 | from sqlalchemy.ext.mutable import MutableDict
from sqlalchemy_utils import UUIDType, JSONType
from depc.extensions import db
from depc.models import BaseModel
class Config(BaseModel):
__tablename__ = "configs"
__repr_fields__ = ("id", "team")
team_id = db.Column(
UUIDType(binary=False), db.For... |
11555845 | import torch
from torchvision.transforms import autoaugment, transforms
from torchvision.transforms.functional import InterpolationMode
class ClassificationPresetTrain:
def __init__(self, crop_size, image_mean=(123.675, 116.28, 103.53), image_scale=(0.017125, 0.017507, 0.017429), hflip_prob=0.5,
... |
11555899 | import random
# Ok, I think what we have below is correct as pseudo-code.
# Next: test it with a simple environment and make it no-longer pseudo-code
# After that: make it into a persistent thing that I can make multiple calls to.
'''
A snag:
I need some way of figuring out whether a node has already been explored. ... |
11555907 | import torch
from torch import nn
from transformers import AlbertModel
class MME2E_T(nn.Module):
def __init__(self, feature_dim, num_classes=4, size='base'):
super(MME2E_T, self).__init__()
self.albert = AlbertModel.from_pretrained(f'albert-{size}-v2')
# self.text_feature_affine = nn.Sequen... |
11555928 | import FWCore.ParameterSet.Config as cms
from IOMC.EventVertexGenerators.VtxSmearedParameters_cfi import *
matchVtx = cms.EDProducer("MixEvtVtxGenerator",
signalLabel = cms.InputTag("hiSignal"),
heavyIonLabel = cms.InputTag("generator","unsmeared")
... |
11555961 | import threading, unittest
from bibliopixel.util.threads import compose_events
class ComposeEventTest(unittest.TestCase):
def test_compose_events(self):
a, b = threading.Event(), threading.Event()
master = compose_events.compose_events([a, b])
self.assertFalse(master.is_set())
a.s... |
11556030 | import pickle
import shutil
import unittest
import platform
import subprocess
from pathlib import Path
from autodrome.simulator import Simulator, ETS2, ATS
from .map import Map
from .definition import Definition
class Policeman:
ExtractorExecutable = Path(__file__).parent / 'bin/scs_extractor.exe'
def __in... |
11556043 | import sys
import unittest
from targetprologstandalone import entry_point
from StringIO import StringIO
class TestSpyrolog(unittest.TestCase):
def test_direct(self):
stdout_bak = sys.stdout
try:
result = StringIO()
sys.stdout = result
entry_point([
... |
11556095 | import pytest
from mfsetup.mf5to6 import (
get_package_name,
get_variable_name,
get_variable_package_name,
)
@pytest.mark.parametrize('version_var_expected', [('mfnwt', 'k', 'hk'),
('mfnwt', 'k33', 'vka'),
... |
11556120 | import string
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QMenu, QAction
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QColor, QCursor
from core import prefs
class RegTableWidget(QTableWidget):
regCheckBoxChanged = pyqtSignal(str, int)
def __init__(self, parent=None):
... |
11556170 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.electric_load_center import GeneratorFuelCellExhaustGasToWaterHeatExchanger
log = logging.getLogger(__name__)
class TestGeneratorFuelCellExhaustGasToWaterHeatExchanger(unittest.... |
11556177 | from __future__ import print_function
import configargparse
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
import torchnet as tnt
from torchnet.engine import Engine
from torchnet.logger import VisdomPlotLogger, VisdomLogger
from tqdm import tqdm
from models i... |
11556212 | from struct import *
import sys
import io
import os
if len(sys.argv) != 4:
print("Usage: {} [pack/unpack] [input] [output]".format(sys.argv[0]))
sys.exit(1)
if sys.argv[1] == "unpack":
with io.open(sys.argv[2], "rb") as input_file:
with io.open(sys.argv[3], "w", encoding="utf-8") as output_file:
print("Unpack... |
11556279 | from pybtex.database import Entry
def cleanup_string(string):
return string.replace('{', '').replace('}', '').replace('\\', '')
def recurse_bibtex(obj, entries):
for b in obj.__class__.__bases__:
if issubclass(b, Citable):
entries.extend(b.BIBTEX_ENTRIES)
recurse_bibtex(b, ent... |
11556287 | JarsToLabelsInfo = provider(fields = [
"jars_to_labels", # dict of path of a jar to a label
])
|
11556332 | class Solution:
def minPatches(self, nums: [int], n: int) -> int:
add, i, count = 1, 0, 0
while add <= n:
if i < len(nums) and nums[i] <= add:
add += nums[i]
i += 1
else:
add += add
count += 1
return coun... |
11556338 | from ..plugins import create_groupnorm_plugin
from ..torch2trt_dynamic import tensorrt_converter, trt_
@tensorrt_converter('torch.nn.GroupNorm.forward')
def convert_GroupNorm(ctx):
module = ctx.method_args[0]
input = ctx.method_args[1]
input_trt = trt_(ctx.network, input)
weight_trt = trt_(ctx.networ... |
11556339 | from setuptools import setup
from setuptools_rust import Binding, RustExtension
import os
setup(name='granne',
version='0.5.2',
rust_extensions=[RustExtension('granne',
'py/Cargo.toml', binding=Binding.RustCPython)],
zip_safe=False,
setup_requires=['setupt... |
11556354 | import logging
import pytorch_lightning as pl
from torch import nn
from transformers import AutoConfig, AutoModel, AutoTokenizer
logger = logging.getLogger(__name__)
class PretrainedTransformer(pl.LightningModule):
def __init__(self, args, num_labels=None, mode="base", **config_kwargs):
"Initialize a ... |
11556368 | import RPi.GPIO as GPIO
import time
import Adafruit_ADS1x15
adc = Adafruit_ADS1x15.ADS1115()
GAIN = 1
adc.start_adc(0, gain=GAIN)
GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)
GPIO.setwarnings(False)
servo = GPIO.PWM(14, 50)
servo.start(0)
Def Distance():
D_value = adc0.get_last_result()
D = (1.0 / (F_... |
11556370 | from app import db
class DNSZoneModel(db.Model):
__tablename__ = 'dns_zones'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, nullable=True, index=True, default=0)
domain = db.Column(db.String(255), nullable=True, default='', index=True)
active = db.Column(db.Boolean, d... |
11556384 | import time
import os
import platform
import sys
if platform.system() == 'Darwin':
print 'Skipped for Mac platform'
sys.exit(0)
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from nw_util import *
from selenium import webdriver
from selenium.webdriver.chrome.options import Optio... |
11556411 | import os
import copy
import shutil
import attacks
import foolbox
import numpy as np
from fmodel import create_fmodel
from bmodel import create_bmodel
from utils import read_images, store_adversarial, compute_MAD
test_model_acc = False
def run_attack_curls_whey(model, image, label):
criterion = foolbox.criteria.... |
11556434 | import torch.utils.data as data
from PIL import ImageFile
from dataset.Parsers.MOT17 import GTParser_MOT_17
from dataset.Parsers.JTA import GTParser_JTA
from dataset.augmentation import SSJAugmentation
ImageFile.LOAD_TRUNCATED_IMAGES = True
class MOT17JTATrainDataset(data.Dataset):
'''
The class is the datas... |
11556435 | import os
import tempfile
import unittest
import pandas as pd
from credentialdigger.cli import cli
from credentialdigger.client_sqlite import SqliteClient
from parameterized import param, parameterized
class TestGetDiscoveries(unittest.TestCase):
@classmethod
def setUpClass(cls):
""" Set up a databa... |
11556493 | import sys
import os
import os.path
import json
import logging
from email.parser import Parser
from collections import namedtuple
from zipfile import ZipFile
from pkg_resources import EntryPoint, parse_version
import minemeld.loader
LOG = logging.getLogger(__name__)
__all__ = [
'get_metadata_from_wheel',
'... |
11556497 | from .uncset import UncSet
from .uncparam import UncParam
from .reformulate import (PolyhedralTransformation,
EllipsoidalTransformation,
GeneratorTransformation,
WGPTransformation)
from .solver import (ReformulationSolver,
... |
11556602 | import socket
import threading
import sys
import monoclient
import decorators
import loads
def request_server_option():
"""
Is used to request the option and prints it.
Returns
-------
option: int
The option that has to be returned
"""
colors = decorators.Colors()
option = 0
... |
11556606 | import GPy
import numpy as np
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.utils import check_array
from sklearn.metrics import r2_score
from scipy.cluster.vq import kmeans2
from typing import Tuple
class SparseGPR(BaseEstimator, RegressorMixin):
def __init__(
self,
kernel=N... |
11556611 | import json
from abc import ABCMeta, abstractmethod
class ConfigurableTrainerFitResult:
"""
Result object of a ConfigurableModel fit. Contains a score for the fitted model and also additional metadata.
"""
def __init__(self, score: float, score_name: str, score_epoch: int = -1, additional_metadata: d... |
11556633 | import os
from bob.bio.base.test.dummy.database import database
import bob.io.image
# Creates a list of unique str
samples = [s.key for s in database.background_model_samples()]
def reader(sample):
data = bob.io.image.load(
os.path.join(database.database.original_directory, sample + database.database.ori... |
11556636 | import os
import sys
sys.path.insert(0, os.getcwd())
import numpy as np
import argparse
import json
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from models.pretraining_nasbench101 import configs
from utils.utils import load_json, preprocessing
from models... |
11556675 | import numpy as np
import torch
import torch.distributions as td
import torch.nn as nn
class DenseModel(nn.Module):
def __init__(self, feature_size: int, output_shape: tuple, layers: int, hidden_size: int, dist='normal',
activation=nn.ELU):
super().__init__()
self._output_shape = ... |
11556680 | from flask_login import current_user
from wtforms import ValidationError
from overhave.admin.views.base import ModelViewProtected
from overhave.db import Role
class DraftView(ModelViewProtected):
""" View for :class:`Draft` table. """
details_template = "draft_detail.html"
can_delete = True
column_l... |
11556696 | import matplotlib
matplotlib.use('Agg')
import numpy as np
import skfuzzy as fuzz
import matplotlib.pyplot as plt
import Adafruit_DHT
import RPi.GPIO as GPIO
import time
print('initialization...')
### initialization GPIO
relay_pin = 26
GPIO.setmode(GPIO.BCM)
GPIO.setup(relay_pin, GPIO.OUT)
sensor = Adafruit_DHT.D... |
11556703 | import sys
sys.path.append('../')
import torch
import torch.nn as nn
import math, random, sys
import argparse
from fast_jtnn import *
import rdkit
def load_model(vocab, model_path, hidden_size=450, latent_size=56, depthT=20, depthG=3):
vocab = [x.strip("\r\n ") for x in open(vocab)]
vocab = Vocab(vocab)
... |
11556719 | import json
import os
from overrides import overrides
from typing import Any, List
from repro.data.output_writers import OutputWriter
from repro.data.types import InstanceDict
@OutputWriter.register("default")
class DefaultOutputWriter(OutputWriter):
"""
Writes a jsonl file with keys for the `instance_id`, `... |
11556735 | import unittest
from myapp import create_app
from myapp.models.db_orm import db
from myapp.models.db_models import User
class TestModelUser(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.c... |
11556764 | from functools import wraps
from django.core.exceptions import PermissionDenied
from django.views.decorators.csrf import csrf_exempt
from canvas import util, knobs, browse
from canvas.api_decorators import json_service
from canvas.exceptions import ServiceError
from canvas.metrics import Metrics
from canvas.redis_mod... |
11556772 | class OperatingSystem(object,ICloneable,ISerializable):
"""
Represents information about an operating system,such as the version and platform identifier. This class cannot be inherited.
OperatingSystem(platform: PlatformID,version: Version)
"""
def Clone(self):
"""
Clone(self: OperatingSystem) ->... |
11556783 | import io
import json
import requests
import pytest
from AzureStorage import (ASClient, storage_account_list, storage_account_create_update,
storage_blob_service_properties_get, storage_blob_service_properties_set,
storage_blob_containers_create, storage_blob_contai... |
11556784 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
#--------------------------------------------------Base Module--------------------------------------------------#
class DepthwiseSeparableConv(nn.Module):
def __init__(self, input_dim, out_dim, kernel_size, conv_dim=1, padding=0, bias... |
11556795 | from test_project.settings import MIDDLEWARE
from django.contrib.auth.models import Group, User
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from test_project.testapp.models import UserAccount
class ViewsTestCase(APITestCase):
def setUp(self):
UserAccount.objects... |
11556809 | import pytest
from django.urls import reverse
from articles.views import ArticleListView
from tests.factories import ArticleFactory
@pytest.mark.django_db
class TestVirtualFields(object):
def _request(self, admin_client):
response = admin_client.get(reverse('articles:list'))
assert response.stat... |
11556842 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from mwptoolkit.model.Seq2Seq import dns,ept,groupatt,lstm,mathen,rnnencdec,saligned,transformer,rnnvae
from mwptoolkit.model.Seq2Seq.dns import DNS
from mwptoolkit.model.Seq2Seq.ept import EPT
from mwptoolkit.... |
11556845 | from .backend import Backend
import torch.multiprocessing as mp
from hypergan.gan_component import ValidationException, GANComponent
import torch.utils.data as data
import hyperchamber as hc
import hypergan as hg
import copy
import torch
import time
def create_input(input_config):
klass = GANComponent.lookup_funct... |
11556903 | import math
import re
from decimal import Decimal
class NumUtil(object):
"""
- number util
"""
UK = 100000000 # 억
@staticmethod
def int2digit(n, base=10): # base: 진수
res = ''
while n > 0:
n, r = divmod(n, base)
res = str(r) + res
return res
... |
11556918 | import torch
import torch.nn as nn
from torch.autograd import Variable
class DescriptionEncoder(nn.Module):
"""
This class is for the Description Encoder
which is a stacked LSTM. It can be used to
encode a given input, a description of an entity,
and outputs the embedding for that entity.
"""
... |
11556932 | import pytest
from pytest_cases import fixture
class TestMethod:
@pytest.fixture
def pytest_fxt(self):
return "Hello"
def test_with_pytest(self, pytest_fxt):
# succeeds
assert pytest_fxt == "Hello"
@fixture
def cases_fxt(self):
return "Hello"
def test_with_ca... |
11556965 | import base64
import binascii
import os
import os.path
import cryptography
from cryptography import x509
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec, utils
from cryptoauthlib import *
... |
11556991 | from distutils.core import setup, Extension
import platform
libname = 'ivhc'
if platform.system()=='Darwin':
libname = 'ivhc.mac'
module = Extension('ivhc',
sources = ['ivhcNoiseEst.cpp'],
include_dirs = [],
libraries = [libname],
... |
11556995 | from functools import reduce
from Obj3D import Point3D, Sphere, Cone, calculateBound, calScaleRatio
import numpy as np
from numpy import linalg as LA
from scipy.spatial import distance_matrix
def getObjList(nodes, graph, node_idx=None):
if node_idx:
# 球体索引列表
sphere_idxs = [node_idx]+list(graph[node... |
11556999 | import re
# from whoosh.fields import NGRAMWORDS, TEXT, Schema
# from whoosh.filedb.filestore import RamStorage
# from whoosh.qparser import OrGroup, QueryParser
# from whoosh.query import Every
class SimpleIndex():
'''
Right now we're just doing substring search because indexing
made startup too slow, b... |
11557000 | from IPython.terminal.interactiveshell import TerminalInteractiveShell
TerminalInteractiveShell.confirm_exit = False
c = get_config()
try:
import line_profiler
c.TerminalIPythonApp.extensions = [
'line_profiler',
]
except Exception:
pass
|
11557068 | def get_base_model(app_label, model):
from django.contrib.contenttypes.models import ContentType
return ContentType.objects.get(app_label=app_label.lower(), model=model.lower()).model_class()
def normalise_field(text):
return text.strip().replace('(', '::').replace(')', '').replace(".", "__")
|
11557076 | import requests
import time
from influxdb import InfluxDBClient
from urllib.parse import urlparse
CURRENT_TIMESTAMP = int(time.time())
class Annotation:
"""
An annotation that we want to create
"""
def __init__(self, title, tags, description='', start=CURRENT_TIMESTAMP, end=CURRENT_TIMESTAMP):
... |
11557081 | import tensorflow as tf
def independent_outputs(featuremap, output_names, num_channels, filter_width, padding, activation):
outputs = dict()
for name in output_names:
outputs[name] = tf.layers.conv1d(featuremap, num_channels, filter_width, activation=activation, padding=padding)
return outputs |
11557134 | import numpy as np
import pytest
import xarray as xr
import py3dep
from py3dep import MissingAttribute, MissingColumns, MissingCRS, MissingDependency
def test_missing_nodata():
with pytest.raises(MissingAttribute) as ex:
dem = xr.DataArray(np.random.randn(2, 3), dims=("x", "y"), coords={"x": [10, 20]})
... |
11557156 | import os
import dgl
import torch
import pickle
import pysmiles
from data_processing import networkx_to_dgl
class PropertyPredDataset(dgl.data.DGLDataset):
def __init__(self, args):
self.args = args
self.path = '../data/' + args.dataset + '/' + args.dataset
self.graphs = []
self.la... |
11557157 | import viewflow
from unittest.mock import patch, ANY, call
@patch("viewflow.parsers.dependencies_r_patterns.custom_get_dependencies")
@patch("viewflow.parsers.dependencies_r_patterns.get_dependencies_default")
def test_default(get_default_mock, get_custom_mock):
viewflow.create_dag("./tests/projects/rmd/default_... |
11557164 | from cryptography.fernet import Fernet
import stepic
import tweepy
from PIL import Image
from termcolor import colored
import pyfiglet
import sys
import os
COMMANDS = {'help':['Shows this help'],
'recon':['Recon module. Perform reconnaisance on the target system and upload Intel on Dropbox'],
'... |
11557179 | import pkg_resources # part of setuptools
__version__ = pkg_resources.require("concoct")[0].version
|
11557189 | import tkinter as tk
import tkinter.font as tk_font
import os
from tkinter import ttk
class ContextMenu(tk.Listbox):
def __init__(self, parent, *args, **kwargs):
tk.Listbox.__init__(self, parent, *args, **kwargs)
self.font_family = parent.font_family
self.font_color = parent.menu_fg
... |
11557232 | import copy
from pyschema import types
import pyschema
import os
import sys
from collections import defaultdict
DEFAULT_INDENT = " " * 4
class SourceGenerationError(Exception):
pass
def to_python_source(classes, indent=DEFAULT_INDENT):
"""Convert a set of pyschemas to executable python source code
Cur... |
11557257 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from .occ_targets_template import OccTargetsTemplate
from ....utils import coords_utils, point_box_utils
class OccTargets3D(OccTargetsTemplate):
def __init__(self, model_cfg, voxel_size, point_cloud_range, data_cfg, grid_size,
... |
11557280 | import ast
import astpretty as ap
# import typing
import sys
import argparse
import prometeo
import os
import platform
import subprocess
from strip_hints import strip_file_to_string
import json
import numpy as np
# from prometeo.mem.ast_analyzer import compute_reach_graph
from prometeo.mem.ast_analyzer import ast_visi... |
11557287 | from contextlib import closing
from dbcat import Catalog, catalog_connection, init_db, pull
from piicatcher.catalog import Store
class DbStore(Store):
@classmethod
def save_schemas(cls, explorer):
catalog: Catalog = catalog_connection(explorer.catalog_conf)
with closing(catalog) as catalog:
... |
11557346 | import datetime
from bookstore import db
from bookstore.models import OrderList, Books
from flask_sqlalchemy import SQLAlchemy
#start of the month
def calc_start(y, m):
return datetime.datetime(y, m, 1)
#end of the month
def calc_end(y, m):
if m == 2:
if (y % 4) == 0:
if (y % 100) == 0:
if (y % 400) == 0... |
11557356 | class Folder:
def __init__(self, name):
self.name = name
self.children = {}
def add_child(self, child):
pass
def move(self, new_path):
pass
def copy(self, new_path):
pass
def delete(self):
pass
class File:
def __init__(self, name, contents):
... |
11557361 | import tkinter as tk
# --- functions ---
def mouse_wheel(event):
global number
# respond to Linux or Windows wheel event
if event.num == 5 or event.delta == -120:
number -= 1
if event.num == 4 or event.delta == 120:
number += 1
label['text'] = number
# --- main ---
... |
11557363 | from chromeless import Chromeless as _Chromeless, dumps
class Chromeless(_Chromeless):
def __invoke_local(self, dumped):
print("__invoke_local")
print(dumped)
with open('/tmp/dumped.txt', 'w') as f:
f.write(dumped)
return dumps(("hoge", {"status": "succeess"}))
def ge... |
11557389 | import cv2
# import speed_prediction
import tools.speed_prediction as speed_prediction
# from core.config import cfg
# from core.utils import read_class_names
# is_vehicle_detected = [0]
left_vehicle_counter = 0
right_vehicle_counter = 0
bottom_vehicle_counter = 0
LEFT_INTERSECTION_ROI_POSITION = 400
LEFT_INTERSECTI... |
11557407 | import tensorflow as tf
in_b_ = tf.compat.v1.placeholder(dtype=tf.bool, shape=[2], name="Hole")
in_x_ = tf.compat.v1.placeholder(dtype=tf.float32, shape=[2, 3], name="Hole")
in_y_ = tf.compat.v1.placeholder(dtype=tf.float32, shape=[2, 3], name="Hole")
where_ = tf.compat.v1.where(in_b_, in_x_, in_y_)
|
11557423 | from __future__ import annotations
from .configs import *
from . import shared as td
class MTP(BaseObject): # nocov
"""
[MTProto Protocal](https://core.telegram.org/mtproto)
This class is for further future developments and has no usage for now.
### Attributes:
`Environment` (`class`): MTP... |
11557439 | import ee
from ee_extra.JavaScript.install import install as ee_install
from ee_extra.JavaScript.install import uninstall as ee_uninstall
from ee_extra.JavaScript.main import ee_require
from .extending import extend
@extend(ee)
def require(module):
"""Loads and executes a JavaScript GEE module.
All modules ... |
11557486 | from typing import Dict, Any, List
import tensorflow as tf
from utils import MLP
from .sparse_graph_model import Sparse_Graph_Model
from tasks import Sparse_Graph_Task
from gnns import sparse_gnn_edge_mlp_layer
class No_Struct_MLP_Model(Sparse_Graph_Model):
@classmethod
def default_params(cls):
para... |
11557502 | import tensorflow as tf
class Inception(tf.keras.layers.Layer):
def __init__(self, c1, c2, c3, c4):
super().__init__()
# 线路1,单1 x 1卷积层
self.p1_1 = tf.keras.layers.Conv2D(c1, kernel_size=1, activation='relu', padding='same')
# 线路2,1 x 1卷积层后接3 x 3卷积层
self.p2_1 = tf.keras.laye... |
11557505 | import json
import os
import yaml
import tempfile
from unittest import TestCase
from conman.conman_file import ConManFile
def _make_config_file(file_type, content):
# create temp filename
f = tempfile.NamedTemporaryFile(suffix=file_type, delete=False)
# write content
f.write(content.encode('utf-8'))
... |
11557517 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='TxtOrg',
version='1.0.0',
author='<NAME>, <NAME>, <NAME>',
author_email='<EMAIL>',
packages=['textorganizer'],
scripts=['bin/txtorg'],
license='LICENSE.txt',
description='Tool to ... |
11557521 | import time
import torch.autograd
import torch.nn as nn
from core.label_smooth import LabelSmoothCrossEntropyLoss
from core.utils import *
from core.warmup_scheduler import GradualWarmupScheduler
class View(nn.Module):
"""
Reshape data from 4 dimension to 2 dimension
"""
def forward(... |
11557565 | import numpy as np
from utils import is_image_file, mod_crop
from hashTable import hashTable
Qangle = 24
Qstrenth = 3
Qcoherence = 3
datasets = './datasets/General100/'
rate = 3
images_path = [os.path.join(datasets, x) for x in os.listdir(datasets) if is_image_file(x)]
print("Load dataset ", len(images_path))
H = n... |
11557672 | from tensorflow_functions import cosine_knn
import collections
import numpy as np
import logging
from embedding import load_embedding
import operator
from sklearn.cluster import KMeans
from utils import length_normalize, normalize_questions, normalize_vector, calculate_cosine_simil, perf_measure
import sklearn.metrics
... |
11557683 | import os
from time import sleep
from multiprocessing import Process
def test(i):
print(f"[{i}]PID:{os.getpid()},PPID:{os.getppid()}")
sleep(1)
def main():
p_list = [Process(target=test, args=(i, )) for i in range(10)]
for p in p_list:
p.start()
for p in p_list:
p.join()
... |
11557727 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.surface_construction_elements import WindowMaterialScreenEquivalentLayer
log = logging.getLogger(__name__)
class TestWindowMaterialScreenEquivalentLayer(unittest.TestCase):
... |
11557773 | import abc
class BaseWrapper(metaclass=abc.ABCMeta):
def __init__(self, env=None):
self.env = env
def set_env(self, env):
self.env = env
@abc.abstractmethod
def step(self, action):
raise NotImplementedError
@abc.abstractmethod
def reset(self):
'''
rese... |
11557824 | import os
from typing import Mapping, Optional, TextIO, Tuple, Union
from .context import Context
from .output import Renderer, render
def determine_format(filename: Optional[str], choices: Mapping[str, Renderer], default: str) -> str:
if filename:
ext = os.path.splitext(filename)[1].lstrip('.').lower()
... |
11557860 | from collections import Counter
import glob
import os
from tqdm import tqdm
import torch
import pandas as pd
import torch.utils.data as tud
def load_clean_aol(folder, use_tqdm=True):
ct_names = glob.glob(os.path.join(folder, 'clean-*.txt'))
dfs = []
if use_tqdm: ct_names = tqdm(ct_names)
for ct_name ... |
11557902 | import pandas as pd
import plotly.express as px
def iplot_bar_polar(self, theta, color, r='auto', template='xgridoff',
color_continuous_scale='auto', **kwds):
"""
It uses plotly.express.bar_polar.
In a polar bar plot, each row of 'color' is represented as a wedge mark in polar coordinat... |
11557929 | import os
import sys
import json
from sklearn.model_selection import train_test_split
def load_labels(database_path):
if os.path.isdir(database_path):
labels = os.listdir(database_path)
return labels
def get_dataset(database_path):
if not os.path.exists(database_path):
raise IOError('n... |
11557935 | from typing import List
from UE4Parse.BinaryReader import BinaryStream
from UE4Parse.Assets.Objects.Structs.Vector import FVector
class FPositionVertexBuffer:
Verts: List[FVector]
Stride: int
NumVertices: int
def __init__(self, reader: BinaryStream):
self.Stride = reader.readInt32()
... |
11557949 | import unittest
import odil
class TestSelector(unittest.TestCase):
def test_default_constructor(self):
selector = odil.webservices.Selector()
self.assertFalse(selector.is_study_present())
self.assertFalse(selector.is_series_present())
self.assertFalse(selector.is_instance_present()... |
11557952 | from re import compile
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.views import redirect_to_login
if hasattr(settings, "LOGIN_REQUIRED_URLS"):
URLS = [compile(expr) for expr in settings.LOGIN_REQUIRED_URLS]
class ActiveUserRequiredMiddleware:
... |
11557963 | import argparse
import json
import os
from typing import List, Tuple
import numpy as np
from PIL import Image, ImageFile
import tensorflow as tf
from tqdm import tqdm
# A couple of images are a bit large, we set this flag to load them properly.
ImageFile.LOAD_TRUNCATED_IMAGES = True
parser = argparse.ArgumentParser... |
11557969 | import pytest
import pandas as pd
import sweat
from sweat.io import strava
from .utils import sweatvcr
def test_top_level_import():
assert sweat.read_strava == strava.read_strava
@sweatvcr.use_cassette()
def test_read_strava():
activity = sweat.read_strava(
activity_id="3547667536", access_token="... |
11558023 | import os
import sys
import inspect
def init():
# realpath() with make your script run, even if you symlink it :)
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
# use this if you want to inclu... |
11558026 | import numpy as np
from vulcanai.net import Network
import theano.tensor as T
from vulcanai.utils import get_one_hot
from vulcanai import mnist_loader
from vulcanai.model_tests import run_test
(train_images, train_labels, test_images, test_labels) = mnist_loader.load_fashion_mnist()
train_labels = get_one_hot(tr... |
11558028 | import os
from payton.scene import Scene
from payton.scene.collision import CollisionTest
from payton.scene.geometry import Wavefront
from payton.scene.gui import info_box
direction = 0
def motion(period, total):
global scene, direction
pos = scene.objects["scar2"].position
apos = scene.objects["acar2"]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.