content
stringlengths
5
1.05M
import logging from django.conf import settings from django.utils.datastructures import MultiValueDictKeyError from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.http import HttpResponse from...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import unicode_literals from collections import defaultdict from mock import Mock class DictMock(Mock): """Like Mock, except also "virally" returns DictMocks upon __getitem__ """ __dict_contents = defaultdict(lambda: Dict...
import pybreaker from ..formation import _CONTEXT, _RES_HTTP class BreakerTriggerException(Exception): pass def breaker_logger(logger): class LogListener(pybreaker.CircuitBreakerListener): "Listener used to log circuit breaker events." def state_change(self, cb, old_state, new_state): ...
import logging import os import random import string import time from datetime import datetime, timezone from enum import Enum, unique from typing import Optional, List import requests logger = logging.getLogger(__name__) BROKER_URL = os.getenv('BDCAT_SB_BROKER_URL', 'https://qa-broker.sbgenomics.com') BROKER_TOKEN ...
# coding: utf-8 from vnpy.trader.vtConstant import * from vnpy.trader.app.ctaStrategy.ctaTemplate import (CtaTemplate, BarGenerator, ArrayManager) from collections import defaultdict import numpy as np import talib...
import pygame from game.control_object import ButtonObject, MenuObject from game.interfaces import ILocation from game.image_collection import ControlImageCollection big_star = ControlImageCollection("../game_assets/star1.png", 50, 50).download_image() small_star = ControlImageCollection("../game_assets/star1.png", 3...
FW = "../examples/mac/devboard/Device.hex" #ex.otap(node.keys(), FW, 0) for k in range(500): for n in nodes: print "----- Node " + hex(n.id) + " ----------------" print (n.sys.led(2)) print(n.sys.ar()) u = n.sys.util() if u != None: print(str(u.mem)) prin...
#!/usr/bin/env python3 import os import json import uuid from dsrlib.meta import Meta from .actions import Axis, ActionVisitor, InvertPadAxisAction, SwapAxisAction, \ GyroAction, CustomAction, DisableButtonAction from .buttons import Buttons from .configuration import Configuration class BaseJSONWriter(Action...
import numpy as np import torch import yaml import os from utils.tracking_utils import * from utils.kalman_filter import KalmanBoxTracker from scipy.optimize import linear_sum_assignment import sys import argparse import time def associate_instances(previous_instances, current_instances, overlaps, pose, association_w...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ dummy_l = ListNode('i') ...
""" image sampler code is clone from https://raw.githubusercontent.com/acil-bwh/ChestImagingPlatform/develop/cip_python/dcnn/data/data_processing.py """ import math import vtk import numpy as np import SimpleITK as sitk from PIL import Image from scipy.ndimage.filters import gaussian_filter from scipy.ndimage.interpola...
from django.http import HttpResponse from django.utils import simplejson from google.appengine.api import urlfetch import urllib import string def vat(request, country_code, vat_no): country_code = string.upper(country_code) data=dict(ms=country_code, iso=country_code, vat=vat_no) payload = urllib.urlencode(...
import pandas as pd import requests from io import StringIO from annotations.cache_utils import cache_data_table URL = "https://www.genenames.org/cgi-bin/download/custom?col=gd_hgnc_id&col=gd_app_sym&col=gd_app_name&col=gd_status&col=gd_prev_sym&col=gd_aliases&col=gd_pub_chrom_map&col=gd_pub_acc_ids&col=gd_pub_refseq...
# imported libraries import random # method: board which holds values of each position, not what is displayed in game # input: x,y range and num bombs # output: built board with bombs in place # effects: none def build_board(x, y, num): board = [] for i in range(y): row = [] for j in range(x):...
import chainer import matplotlib.pyplot as plt import numpy as np from brancher.variables import RootVariable, RandomVariable, ProbabilisticModel from brancher.standard_variables import NormalVariable, LogNormalVariable, BetaVariable from brancher import inference import brancher.functions as BF # Probabilistic model...
# Keyboard rand_keyboard = open('random3.txt','w') keyboard = 'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm' text_length = 10000 line_length = 15 index = 0 output = '' for i in range(text_length): for j in range(line_length): index %= len(keyboard) output += keyboard[index] index += 1 output += '\n' ...
from flask import jsonify from schema import Schema from pysite.base_route import APIView from pysite.constants import ValidationTypes from pysite.decorators import api_params LIST_SCHEMA = Schema([{"test": str}]) DICT_SCHEMA = Schema({"segfault": str}) class TestParamsView(APIView): path = "/testparams" na...
import argparse from generate import generate_min_blep from render import render_output def main(): parser = argparse.ArgumentParser() parser.add_argument('sample_rate', type=int, help="This is actualy labeled 'oversampling' in the " "ExperimentalScene code, and I'm ...
# project/tests/test_auth.py import json, time from project import db from project.api.models import User from project.tests.base import BaseTestCase from project.tests.utils import add_user class TestAuthBlueprint(BaseTestCase): """Tests for the Auth service.""" def test_user_registration(self): ...
"""Contains entrypoint logic for running moduledependency as a program.""" import sys import os from .cli import ArgumentProcessor from .executor import Executor from .outputter import OutputterFactory from . import MODULEDEPENDENCY_DIR # Directory which stores all the outputters OUTPUTTER_DIRECTORY = os....
# from app.models import Pitch,User # from app import db # def setUp(self): # self.user_James = User(username = 'James',password = 'potato', email = '[email protected]') # self.new_review = Review(movie_id=12345,movie_title='Review for movies',image_path="https://image.tmdb.org/t/p/w500/jdjdjdjn",movie_revi...
import random def choose(): words=["umbrella","electricity","library","explanation","demonitisation","rainbow","flipkart","computer","elctronics","chemical"] pick=random.choice(words) return pick def jumble(word): jumbled="".join(random.sample(word,len(word))) return jumbled def pl...
from pathlib import Path _root = Path(__file__).resolve().parent _constraints = _root.parent / 'constraints' _content = _root / 'content' (_content / 'boards').mkdir(exist_ok=True) for item in (_constraints / 'board').glob('**/*.yml'): if item.name != 'info.yml': _name = item.stem _prefix = '.to...
from setuptools import setup setup(name='HDMSpectra', version='1.0', description='Dark Matter Spectra from the Electroweak to the Planck Scale', author='Nicholas L Rodd', author_email='[email protected]', url='https://github.com/nickrodd/HDMSpectra', license='MIT', packages=['HDMSpectra'], i...
import struct #Get the variable length time that is represented as some fraction of a beat for beat tick format #Assumptions: file buf starts at the beginning of the vlr def get_vlv(file_buf, index): end_index = index vlv = 0 vlv_accumulator = 0 evaluation = 128 count = 0 while(evaluation >= 12...
FEATURE_SELECT_PARAMNAME_PREFIX = "feature_group" ALWAYS_USED_FEATURE_GROUP_ID = -1 RANDOM_SCORE = 10
"""This module contains operations related to committing and reviewing changes done to requirements.""" from logging import Logger from pipwatch_worker.core.data_models import Project from pipwatch_worker.worker.commands import Git from pipwatch_worker.worker.operations.operation import Operation class CommitChanges...
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import unittest import requests from mock import Mock, patch from pants.cache.resolver ...
from base.BaseAlgorithm import BaseAlgorithm import math class InsertionLengthAlgorithm(BaseAlgorithm): def __init__(self, name, path): BaseAlgorithm.__init__(self, name, path) def run(self): self.lengthOfCoverage() genome_insertion = [] sum = 0; sumI = 0; wit...
# class Actions: # def polish_single_phrase(phrase: Union[Phrase, str] = None): # actions.mode.enable("user.polish_dictation") # actions.mode.disable("command") # if phrase: # samples = extract_samples() # speech_system._on_audio_frame(samples) # actions.mode...
from __future__ import division def html_head_title(title): return '''\ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> <title>%s</title> </head> ''' % title
import vaex.utils import numpy as np import pytest def test_required_dtype_for_max(): assert vaex.utils.required_dtype_for_max(127, signed=True) == np.int8 assert vaex.utils.required_dtype_for_max(128, signed=True) == np.int16 assert vaex.utils.required_dtype_for_max(127, signed=False) == np.uint8 ass...
"""Treadmill schedule monitor event. This module allows the treadmill cron to take actions on applications, for example, start and stop them at a given time. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import...
import pytest from energym.simulators.eplus_old import EnergyPlus from energym.envs.eplus_env import EplusEnv import energym.utils.rewards as R from energym.utils.wrappers import NormalizeObservation, MultiObsWrapper from opyplus import Epm, WeatherData import os import pkg_resources from glob import glob #to find dir...
""" This example file is intended to demonstrate how to use SHTK to mount a Debian or Ubuntu image and install vim inside it via chroot. All mount points are automatically unmounted after success or failure of installation. Args: image_path (str): Path of the image to mount mount_path (str): Path of the dir...
# -*- coding: utf-8 -*- """ @author: vinay """ import numpy as np import math import matplotlib.pyplot as plt x1 = np.linspace(0, 5/50, num=1000) np.random.seed(0) noisy_sine = np.sin(2*math.pi*50*x1) + np.random.normal(0,0.06,1000) plt.subplot(3,1,1) plt.plot(x1, noisy_sine, color = "cyan") plt.xlim(0, 5...
import re import numpy as np import pickle from collections import defaultdict from chainer.dataset.dataset_mixin import DatasetMixin class LtrDataset(DatasetMixin): """ Implementation of Learning to Rank data set Supports efficient slicing on query-level data. Note that single samples are collectio...
from .datasets.captioning import CaptioningDataset from .datasets.masked_lm import MaskedLmDataset from .datasets.multilabel import MultiLabelClassificationDataset from .datasets.downstream import ( ImageNetDataset, INaturalist2018Dataset, VOC07ClassificationDataset, ImageDirectoryDataset, ) __all__ = ...
from bs4 import BeautifulSoup import requests url = "http://awoiaf.westeros.org/index.php/Main_Page" r = requests.get(url) soup = BeautifulSoup(r.text) word_bank = set() for link in soup.find_all('a'): print(link) word_bank.add(link.get('title')) print(word_bank)
# -*- coding: utf-8 -*- import csv import os csv_file = "test.csv" with open(csv_file, "wt", newline="") as f: # 参数newline设置一行文本的结束字符 w = csv.writer(f, dialect="excel", delimiter="#") # 以excel方式打开,分隔符为“#” w.writerow(("index", "char", "num")) # 插入一行数据 for i in range(3): w.writerow((i +...
import datetime import logging import orm logging.basicConfig(level=logging.INFO) class BotMixin(object): pass def new_timezone(): uu = datetime.datetime.now() return uu class RequestCache(object): __tablename__ = "sheet_request_cache" id = orm.Integer(primary_key=True) request_id = orm....
import io import os import struct from datetime import datetime from enum import Enum import numpy as np import pandas as pd import soundfile as sf from PIL import Image from dataclasses import dataclass from .classifiers.classifier import Classifier class DataType(Enum): EMOTIONS = 1 EMOTIONS_FROM_RAW_DATA...
"""Unit test package for grblc."""
''' Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. Note: You may only use...
# # Basic PoW Auth class # import werkzeug.security from {{appname}}.models.tinydb import pow_user as Model class PowAuth(object): def check_auth( login, pwd ): """ checks the login, password hash combination against the pow_user model """ m = Model() t...
import numpy as np from pax import plugin from pax.dsputils import adc_to_pe class DesaturatePulses(plugin.TransformPlugin): """Estimates the waveform shape in channels that go beyond the digitizer's dynamic range, using the other channels' waveform shape as a template. pulse.w will be changed from int16 ...
from dataclasses import dataclass, field from enum import Enum from re import compile from string import Formatter from typing import AnyStr, ClassVar, List from lark import Token class IssueType(str, Enum): WARNING = 'Warning' ERROR = 'Error' @dataclass(order=True) class Issue: MD_REGEX: ClassVar = co...
import os from setuptools import find_packages from setuptools import setup info = {} version = os.path.join("arlunio", "_version.py") with open(version) as f: exec(f.read(), info) def readme(): with open("README.md") as f: return f.read() required = ["attrs", "appdirs", "ipython", "numpy", "Pill...
# -*- coding: utf-8 -*- # Copyright 2014, 2015 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
''' Created on Jul 26, 2013 @author: Yubin Bai ''' import sys INF = 1 << 31 def solve(par): N, M, Q, mat, query = par result = [] for q in query: c = mat[q[0]][q[1]] size = 1 finished = False while not finished: sStr = c * size if q[0] - size // 2 >=...
# -*- coding: utf-8 -*-l # Copyright (c) 2017 Vantiv eCommerce # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy,...
import requests,json,sys,re,os from datetime import datetime from VideoIDHelper import * #if you intend to extend this module #simply call #saveYouTubeAnnotations.retrieveAnnotation # #arg is either an ID, link or shortened link #and location is the location the XML file is to be saved in def retrieveShows(arg,locati...
""" Kivy Widget that accepts data and displays qrcode. """ import os from functools import partial from threading import Thread import qrcode from kivy.clock import Clock from kivy.graphics.texture import Texture from kivy.lang import Builder from kivy.properties import (BooleanProperty, ListProperty, NumericProperty,...
# Copyright 2018 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, sof...
from django.conf.urls import url from rest_framework.routers import DefaultRouter, SimpleRouter from booktest import views urlpatterns = [ ] # 路由Router: 动态生成视图集中处理函数的url配置项 # router = SimpleRouter() router = DefaultRouter() # 路由Router router.register('books', views.BookInfoViewSet, base_name='books') # 向路...
import networkx as nx import math import operator from datetime import datetime import os import queue import copy import threading import crestdsl.model as model import crestdsl.model.api as api from crestdsl.simulation.simulator import Simulator import crestdsl.simulation.dependencyOrder as DO from crestdsl.cachin...
import json import random import requests import dydx.util as utils import dydx.constants as consts import dydx.solo_orders as solo_orders import dydx.perp_orders as perp_orders from decimal import Decimal from dydx.eth import Eth from .exceptions import DydxAPIError class Client(object): BASE_API_URI = 'https://...
import sys sys.stdout.write('Hello\nWorld\n')
# For live classification from approaches.approach import Multiclass_Logistic_Regression, Perceptron, Sklearn_SVM import comp_vis.calibration_tools as ct import comp_vis.data_tools as dt import comp_vis.img_tools as it import comp_vis.live_tools as lt import numpy as np import os import random import sys import time ...
import os import yaml import logging from multiprocessing import Queue from flask import Flask, jsonify, request from .worker import Worker logger = logging.getLogger('triggerflow-worker') app = Flask(__name__) event_queue = None workspace = None worker = None @app.route('/', methods=['POST']) def run(): """ ...
""" This module provides the AIPSTask class. It adapts the Task class from the Task module to be able to run classic AIPS tasks: >>> imean = AIPSTask('imean') The resulting class instance has all associated adverbs as attributes: >>> print imean.ind 0.0 >>> imean.ind = 1 >>> print imean.indisk 1.0 >>> imean.indi =...
""" Main fallback class. """ import types import numpy as np import cupy as cp from cupyx.fallback_mode import utils class _RecursiveAttr: """ RecursiveAttr class to catch all attributes corresponding to numpy, when user calls fallback_mode. numpy is an instance of this class. """ def __init_...
# Faça um programa que leia algo do teclado, # e diga todas as informações possíveis sobre # ela. valor = input('Digite algo: ') print('\tO tipo disso é: {}'.format(type(valor))) print('\tÉ alfabético? {}'.format(valor.isalpha())) print('\tÉ alfanumérico? {}'.format(valor.isalnum())) print('\tÉ decimal? {}'.format(va...
import numpy as np import Algorithm_new as AL import scipy.sparse as sparse def Example(): beta = np.random.normal(1, 0.1, 30) freq_1_r = np.random.poisson(0.1, [1000, 100]) freq_2_r = np.random.poisson(0.1, [1000, 100]) freq_1_e = np.random.poisson(0.1, [1000, 100]) freq_2_e = np.random.poi...
# Author: Levente Fodor # Date: 2019.04.20 # Language: Python 3 ''' u: number of children in node_1 v: number of children in node_2 w: weight between two nodes myEdge = Edge(0,1,10) ''' class Edge: def __init__(self,u,v,w): self.verticles = [int(u),int(v),int(w)] def __getitem__(sel...
"""Cred artifacts to attach to RFC 453 messages.""" from typing import Mapping from marshmallow import EXCLUDE, fields from .......messaging.models.base import BaseModel, BaseModelSchema from .......messaging.valid import ( INDY_CRED_DEF_ID, INDY_REV_REG_ID, INDY_SCHEMA_ID, NUM_STR_WHOLE, ) class I...
FAKE_DATA = [{"close_0": 296.0, "time": 1577743200000, "myVar1": 269.5, "open_0": 123.0}, {"close_0": 155.0, "time": 1577829600000, "myVar1": 129.25, "open_0": 121.5}, {"close_0": 182.5, "time": 1577916000000, "myVar1": 129.0, "open_0": 121.5}, {"close_0": 162.5, "time": 157800240...
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
"""This module handles the encryption of decryption of data.""" import re class Crypter: """This class generates the encryption key, calls the correct function, and returns the text. Arguments: - password: hashed (scrambled) version of the password, used to generate the encryption key - text:...
import logging import os import subprocess _ffmpeg_valid_path = None _ffprobe_valid_path = None def get_ffmpeg_path(ffmpeg_path=None): """ Series of check up to lookup for a valid ffmpeg path. Cache the result to avoid those check each time. """ global _ffmpeg_valid_path if _ffmpeg_valid_pat...
__author__ = "[email protected]" from bs4 import BeautifulSoup import requests import json import datetime import time import settings import traceback import MySQLdb class Database: def __init__(self): self.host = settings.host self.user_name = settings.user_name self.password = settings...
import os import io import yaml import shutil import tarfile import warnings import argparse import numpy as np import pandas as pd from enum import Enum from pathlib import Path from functools import partial from typing import Union, List, Callable # CONSTANTS ARCHIVES_FMT = ['.zip', '.tar', '.gz'] # Global utils d...
from .augmentation import * from .compose import Compose from .discard import FaceDiscarder from .interpolate import ConditionalInterpolate, Interpolate from .pad import Padding from .rotate import Rotate __all__ = [ "Compose", "FaceDiscarder", "ConditionalInterpolate", "Interpolate", "Padding", ...
import numpy as np import matplotlib.pyplot as plt from signals import Signal, G_xx # custom module def spectrogram(signal, binWidth, overlap): """ Generates the spectrogram of an input signal. @param signal The input signal object @return specs The values of the spectrogram @return f The frequ...
# -*- coding: utf-8 -*- # # Testing for access control list authorization. # # ------------------------------------------------ # imports # ------- from sqlalchemy import and_ from flask import g from .fixtures import authorize, Article, ArticleFactory # helpers # ------- def query(name, check): return Article....
from .json_queue import *
from sqlalchemy.orm import backref from .import db, login_manager from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin from datetime import datetime @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(db.Model, U...
# Generated by Django 2.0.2 on 2018-03-10 14:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tracks', '0002_auto_20180310_1724'), ] operations = [ migrations.AlterField( model_name='tracks', name='track_name',...
from manimlib.imports import * class CompareACDC(Scene): def construct(self): self.show_titles() self.show_dc_examples() self.show_ac_examples() self.wait(2) def show_titles(self): # SS6.1 self.DC_title = TextMobject("\\underline{DC}")\ .scale(2.5)\...
from selenium.webdriver.chrome.options import Options def pytest_setup_options(): """called before webdriver is initialized""" options = Options() options.add_argument("--headless") options.add_argument("--disable-gpu") return options
# Copyright 2021 MosaicML. All Rights Reserved. import numpy as np import pytest import torch from composer.algorithms import ChannelsLastHparams from composer.core.event import Event from composer.core.state import State from composer.core.types import DataLoader, Model, Precision, Tensor def _has_singleton_dimens...
from setuptools import setup from Cython.Build import cythonize print("Compilando encoder.pyx\n\n") setup(ext_modules = cythonize("encoder.pyx"),) print("\n\nCompilando conversor.pyx\n\n") setup(ext_modules = cythonize("conversor.pyx"),)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from icecream import install from icecream import ic install() ic.configureOutput(includeContext=True) from B import foo if __name__ == "__main__": ic("Hello World") foo()
import sys import typing import numpy as np from scipy import signal class ModConvolve(): def __call__( self, f: np.ndarray, g: np.ndarray, ) -> np.ndarray: mod = self.__mod N: typing.Final[int] = 10 BASE: typing.Final[int] = 1 << N f, f0 = np.divmod(f, BASE) f2, ...
"""Unit test package for class_enrollment_simulations."""
""" File: sierpinski.py Name: --------------------------- This file recursively prints the Sierpinski triangle on GWindow. The Sierpinski triangle is a fractal described in 1915 by Waclaw Sierpinski. It is a self similar structure that occurs at different levels of iterations. """ from campy.graphics.gwindow import G...
## Sid Meier's Civilization 4 ## Copyright Firaxis Games 2005 from CvPythonExtensions import * import CvUtil import Popup as PyPopup import PyHelpers PyPlayer = PyHelpers.PyPlayer PyCity = PyHelpers.PyCity gc = CyGlobalContext() local = CyTranslator() def isWBPopup(context): "helper for determining if...
import logging from src.backup.backup_process import BackupProcess from src.backup.scheduler.task_creator import TaskCreator from src.commons.big_query.big_query import BigQuery from src.commons.big_query.big_query_table_metadata import BigQueryTableMetadata from src.commons.tasks import Tasks class TableBackup(obje...
# -*- coding: utf-8 -*- """ Created on Mon Sep 20 09:33:41 2021 @author: Erlend Tøssebro """ import matplotlib.pyplot as plt import random karakterer = ["A", "B", "C", "D", "E", "F"] antall = [5, 15, 40, 24, 18, 26] # Subplot, parametere: antall rader, antall kolonner, hvilken er dette # For den tre...
# pylint: disable=missing-docstring, redefined-outer-name import os from typing import Generator, List import pytest from fideslang.models import System, SystemMetadata from py._path.local import LocalPath from fidesctl.connectors.models import OktaConfig from fidesctl.core import api from fidesctl.core import system...
import logging from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.utils import timezone from django.utils.translation import ugettext as _ from rr.forms.redirecturi import RedirectUriForm from rr.models.redirecturi import Redir...
# encoding: UTF-8 # # Copyright 2012-2013 Alejandro Autalán # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but #...
""" @Date: 2021/08/12 @description: """ import torch import torch.nn as nn class LEDLoss(nn.Module): def __init__(self): super().__init__() self.loss = nn.L1Loss() def forward(self, gt, dt): camera_height = 1.6 gt_depth = gt['depth'] * camera_height dt_ceil_depth = d...
#!/usr/bin/env python3 from setuptools import find_packages, setup import os os.chdir(os.path.dirname(os.path.realpath(__file__))) try: with open("readme.md") as f: md = f.read() except: md = "" setup( name="k1lib", packages=["k1lib", "k1lib._hidden", "k1lib.cli", ...
def sum2d(arr): M, N = arr.shape result = 0.0 for i in range(M): for j in range(N): result += arr[i, j] return result
import unittest import moksha.wsgi.middleware import webtest from nose.tools import raises from nose.tools import eq_ class TestMiddleware(unittest.TestCase): def setUp(self): def app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Hel...
import time def Chorus_origin(): for i in range(2): img1() time.sleep(0.5) img2() time.sleep(0.5) img3() time.sleep(1) img3() time.sleep(1) Chorus_origin img1() time.sleep(4) img2() time.sleep(4) img3() time.sleep(10) img4() time.sleep(4) img5() tim...
"""ヴィジュネル暗号を作る関数が入っています。""" def make_vij(key:str,sent:str)->str: """ 第一引数に鍵、第二引数に平文を受け取りヴィジュネル暗号を返します。 """ x,y=0,0 ang="" key=key.lower() sent=sent.lower() while y<len(sent): if ord(sent[y])>=ord('a') and ord(sent[y])<=ord('z'): ang+=chr(ord('A')+(ord(sent[...
# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import Snapshot snapshots = Snapshot() snapshots['TaxPercentagesGraphQLTestCase::test_getting_tax_percentages 1'] = { 'data': { 'taxPercentages': { 'edges': [ ...
# pytype: skip-file import logging from logging import Logger from typing import Callable, Dict, Any, Optional from slack_bolt.context import BoltContext from slack_bolt.context.ack import Ack from slack_bolt.context.respond import Respond from slack_bolt.context.say import Say from slack_bolt.request import BoltReque...