id
stringlengths
3
8
content
stringlengths
100
981k
473377
from ..visualize import plot from ..utils import use_gpu, seed, U from ..data_structures import DotDict import framework import os import shutil import sys from datetime import datetime import socket from typing import List, Callable, Optional, Any from .saver import Saver from .argument_parser import ArgumentParser im...
473382
import copy import os import random import string import unittest from contextlib import redirect_stdout from os import path import io import torch from closest_string.task.dataset_generator_synthetic import ClosestStringDatasetGenerator from edit_distance.models.cnn.model import CNN from edit_distance.models.feedforw...
473389
from __future__ import unicode_literals from django.apps import AppConfig class SimpleImageUploadConfig(AppConfig): name = 'simple_image_upload'
473465
import os import sys import requests import re with open(sys.argv[1]) as fp: lines = fp.readlines() flag = False start = 0 end = 0 for i, line in enumerate(lines): if "MODELS_HASH" in line: flag = True start = i continue if flag: if line.startswith("}"): end...
473516
import pytest from model_mommy import mommy from rest_framework.test import APIClient from reqs.models import Agency, AgencyGroup, Policy, Requirement, Topic @pytest.mark.django_db @pytest.mark.parametrize('path,num_results', ( ('/topics/', 10), ('/topics/?name=0000000000', 1), ('/topics/?name=000000', 0...
473518
from __future__ import absolute_import from celery import Celery from django.conf import settings app = Celery('backend') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request))...
473535
import base64 import binascii import pytest from aead import AEAD def test_vector(): key = base64.urlsafe_b64encode(binascii.unhexlify( b"<KEY>" )) data = binascii.unhexlify( b"41206369706865722073797374656d206d757374206e6f742062652072657175" b"6972656420746f20626520736563726574...
473542
from metann.utils.containers import DefaultList def test_default_list(): l = DefaultList() l.fill([1, 2, 3, 4]) for i, _ in zip(l, range(10)): print(i)
473559
import base64 from functools import wraps from django.contrib.auth.models import AnonymousUser as DjangoAnonymousUser, User as DjangoUser from django.core.exceptions import PermissionDenied from django.http import HttpResponse from apps.canvas_auth.backends import authenticate from apps.canvas_auth.models import Anon...
473582
from django.conf import settings from django.conf.urls import url from django.urls import include, path from .views import login, launch, get_jwks, configure, score, scoreboard urlpatterns = [ url(r'^login/$', login, name='game-login'), url(r'^launch/$', launch, name='game-launch'), url(r'^jwks/$', get_jwk...
473620
from django.contrib.auth.models import AbstractUser from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from .managers import CustomUserManager class CustomUser(AbstractUser): class Meta: verbose_name = _("user") verbose_name_plur...
473643
import cgi def notfound(environ, start_response): start_response('404 Not Found', [('content-type', 'text/plain')]) return ['404 Not Found'] class PathDispatcher: def __init__(self): self.pathmap = {} def __call__(self, environ, start_response): path = environ['PATH_INFO'] ...
473652
from .f_AlbumWinners_publisher import AlbumWinnersPublisher from .f_AlbumWinners_subscriber import AlbumWinnersSubscriber from .f_Store import Client as FStoreClient from .f_Store import Iface as FStoreIface from .ttypes import *
473653
from flask.ext.assets import Bundle app_css = Bundle( 'app.scss', filters='scss', output='styles/app.css', depends=('*.scss') ) images_png = Bundle( 'clock.gif', 'images/guiders_x_button.jpg', output='guiders_arrows.png' ) app_js = Bundle( 'app.js', filters='jsmin', output='sc...
473673
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils import timezone def get_affiliate_id(request, expiry_period=None): expiry_period = expiry_period or getattr(settings, 'AFFILIATE_EXPIRY_PERIOD', None) try: affiliate_id = request.affiliate_id ...
473708
from django.conf.urls import re_path from .views import ( schedule_conference, schedule_edit, schedule_list, schedule_list_csv, schedule_detail, schedule_slot_edit, schedule_json, ) urlpatterns = [ re_path(r"^$", schedule_conference, name="schedule_conference"), re_path(r"^edit/$",...
473711
from typing import Iterable from typing import List from typing import Union from pathlib import Path from typeguard import check_argument_types import warnings class WordTokenizer: def __init__( self, delimiter: str = None, non_linguistic_symbols: Union[Path, str, Iterable[str]] = None, ...
473716
from enum import Enum class FilterType(Enum): """ Filter type (filter densities, or gradients only) """ NoFilter = 0 Density = 1 Sensitivity = 2 class InterpolationType(Enum): """ Material interpolation scheme: classic SIMP, or Pedersen (for self-weight problems) """ SIMP = 1...
473721
import argparse import os from os.path import join as pjoin import pandas as pd from src.evaluation import Evaluator import zipfile import shutil debug_mode = 0 def mkdir(d): if not os.path.exists(d): os.makedirs(d) def build_ref_pred_pair(ref_dict, pred_dict): ref_list, pred_list = [], [] for ...
473736
from .. import miscellaneous class BaseEntity(object): is_fetched = True def print(self, to_return=False, columns=None): """ :param to_return: :param columns: """ return miscellaneous.List([self]).print(to_return=to_return, columns=columns) def to_df(self, show_al...
473751
import taso as ts import sys seq_length = 512 hidden_dims = 768 batch_size = int(sys.argv[1]) def attention(graph, input, heads): embed = input.dim(1) # embedding len assert input.dim(1) % heads == 0 weights = list() for i in range(3): weights.append(graph.new_weight(dims=(embed, embed))) ...
473759
from typing import Text, List __all__ = [ 'Tokenizer' ] # noinspection SpellCheckingInspection class Tokenizer: def tokenize(self, sentence: Text) -> List[Text]: raise NotImplementedError()
473760
from six.moves import zip from smqtk.algorithms import Classifier from smqtk.representation.data_element import from_uri class IndexLabelClassifier (Classifier): """ Applies a listing of labels (new-line separated) to input "descriptor" values, which is actually a vector of class confidence values. "...
473778
from .regressors import KNeighborsRegressor from .classifiers import KNeighborsClassifier __all__ = ['KNeighborsRegressor', 'KNeighborsClassifier']
473842
from __future__ import absolute_import, division, print_function from scitbx.array_family import flex # import dependency
473904
import datetime import re from bson.objectid import ObjectId from flask import request, redirect, url_for, flash, render_template, Response from pymongo import DESCENDING from web import captcha from web import client from web.queues import crawler_q from web.config import * from web.filters import * from web import...
473912
from django.contrib import admin from django.contrib.admin import register, models as admin_models from django.utils.safestring import mark_safe from tracker import models from .filters import AdminActionLogEntryFlagFilter from .forms import LogAdminForm from .util import CustomModelAdmin @register(models.Log) class...
473913
import torch from torch import multiprocessing, cuda from torch.utils.data import DataLoader import torch.nn.functional as F from torch.backends import cudnn import numpy as np import importlib import os import voc12.dataloader from misc import torchutils, imutils import cv2 cudnn.enabled = True from step.gradCAM imp...
473989
from .context import Context from .constraint import PrimExprConstraint, VarConstraint, StmtConstraint, BlockConstraint, PrimFuncConstraint from .constraint import Constraint
473997
from carla_utils import carla import numpy as np from typing import List, Any import pickle import os from os.path import join from ..basic import Data, YamlConfig from ..world_map import Role, get_topology from ..augment import GlobalPath from ..agents import AgentListMaster, BaseAgent from .scenario import Scenari...
474002
import pyblish.api class FusionSaveComp(pyblish.api.ContextPlugin): """Save current comp""" label = "Save current file" order = pyblish.api.ExtractorOrder - 0.49 hosts = ["fusion"] families = ["render"] def process(self, context): comp = context.data.get("currentComp") asser...
474015
import pytest import numpy as np import pybinding as pb from pybinding.repository import graphene def silence_parallel_output(factory): factory.hooks.status.clear() factory.config.pbar_fd = None factory.config.filename = None def test_sweep(baseline, plot_if_fails): @pb.parallelize(v=np.linspace(0,...
474024
from . import libevt class EVTErrCode: EVT_OK = 0 EVT_INTERNAL_ERROR = -1 EVT_INVALID_ARGUMENT = -2 EVT_INVALID_PRIVATE_KEY = -3 EVT_INVALID_PUBLIC_KEY = -4 EVT_INVALID_SIGNATURE = -5 EVT_INVALID_HASH = -6 EVT_INVALID_ACTION = -7 EVT_INVALID_BINARY = -8 EVT_INVALID_JSON = -9 ...
474071
from modules.basemodule import BaseModule from pprint import pformat class Eval(BaseModule): def alias(self, line): if line.startswith('#py '): rest = line[4:] self.mud.log("\n" + pformat(eval(rest))) return True elif line.startswith('#pye '): rest =...
474129
import os import sys sys.path.append ('opy') import opy from setuptools import setup import codecs def read (*paths): with codecs.open (os.path.join (*paths), 'r', encoding = 'utf-8') as aFile: return aFile.read() setup ( name = 'Opy', version = opy.programVersion, description = 'OPY - Obfusca...
474142
import logging from gearman.errors import UnknownCommandError from gearman.protocol import get_command_name gearman_logger = logging.getLogger(__name__) class GearmanCommandHandler(object): """A command handler manages the state which we should be in given a certain stream of commands GearmanCommandHandler d...
474149
import json import os import time import argparse parser = argparse.ArgumentParser(description="Post processing for converted explanation") parser.add_argument("--data", type=str, default=None, help="path to preprocessed data") parser.add_argument("--save", type=str, default='./', help="path for saving the data") args...
474156
import os def move_files(abs_dirname,speaker,datapath,trainSet,cvSet,tstSet): """Move files into subdirectories.""" for subdir in os.listdir(abs_dirname): files = [os.path.join(abs_dirname,subdir, f) for f in os.listdir(os.path.join(abs_dirname,subdir))] cv_dir = os.path.abspath(os.path.join...
474227
import asyncio import json from unittest import mock from mmpy_bot import ExamplePlugin, Message, Settings, WebHookExample from mmpy_bot.driver import Driver from mmpy_bot.event_handler import EventHandler from mmpy_bot.wrappers import WebHookEvent def create_message( text="hello", mentions=["q<PASSWORD>"], ...
474248
from moai.data.datasets.generic.structured_images import StructuredImages __all__ = [ "StructuredImages", ]
474254
from src.alerter.alert_severities.severity import Severity from src.alerter.alert_severities.severity_code import SeverityCode
474263
import struct LINK_TYPES = { 'BLE': 251, 'ZIGBEE': 195, 'H4': 201, } class PcapFile(object): def __init__(self, filename, link_type="H4"): self.filename = filename self.link_type = LINK_TYPES[link_type] self._file = open(self.filename, "wb") self._file.write(struct.pac...
474275
import responses from wiremock.tests.base import BaseClientTestCase, attr from wiremock.client import Scenarios class ScenariosResourceTests(BaseClientTestCase): @attr("unit", "scenarios", "resource") @responses.activate def test_reset_scenarios(self): responses.add(responses.POST, "http://localh...
474307
from robovat.math.euler import Euler from robovat.math.orientation import Orientation from robovat.math.point import Point from robovat.math.pose import get_transform from robovat.math.pose import Pose from robovat.math.quaternion import Quaternion
474315
class Stack: def __init__(self): self.stack = [] self.max_stack = [] def push(self, val): self.stack.append(val) if not self.max_stack or val > self.stack[self.max_stack[-1]]: self.max_stack.append(len(self.stack) - 1) def pop(self): if not self.stack: ...
474333
import doctest import optparse import pytest try: import pathlib except ImportError: import pathlib2 as pathlib from flake8_rst.rst import RST_RE, apply_default_groupnames, apply_directive_specific_options, merge_by_group from flake8_rst.sourceblock import SourceBlock, _extract_roles from hypothesis import as...
474334
from fidesops.schemas.masking.masking_configuration import ( RandomStringMaskingConfiguration, ) from fidesops.service.masking.strategy.masking_strategy_random_string_rewrite import ( RandomStringRewriteMaskingStrategy, ) def test_mask_with_value(): request_id = "123432" config = RandomStringMaskingCo...
474357
from polymath.codegen.dnnweavergen.dnnweaver2.scalar.dtypes import FQDtype import numpy as np import math class Tensor(object): """ Tensor class for computations n-dimensional array """ def __init__(self, shape, name, data, dtype=FQDtype.FP32, trainable=False): if isinstance(shape, int)...
474405
from io import StringIO from unittest.mock import patch from django.core.management import call_command from django.core.management.base import CommandError from django.test import TestCase from ditto.flickr.factories import AccountFactory, UserFactory class FetchFlickrAccountUserTestCase(TestCase): def setUp(s...
474410
pkgname = "firmware-ipw2200" pkgver = "3.1" pkgrel = 0 pkgdesc = "Firmware for the Intel PRO/Wireless 2200BG wifi cards" maintainer = "q66 <<EMAIL>>" license = "custom:ipw2200" url = "http://ipw2200.sourceforge.net" source = f"http://firmware.openbsd.org/firmware-dist/ipw2200-fw-{pkgver}.tgz" sha256 = "c6818c11c18cc030...
474415
from typing import Dict,List from django.apps import apps from django.forms import models from automatic_crud.data_types import Instance,DjangoForm def get_model(__app_name:str,__model_name:str) -> Instance: # return the model corresponding to the application name and model name sent return apps.get_model(ap...
474425
import pytest from tsplib95 import fields as F from tsplib95 import exceptions as E @pytest.fixture def field(): return F.DemandsField('foo') @pytest.mark.parametrize('text,value,exc', [ ('1 2', {1: 2}, None), ('1 2\n2 3', {1: 2, 2: 3}, None), ('2 x 0', None, E.ParsingError), ]) def test_parse(fiel...
474435
import maya.api.OpenMaya as om def mobject_from_name(name): sel_list = om.MSelectionList() sel_list.add(name) return sel_list.getDependNode(0)
474472
import select class POLL_EVENT_TYPE: READ = 1 WRITE = 2 ERROR = 4 class Poller(object): def subscribe(self, descr, callback, eventMask): raise NotImplementedError def unsubscribe(self, descr): raise NotImplementedError def poll(self, timeout): raise NotImplementedEr...
474475
from typing import Callable from typing import Tuple import tensorflow as tf from libspn_keras.sum_ops.base import SumOpBase from libspn_keras.sum_ops.batch_scope_transpose import batch_scope_transpose class SumOpSampleBackprop(SumOpBase): """ Sum op with hard EM signals in backpropagation when computed thr...
474513
import os import re import torch import random import time import logging import argparse import subprocess import numpy as np from tqdm import tqdm, trange from collections import defaultdict from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DataLoader, SequentialSampler from transformers....
474575
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from forums.models import UserProfile CustomUser = get_user_model() class UserProfileInline(admin.StackedInline): model =...
474630
import json from zipfile import ZipFile import pandas as pd from download import download from dicodile.config import DATA_HOME def get_gait_data(subject=1, trial=1): """ Retrieve gait data from this `dataset`_. Parameters ---------- subject: int, defaults to 1 Subject identifier. ...
474632
import numpy as np from sklearn.base import RegressorMixin from sklearn.linear_model.base import LinearModel from sklearn.utils import check_X_y, check_array, as_float_array from sklearn.utils.validation import check_is_fitted from scipy.linalg import svd import warnings class BayesianLinearRegression(RegressorMixin...
474725
import importlib.metadata as im import pytest @pytest.mark.parametrize("name", ("foo-bar", "foo_bar", "Foo-Bar")) def test_distribution(name): assert im.distribution(name) is not None def test_unknown_package(): with pytest.raises(im.PackageNotFoundError): im.distribution("bar") def test_version(...
474780
from datetime import date, timedelta from maintenance.models import TaskSchedule from logical.models import Database def register_schedule_task_restart_database(hostnames): today = date.today() try: databases = Database.objects.filter( databaseinfra__instances__hostname__hostname__in=host...
474837
from .variable_plotter import VarPlot from .base import get_os_friendly_name class MonPlot (VarPlot): def plot(self, keyx="clock", keyy=None): # assert len(keys) == 1, "We only support a single key at the moment." # key = keys[0] # abscissa_key = self.options.get("abscissa_key", "clock") # ...
474917
import json import os import horovod.tensorflow as hvd hvd.init() with open(os.path.join('/opt/ml/model/local-rank-%s-rank-%s' % (hvd.local_rank(), hvd.rank())), 'w+') as f: basic_info = {'local-rank': hvd.local_rank(), 'rank': hvd.rank(), 'size': hvd.size()} print(basic_info) json.dump(basic_info, f)
474919
from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.schema import FetchedValue from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.ext.hybrid import hybrid_property from app.api.utils.models_mixins import Base, AuditMixin from app.extensions import db from app.api.now_application...
474933
from builtins import object from yapsy.IPlugin import IPlugin import jsonpickle import lxml.etree as etree from elasticsearch_dsl import Search from elasticsearch_dsl.query import Match from opentargets_urlzsource import URLZSource from mrtarget.common.UniprotIO import Parser import logging class ReactomeRetriever(ob...
474958
from multiprocessing import Process from bilibili import Bilibili from config import config from mirrativ import Mirrativ from openrec import Openrec from tools import check_ddir_is_exist, get_logger from twitcasting import Twitcasting from youtube import Youtube, start_temp_daemon logger = get_logger() class Even...
474975
import json import io def util_load_json(path): with io.open(path, mode='r', encoding='utf-8') as f: return json.loads(f.read()) def test_ip_command(requests_mock): from IPQualityScore import Client, ip_command mock_response = util_load_json('test_data/ip_response.json') requests_mock.get('h...
474981
from pyramid.view import view_config import logging log = logging.getLogger(__name__) @view_config(route_name='appcache', http_cache=0, renderer='../templates/geoportailv3.appcache') def appcache(request): request.response.content_type = 'text/cache-manifest' return {}
474983
import configparser from os.path import join def config(path, section, option, name='scrapy.cfg', default=None): """ parse scrapy config :param path: config path :param section: config section :param option: other params :param name: file name :param default: :return: """ try: ...
474988
from dataclasses import dataclass from .flyweight import Flyweight @dataclass(frozen=True) class Gametime(Flyweight): """ NHL gametime object. This object represents a unique time of the game. There are convenience properties to convert the gametime into convenient formats. Parameters -----...
475076
from django.conf.urls import include from django.urls import path from rest_framework.routers import DefaultRouter from search.views import NewsDocumentView app_name = "search" router = DefaultRouter() router.register(r"", viewset=NewsDocumentView, basename="search") urlpatterns = [ path("", include(router.url...
475078
import pytest from flex.exceptions import ValidationError from flex.validation.request import ( validate_request, ) from flex.error_messages import MESSAGES from flex.constants import ( ARRAY, BOOLEAN, CSV, INTEGER, PATH, PIPES, QUERY, SSV, STRING, TSV, ) from tests.factori...
475091
import os import zipfile from shlex import split from subprocess import PIPE, Popen from uuid import uuid4 from django.conf import settings from rest_framework import exceptions def _linuxCopy(src, dest): src_path = src.replace(' ', '\ ') dest_path = dest.replace(' ', '\ ') # -R, -r, --recursive # ...
475111
import pytest from ..helpers import * import hail.experimental.time as htime @skip_unless_spark_backend() def test_strftime(): assert hl.eval(htime.strftime("%A, %B %e, %Y. %r", 876541523, "America/New_York")) == "Friday, October 10, 1997. 11:45:23 PM" assert hl.eval(htime.strftime("%A, %B %e, %Y. %r", 876541...
475115
import math from typing import Optional from cftool.misc import Incrementer from ...protocol import TrainerMonitor @TrainerMonitor.register("basic") class BasicMonitor(TrainerMonitor): def __init__(self, patience: int = 25): # type: ignore super().__init__() self.patience = patience sel...
475116
import os import sys import errno import subprocess import glob import shutil from contextlib import contextmanager def normpath(path): """Normalize UNIX path to a native path.""" normalized = os.path.join(*path.split("/")) if os.path.isabs(path): return os.path.abspath("/") + normalized else: ...
475118
try: from public_config import * except ImportError: pass PORT = 9030 SERVICE_NAME = 'message'
475132
import logging import os def load_word_dict(opt): """ Load word dictionary. Naming format: str(opt.word_dict_size) + '_' + opt.name + '.vocab.dict' :param opt: :return: """ fname = str(opt.word_dict_size) + '_' + opt.name + '.vocab.dict' logging.info('Word dict fname %s' % (fname)) wor...
475162
def raw_to_libsvm(ofile, store, full_first_header=False): """Write a raw store to libsvm format :param ofile: file like object to write to :param store: the raw store :param full_first_header: Write the full first line regardless of sparseness """ for idx,data in enumerate(store): ...
475245
import markdown MARKDOWN_EXTENSIONS = ["def_list", "fenced_code", "codehilite", "tables"] def extended_markdown(text): if isinstance(text, str): text = text.decode("utf8") return markdown.markdown(text, extensions=MARKDOWN_EXTENSIONS, output_format="html") Config.transformers['markdown']...
475272
import os import sys import discord from dotenv import load_dotenv env_files = [f for f in os.listdir() if f.endswith(".env")] if env_files: load_dotenv(env_files[0]) # Path to the terminal GST_PATH = os.path.join("~", "Documents", "GamestonkTerminal") sys.path.append(GST_PATH) # https://discord.com/developers/...
475283
import pymzml import numpy as np import pandas as pd from tqdm import tqdm class ResultTable: def __init__(self, files, features): n_features = len(features) n_files = len(files) self.files = {k: v for v, k in enumerate(files)} self.intensities = np.zeros((n_files, n_features)) ...
475305
from __future__ import annotations import os from typing import BinaryIO from aiosnow.utils import convert_size class FileHandler: def __init__(self, file_name: str, dir_path: str = "."): self.file_path = os.path.join(dir_path, file_name) self.file = self._open() self.open = True de...
475357
from __future__ import print_function import torch.nn as nn class Flatten(nn.Module): def __init__(self): super(Flatten, self).__init__() def forward(self, feat): return feat.view(feat.size(0), -1) class LinearClassifierAlexNet(nn.Module): def __init__(self, layer=5, n_label=1000, pool...
475373
import random import torch from torch.autograd import Variable from torch.utils.data.dataloader import DataLoader from config import batch_size from data_gen import AiChallengerDataset from data_gen import pad_collate if __name__ == '__main__': checkpoint = 'BEST_checkpoint.tar' checkpoint = torch.load(check...
475393
import scipy.stats as stats import numpy as np from cde.density_simulation.BaseConditionalDensitySimulation import BaseConditionalDensitySimulation class SkewNormal(BaseConditionalDensitySimulation): """ This model represents a univariate skewed normal distribution. """ def __init__(self, random_seed=None): ...
475423
def binary_search(arr, tn): low = 0 high = len(arr) - 1 while low <= high: m = int((high - low) / 2) + low if arr[m] == tn: return m else: if arr[m] < tn: low = m + 1 else: high = m - 1 if low > high: r...
475467
import FWCore.ParameterSet.Config as cms # This modifier is used to adapt input configurations of tau producers if input files with old tau ID format are used. tau_readOldDiscriminatorFormat = cms.Modifier()
475479
import os import string import tensorflow as tf from aster.core import label_map from aster.protos import label_map_pb2 def build(config): if not isinstance(config, label_map_pb2.LabelMap): raise ValueError('config not of type label_map_pb2.LabelMap') character_set = _build_character_set(config.character_s...
475480
from .imports import * class SwitchDelegate(QItemDelegate): def __init__(self, parent): QItemDelegate.__init__(self, parent) def createEditor(self, parent, option, index): switch = QPushButton(parent) switch.setCheckable(False) switch.setAutoExclusive(False) icon = swi...
475577
from cliff.command import Command import call_server as server class AppList(Command): def get_parser(self, prog_name): parser = super(AppList, self).get_parser(prog_name) return parser def take_action(self, parsed_args): response = server.TakeAction().get_app_list() pr...
475587
import numpy as np import pickle, torch from . import tools class Feeder_single(torch.utils.data.Dataset): """ Feeder for single inputs """ def __init__(self, data_path, label_path, shear_amplitude=0.5, temperal_padding_ratio=6, mmap=True): self.data_path = data_path self.label_path = label_p...
475588
from keras.layers import Input, Activation, Dense,Flatten, BatchNormalization, Add, Conv2D from keras.layers import MaxPooling2D,AveragePooling2D,Permute,Reshape,LSTM,Lambda,GRU,Bidirectional,BatchNormalization,Concatenate from keras import regularizers from keras.optimizers import Adam from models.attention_layer impo...
475610
from argparse import ArgumentParser import logging from torch import nn from torch.optim import SGD from torch.utils.data import DataLoader import torch.nn.functional as F from torchvision.transforms import Compose, ToTensor, Normalize from torchvision.datasets import MNIST from ignite.engine import ( Events, cre...
475616
import setuptools def get_long_description(): with open('README.md', 'r') as f: long_description = f.read() return long_description version = '0.0.1' description = 'FSA/FST algorithms, intended to (eventually) be interoperable with PyTorch and similar' setuptools.setup( python_requires='>=3...
475699
from django.apps import AppConfig class SecateurConfig(AppConfig): name = "secateur" def ready(self) -> None: import secateur.signals return super().ready()
475704
import numpy as np # Example taken from : http://cs231n.github.io/python-numpy-tutorial/#numpy x = np.array([[1,2],[3,4]]) print (np.sum(x)) # Compute sum of all elements; prints "10" print (np.sum(x, axis=0)) # Compute sum of each column; prints "[4 6]" print (np.sum(x, axis=1)) # Compute sum of each row; prints...
475735
import atexit def exit_with_exception(message): raise RuntimeError(message) atexit.register(exit_with_exception, 'Registered first') atexit.register(exit_with_exception, 'Registered second')
475779
from visual_mpc.envs.base_env import BaseEnv from .robosuite_wrappers.SawyerIKEnv import make_sawyer_env import numpy as np from robosuite.utils.transform_utils import mat2quat, rotation_matrix low_bound = np.array([0.35, -0.2, 0.83, 0, -1]) high_bound = np.array([0.75, 0.2, 0.95, np.pi, 1]) start_rot = np.arra...
475793
import PyLidar3 import time # Time module #Serial port to which lidar connected, Get it from device manager windows #In linux type in terminal -- ls /dev/tty* port = input("Enter port name which lidar is connected:") #windows #port = "/dev/ttyUSB0" #linux Obj = PyLidar3.YdLidarX4(port) #PyLidar3.your_version_of_lidar(...