content
stringlengths
5
1.05M
from unittest import TestCase """These are not real unit tests, as they rely on the database to be correct, and the DbCursor class to be correct as well """ class TestNode(TestCase): def setUp(self): from arkdbtools.dbtools import set_connection set_connection( host='localhost', ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # SPDX-License-Identifier: Apache-2.0 # Copyright 2021 RT Corporation # # 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...
from __future__ import absolute_import, print_function from sentry.rules.base import RuleBase class EventAction(RuleBase): rule_type = "action/event" def after(self, event, state): """ Executed after a Rule matches. Should yield CallBackFuture instances which will then be passed int...
# -*- coding: utf-8 -*- """ Created on Sat Oct 12 13:39:17 2019 @author: abraverm """ import numpy as np import os import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint from src.enet_wc_keras_model import autoencoder_wc, transfer_weights from src...
# -*- coding: utf-8 -*- # from __future__ import division from mpmath import mp import numpy import sympy from .helpers import cartesian_to_spherical_sympy from ..helpers import untangle, pm_array0, fsd, pm_array, pm class McLaren(object): """ A.D. McLaren, Optimal Numerical Integration on a Sphere, ...
import os import threading import queue from utils.grid_tools_2d import Point, Vector from utils.intcode_computer import IntCodeComputer, get_program def get_input(filepath): # Load the comma separated intcode program from a file into memory (a list). with open(filepath) as f: data = [line.strip() fo...
from core.advbase import * class Pecorine(Adv): def prerun(self): self.gourmand_gauge = 0 self.gourmand_mode = ModeManager(group="gourmand", fs=True, s1=True, duration=20, pause=("s", "dragon")) def a1_update(self, gauge): if not self.gourmand_mode.get(): self.gourmand_gau...
# coding:utf-8 from django.shortcuts import render, render_to_response, HttpResponse from api.function import * from api.models import * defaultCount = 40 # Create your views here. # API文档 def doc(request): return render_to_response("doc/doc.html", {}) # 登录处理 POST方式, 参数 uid, pwd, pwd须进行MD5加密 def login(request):...
""" Obtain the statistics of Du et al. dataset """ import json from pathlib import Path from transformers import BertTokenizerFast from pprint import pprint as print from utils.logging import logging from tqdm import tqdm class Configs: txt_data_dir = "../txt_data/preprocessed/" txt_data_file_fmt = "para_73k_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- '__slots__绑定限制的练习' __author__ = 'Jacklee' # 导入模块 #import types # 绑定限制 class Student(object): __slots__ = ('name', 'age') s = Student() #s.score = 99 Student.score = 99 class A(object): __slots__ = () pass class B(A): #__slots__ = ('x', 'y') pass class C(B): _...
from arm.logicnode.arm_nodes import * class OnContactNode(ArmLogicTreeNode): """Activates the output when the rigid body make contact with another rigid body. @option Begin: the output is activated on the first frame when the two objects have contact @option End: the output is activated on the...
""" File watch commercial remover """ import os import subprocess import logging import shutil import sys import time from threading import Thread from queue import Queue WORK_ROOT = "/config/" _LOGGER = logging.getLogger(__name__) logging.basicConfig(filename=WORK_ROOT+'watcher.log', filemode='a', level=logging.DEBU...
import taichi as ti def archs_support_bitmasked(func): return ti.archs_excluding(ti.opengl, ti.cc)(func) @archs_support_bitmasked def test_basic(): x = ti.field(ti.i32) c = ti.field(ti.i32) s = ti.field(ti.i32) bm = ti.root.bitmasked(ti.ij, (3, 6)).bitmasked(ti.i, 5) bm.place(x) ti.root...
"""skmf.views by Brendan Sweeney, CSS 593, 2015. Define the views that are rendered by Flask to the end user. This controls what action to take given a URL path provided by the user. Typically, a path will result in the display of a Web page which is rendered from a template. Multiple paths may lead to the same action...
from os import name import pytest import random from automates.program_analysis.CAST2GrFN.model.cast import ( AstNode, Assignment, Attribute, BinaryOp, BinaryOperator, Call, ClassDef, Dict, Expr, FunctionDef, List, Loop, ModelBreak, ModelContinue, ModelIf, ...
from .version import __version__ # noqa try: str = unicode # python 2.7 except NameError: str = str
#!/usr/bin/python # -*- coding: utf-8 -*- # ######################################## ## # @author: Amyth # @email: mail@amythsingh.com # @website: www.techstricks.com # @created_date: 22-02-2017 # @last_modify: Wed Feb 22 12:44:32 2017 ## ########################################
from fractions import gcd from sys import stdin def p(n): s = int(n ** .5) c = sum(n/i for i in xrange(1, s+1)) * 2 - s**2 g = gcd(c, n ** 2) return '{}/{}'.format(c / g, n**2 / g) print( '\n'.join( p(int(ln)) for i, ln in enumerate(stdin) if i ) )
#!/usr/bin/env python # Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All c...
#!/usr/bin/env python3 import rospy import time def call_service(service_name: str, service_class, service_req = None, time_out: float = 5, max_retry: int = 5): """ Create a service proxy for given service_name and service_class and call the service :param str service_name: name of the service ...
#!/usr/bin/python3 #coding:utf-8 import rospy import cv2 import os from predict_image import detectImage import json from vision.srv import * class VisionNode: def __init__(self): rospy.init_node('vision_node', anonymous = True) #创建节点 self.rate = rospy.Rate(20) self.c...
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved. # # 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 ...
import datetime import docker import docker.errors import docker.models.containers import docker.models.images import enum import pathlib as pt import secrets import tarfile import tempfile import typing import app.database as db_module import app.database.user as user_module import app.database.dodoco.project as ddc_...
import discord from discord.app.commands import slash_command from discord.ext import commands from extra import utils from typing import Union, List from extra.language.centish import Centish from PIL import ImageDraw, ImageFont, Image import aiohttp import os guild_ids: List[int] = [int(os.getenv('SERVER_ID'))] dnk...
import bcrypt from django.contrib import messages from django.db.models import Count, Q from django.shortcuts import redirect, render from django.views.decorators.http import require_GET, require_POST from .models import User, UserRole, Loan from django.http import HttpResponse def get_logged_user(request): """ ...
import json import sys def main(): # Pull in data. datafile = sys.argv[1] with open(datafile) as f: data = json.loads(f.read()) # Pull node list together. nodes = [] for key, node in data["nodes"].items(): node["_key"] = key nodes.append(node) # Pull edge list tog...
from django.shortcuts import render from django.http import HttpRequest, HttpResponse # Create your views here. def index(request: HttpRequest): return HttpResponse('This is DRF index')
import os import gzip import random import time name = ['james', 'stefan', 'steve', 'frank', 'paul', 'jamey', 'stephan', 'paul'] for y in xrange(1000): destfile = "people-data_" + str(random.randint(1,10000)) + "-" + time.strftime("%s") fo = open(destfile, "a") for x in xrange(10000): fo.write("%s...
# -*- coding: utf-8 -*- """Punctuation. --- layout: post source: Garner's Modern American Usage source_url: http://bit.ly/1T4alrY title: dates date: 2014-06-10 12:31:19 categories: writing --- Dates. """ from proselint.tools import existence_check, memoize @memoize def check_et_al(text): """...
# ###################################################################################################################### # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # ...
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import os import sys _CHROME_SRC = os.path.join( os.path.abspath(os.path.dirname(__file__)), '..', '..', '..'...
#!/usr/bin/python #-*-coding:utf-8-*- from PyQt4.QtGui import * from PyQt4.Qt import * from PyQt4.QtCore import * from PyQt4 import QtCore, QtGui class SettingMenu(QMenu): def __init__(self,parent = None): super(SettingMenu,self).__init__() # self.setStyleSheet("background-image:url(\":/images/setting_bg.jpg...
import bilby import numpy as np class PTABilbyLikelihood(bilby.Likelihood): """ The class that wraps Enterprise likelihood in Bilby likelihood. Parameters ---------- pta: enterprise.signals.signal_base.PTA Enterprise PTA object that contains pulsar data and noise models parameters: list ...
import pytest from yfs.statistics import ( parse_valuation_table, parse_financial_highlights_table, parse_trading_information_table, ) from pytest_regressions import data_regression # noqa: F401 from .common_fixtures import statistics_page_data_fixture def test_parse_valuation_table(data_regression, stat...
import os cromwell_metadata_path = os.path.join( os.path.dirname(__file__), "cromwell_metadata.json" ) ANALYSIS_PROCESS_INPUT = { "input_uuid": "6f911b71-158e-4f50-b8e5-395f386a343b", "pipeline_type": "Optimus", "workspace_version": "2021-05-24T12:00:00.000000Z", "references": [ "gs://hca-...
""" This problem was asked by Facebook. Given a function that generates perfectly random numbers between 1 and k (inclusive), where k is an input, write a function that shuffles a deck of cards represented as an array using only swaps. It should run in O(N) time. Hint: Make sure each one of the 52! permutations of t...
import re import os import jk_logging import jk_utils import jk_prettyprintobj from .GitWrapper import GitWrapper from .GitCommitHistory import GitCommitHistory #from .GitConfigFile import GitConfigFile # not needed class GitServerRepository(jk_prettyprintobj.DumpMixin): #################################...
#!/usr/local/bin/python # Code Fights Is Power Problem def isPower(n): if n == 1: return True for exp in range(2, 9): for base in range(2, n): tmp = base ** exp if tmp == n: return True elif tmp > n: break return False d...
import unittest from card.components import BaseOracle class OracleTest(unittest.TestCase): def setUp(self): self.oracle = self.get_oracle() def get_oracle(self) -> BaseOracle: raise NotImplementedError() def e(self, abbrv: str, strings: list): for s in [abbrv] + strings: ...
""" Generate docs """ from jinja2 import Template import subprocess def generate(host, port, database): # read config template with open("bin/schemaspy-template.properties", "r") as inpfile: template = Template(inpfile.read()) rendered_config = template.render( host=host, port=po...
import os, pendulum class Config: QUERY = os.environ.get('QUERY', '*') CHECK_DURATION = int(os.environ.get('CHECK_DURATION', 1)) USERNAME = os.environ['USERNAME'] PASSWORD = os.environ['USERNAME'] CLIENT_ID = os.environ.get('CLIENT_ID') CLIENT_SECRET = os.environ.get('CLIENT_SECRET') TENA...
import os import sys import argparse import matplotlib.pyplot as plt from keras.models import load_model from keras import backend as K from termcolor import colored,cprint import numpy as np from utils import * import pandas as pd from keras.utils import np_utils from sklearn import preprocessing # Saliency map # h...
t = int(input()) for i in range(t): l = [] n = int(input()) for i in range(n): d = list(map(int, input().split())) l.append(d) p = [] for i in l: for j in i: p.append( (i[1]//(i[0]+1) )*i[2] ) print(max(p))
from unittest import TestCase from app import app from i18n.i18n import I18n class MockApp(object): def add_template_filter(self, fn): pass class IntegrationTestBase(TestCase): def setUp(self): I18n(app) app.testing = True self.app = app.test_client() def _assertStatusC...
""" Dada um array numérico "nums", retorne true se um dos 4 elementos iniciais for um "9". O "length" do array pode ser menor que 4. """ def array_front9(nums): return nums[:4].count(9) >= 1 # OUTRO JEITO MAIS EXPLICADO E PASSO A PASSO def array_front9_2(nums): # First figure the end for the loop end = ...
import csv; from random import shuffle; newNames = []; persons = []; newPlaces = []; oldPlaces = []; oldRelations = []; newRelations = [ 'Academic Work', 'Friendship', 'Politics', 'Colleges', 'Food' ] # Extract new names with open('scientists.csv', newline='') as csvfile: csvreader = csv.reader(csvfile, deli...
from .version import version as __version__ __all__ = [ "__version__", ]
from torch.distributions import Categorical from torch.autograd import Variable from models.dropout import ConcreteDropout, Standout import torch.nn as nn import torch.nn.functional as F from torchvision import datasets, transforms import torch scale = transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) tr...
# -*- coding: utf-8 -*- """ Created on Fri Oct 1 22:07:22 2021 @author: pcjean """ import PySimpleGUI as sg import sys class Vcard: def __init__(self,numer,prop,val, listprop): self.numero = numer self.ident = prop self.valeur = val self.listprop = listprop ...
"""This module contains tests for edgecases. """ import copy import pytest import sphinx.errors from sphinx.transforms.post_transforms import ReferencesResolver def test_not_json_compliant(autodocument): actual = autodocument( documenter='pydantic_model', object_path='target.edgecases.NotJsonCom...
import FWCore.ParameterSet.Config as cms # AlCaReco for track based alignment using ZMuMu events (including the tracks from the PV) OutALCARECOTkAlDiMuonAndVertex_noDrop = cms.PSet( SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('pathALCARECOTkAlDiMuonAndVertex') ), outputCommands = ...
from urllib.request import Request, urlopen import json # Ошибки class Error(Exception): pass class ApiError(Error): pass class GetOnlinePlayers(): def __init__(self, players, count, max): self.players = players self.count = count self.max = max def __repr__(self): return f"<GetOnlinePlayers m...
#from compas_fab.robots import Robot from compas.geometry import Frame, Point, Transformation, Vector from compas.geometry.transformations.translation import Translation from compas.robots import Axis, Joint, Link # from compas.datastructures import Mesh from compas_fab.robots import Configuration from integral_timb...
#!/usr/bin/python # -*- coding: UTF-8 -*- import xlwings as xw import sys, os def isPointinPolygon(point, rangelist): # 判断是否在外包矩形内,如果不在,直接返回false lnglist = [] latlist = [] for i in range(len(rangelist)-1): lnglist.append(rangelist[i][0]) latlist.append(rangelist[i][1]) # print(lngli...
#!/usr/bin/env python """ A ROS node to detect objects via TensorFlow Object Detection API. Author: Cagatay Odabasi -- cagatay.odabasi@ipa.fraunhofer.de """ # ROS import rospy import cv2 from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError from detector import Detector import utils...
""" Module containing serializers. These functions are provided as definitions of the basic interface that all serializers should implement. This abstraction is intended to allow easily switching from one form of serialization to another. """ import json from message import Message class BaseSeriali...
class Vector: """ Constructor self: a reference to the object we are creating vals: a list of integers which are the contents of our vector """ def __init__(self, vals): self.vals = ( vals # We're using the keyword self to create a field/property ) print("A...
import json import random import string import traceback from tests.cephfs.cephfs_utilsV1 import FsUtils from utility.log import Log log = Log(__name__) def run(ceph_cluster, **kw): """ Test Cases Covered: CEPH-83573867 - Create 4-5 Filesystem randomly on different MDS daemons Pre-requisites : ...
class TemplateError(Exception): """ General template error """ __msg = "" def __init__(self, what): super(TemplateError, self).__init__() self.__msg = what def __str__(self): return str(self.__msg)
""" @Time: 2020/9/22 10:41 @Author: Zhirui(Alex) Yang @E-mail: 1076830028@qq.com @Program: """ import os import logging from datetime import datetime from utils.config import LOG_LEVEL, DATA_DIR logger = logging.getLogger("TAROT LOG") level = logging.getLevelName(LOG_LEVEL) logger.setLevel(level) fmt = "TAROT LOG: %(...
# -*- coding: utf-8 -*- def note_generate(): return {'title': 'Notification', 'time': '11.30.2021', 'content': '你好,我是该系统的Developer。目前,网站已完成测试,' '基本实现了财务危机预测的功能,您可以通过Demo选择我们提供的公司数据。' '我们采用uWSGI+Nginx部署方案,' '撰写了项目开发文档,' ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('flisol_event', '0004_auto_20141229_2309'), ] operations = [ migrations.AddField( model_name='flisolattendance', ...
#! python2 #coding:utf8 from Core.Thread import * if __name__=='__main__': th = MainThread() th.start()
import pytest from flask_security.utils import hash_password from cafebabel import create_app from cafebabel.commands import auth_fixtures, drop_collections from cafebabel.articles.models import Article from cafebabel.articles.tags.models import Tag from cafebabel.articles.translations.models import Translation from ...
""" Init file for the SpatialCluster library. """ version_info = (0, 0, 46) __version__ = ".".join([str(x) for x in version_info]) __all__ = [ "methods" "preprocess" "visualization" "utils" ]
import unittest, re, logging import tbot.testbase from tbot.utils import link class Test(unittest.TestCase): def test_link(self): self.assertEqual(link.find_links('not a link'), []) self.assertEqual(link.find_links('3.1'), []) self.assertEqual(link.find_links('3.'), []) self.asser...
from datetime import date from onegov.ballot import Election from onegov.election_day.collections import ArchivedResultCollection from tests.onegov.election_day.common import login from tests.onegov.election_day.common import upload_majorz_election from tests.onegov.election_day.common import upload_proporz_election fr...
import asyncio import logging import pytest import kopf from kopf._cogs.structs.ephemera import Memo from kopf._core.actions.execution import PermanentError, TemporaryError from kopf._core.engines.indexing import OperatorIndexers from kopf._core.intents.causes import HANDLER_REASONS, Reason from kopf._core.reactor.in...
#!/usr/bin/env python import scipy.stats as stats import pandas as pd import numpy as np def contingency_chi2(categorical_1, categorical_2): ''' contingency_chi2(categorical_1, categorical_2) ''' crosstab = pd.crosstab(categorical_1, categorical_2) chi2, _, _, _ = stats.chi2_contingency(crosst...
def create(): with open("out.obj", 'w') as f: f.write("# OBJ file\n") f.write("o Point_Cloud.001\n") f.close() def pointswrite(x,y,z): with open("out.obj", 'a+') as f: f.write("v "+str(x)+" "+str(y)+" "+str(z)+" "+"\n") f.close() def finish(point): with open("out.obj", 'a+') as f: for n in point: po...
import scrapy from locations.items import GeojsonPointItem from locations.hours import OpeningHours import json import re class IHOPSpider(scrapy.Spider): name = "ihop" item_attributes = {'brand': "IHOP", 'brand_wikidata': "Q1185675"} allowed_domains = ["restaurants.ihop.com"] start_urls = ( '...
from torch.utils.tensorboard import SummaryWriter class dl_logger: def log(self,tag,message,idx): pass def close(self): pass class print_logger(dl_logger): def log(self,tag,message,idx=-1): print("{}: {}".format(tag,message)) class tensorboard_logger(dl_logger): ...
import sys sys.path.append("../") import unittest from python_dict_wrapper import wrap from models import get_dataset, preprocess_data, get_feature_model, get_aggregator from modelzoo import slowfast_wrapper import torch class TestSlowFast(unittest.TestCase): @unittest.skip("Slow") def test_each(self): ...
import pkg_resources try: __version__ = pkg_resources.get_distribution("nbb").version except Exception: __version__ = "unknown"
# Copyright 2017 Google Inc. All Rights Reserved. # # 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 ag...
import re from docutils.core import publish_cmdline, default_description from docutils.nodes import NodeVisitor from docutils.writers import Writer class WikidotTranslator(NodeVisitor): """Write output in Wikidot format. Based on http://www.wikidot.com/doc:wiki-syntax """ def __init__(self, document...
# -*- coding: utf-8 -*- """ Microsoft-Windows-Heap-Snapshot GUID : 901d2afa-4ff6-46d7-8d0e-53645e1a47f5 """ from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct from etl.utils import WString, CString, SystemTime, Guid from etl.dtyp import Sid from e...
from keras.preprocessing.image import ImageDataGenerator from sklearn.metrics import confusion_matrix # Below here is the code snippet for calculating various performance parameters of our model(). tpr=[] fpr=[] total_no_fp=0 total_no_tp=0 total_no_fn=0 total_no_tn=0 total=[] precision=[] f1=[] acc=[] sp=[...
# # Show customizing the circular scrolling animation of a label with `LV_LABEL_LONG_SCROLL_CIRCULAR` long mode. # label1 = lv.label(lv.scr_act()) label1.set_long_mode(lv.label.LONG.SCROLL_CIRCULAR) # Circular scroll label1.set_width(150) label1.set_text("It is a circularly scrolling text. ") label1.align(lv.A...
import unittest from wonk import create_app from wonk.models.users import db app = create_app('testing') class NeuralTestCase(unittest.TestCase): def setUp(self): self.test_client = app.test_client() with app.app_context(): db.create_all() self.populate_db() def tearD...
# Generated by Django 3.0.2 on 2020-03-28 21:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tutor', '0002_auto_20200328_1722'), ] operations = [ migrations.AddField( model_name='job', name='isConfirmed', ...
# coding: utf-8 from multiprocessing import Lock from .timer_task_entry import TimerTaskEntry class TimerTaskList(object): """ 延时任务列表,为双向链表结构 """ __lock = Lock() # 过期时间 _expiration = -1 # @property # def expiration(self): # with self.__lock: # return self._expir...
import unittest import cogent from cogent.tests import TestCase from cogent import settings settings.HTML_TEST_REPORT_FILENAME = "my_test_report.html" class TestClassOne(TestCase): def test1(self): # Pass Test Case expected_number = 90 actual_number = 90 print('Test output foe tes...
print ("boot.py loaded") from ___blocks.___main_block import MainBlock MainBlock.run()
"""Pipeline parallel on a single device. This is only used for debugging.""" from typing import Sequence, Any, Dict import jax from jax import linear_util as lu from jax.core import Var, ClosedJaxpr, Literal, gensym from jax.interpreters import partial_eval as pe from jax.interpreters.xla import DeviceArray from alpa...
from tornado import gen from engine.social.interface import SocialInterface from engine.social.web import WebSocialInterfaceMixin __author__ = 'kollad' class BackdoorSocialInterface(SocialInterface, WebSocialInterfaceMixin): def authenticate(self, handler): user_id = handler.get_argument('user_id') ...
# Import Tcl Tkinter Combobox to use it and modify default from tkinter.ttk import Combobox as ttkCombobox class Combobox(ttkCombobox): # combobox class can be called once the root tk is defined # only one must required field is root which is the any of widget # other params can be set to get different ...
""" -*- test-case-name: PyHouse.src.Modules.Web.test.test_web_house -*- @name: PyHouse/src/Modules/Web/web_house.py @author: D. Brian Kimmel @contact: D.BrianKimmel@gmail.com @copyright: (c) 2013-2015 by D. Brian Kimmel @license: MIT License @note: Created on Jun 3, 2013 @summary: Web interface to h...
import glob import json import tempfile import os END_DELIMETER = "*END_OF_FILE*" def download_files(my_socket): print("[+] Downloading files") tmp = tempfile.gettempdir() file_name = my_socket.receive_data() path_dir, actual_file_name = os.path.split(file_name) temp_path = os.path.join(tmp, ...
import mappyfile def test(): mapfile = mappyfile.open("./docs/examples/raster.map") # START OF API EXAMPLE # update the map name mapfile["name"] = "MyNewMap" # update a layer name layers = mapfile["layers"] layer = layers[0] layer["name"] = "MyLayer" # update the error file path i...
#!/usr/bin/python import RPi.GPIO as GPIO import time channel =7 data = [] j = 0 GPIO.setmode(GPIO.BOARD) time.sleep(1) GPIO.setup(channel, GPIO.OUT) GPIO.output(channel, GPIO.LOW) time.sleep(0.02) GPIO.output(channel, GPIO.HIGH) GPIO.setup(channel, GPIO.IN) while GPIO.input(channe...
#!/usr/bin/env python from math import * import rospy from gravl.msg import Hemisphere from message_filters import TimeSynchronizer from sensor_msgs.msg import NavSatFix # TODO Ensure that this still works with the custom hemisphere messages from ackermann_msgs.msg import AckermannDrive class GPSNavigationNode: ""...
from seamless.silk import Silk StructureState = Silk(schema=structurestate_schema) struc = StructureState() struc.data = struc_data for lineno0, line in enumerate(visualization.splitlines()): lineno = lineno0 + 1 pound = line.find("#") if pound > -1: line = line[:pound] if not len(line.strip())...
# -*- coding: utf-8 -*- # @Time : 2021/8/6 15:01 # @Author : zc # @Desc : 往来单位查询条件的请求实体 from chanjet_openapi_python_sdk.chanjet_content import ChanjetContent # 往来单位查询条件的请求实体 class QueryPartnerContent(ChanjetContent): def __init__(self, code, name, made_record_date): self.param = self.Params(code, ...
import numpy as np from scipy.stats import norm as norm from scipy.optimize import fmin_bfgs from copy import deepcopy class GridDistribution: def __init__(self, x, y): self.x = x self.y = y def pdf(self, data): # Find the closest bins rhs = np.searchsorted(self.x, data) ...
from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__, template_folder='template') app.secret_key = 'admin' @app.route('/') def index(): if 'username' in session: username = session['username'] return 'Logged in as ' + username + '<br>' + "<b><a href = '/logou...
from django import forms from decks.models import Deck, Card, Category class SearchDeckForm(forms.ModelForm): name = forms.CharField( label="Name", max_length=20, required=False, widget=forms.TextInput( attrs= {'placeholder': 'Search by deck name'} ) ) ...
from utils import device_create from utils.history_item import HistoryItem from datetime import datetime db = device_create.get_creator("202.193.57.131", "bitkyTest") LampStatusHistory = db.LampStatusHistory LampStatusHistory.drop() device_list = [] employees = db.Employee.find() print('共需执行次数:' + str(employees.count(...
from django.test import TestCase from .models import Profile,Posts,Comments,Following # Testing the 'Following' and 'Comments' class FollowingTestClass(TestCase): def setUp(self): self.esther=Following(username='mykey',followed='marabel') def test_instance(self): s...
from cgitb import Hook from colossalai.registry import HOOKS from torch import Tensor from colossalai.trainer.hooks import BaseHook from colossalai.utils.memory_tracer import AsyncMemoryMonitor from ._metric_hook import LearningRateMetric, MetricHook @HOOKS.register_module class MemTraceHook(BaseHook): """Save mem...