text
stringlengths
8
6.05M
""" 斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是: F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), 其中 N > 1. 给定 N,计算 F(N)。 示例 1: 输入:2 输出:1 解释:F(2) = F(1) + F(0) = 1 + 0 = 1. 示例 2: 输入:3 输出:2 解释:F(3) = F(2) + F(1) = 1 + 1 = 2. 示例 3: 输入:4 输出:3 解释:F(4) = F(3) + F(2) = 2 + 1 = 3. """ class S...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Jun 21 20:17:15 2018 @author: wanghao """ import tensorflow as tf import numpy as np from model import regression from glob import glob import os from scipy import io import time #import random tf.reset_default_graph() #用try...except...避免因版本不同出现导入错误问题 ...
from abc import ABCMeta, abstractmethod class Human(object): __metaclass__ = ABCMeta @abstractmethod def run(self): pass class Robot(object): __metaclass__ = ABCMeta @abstractmethod def vacuum(self): pass class Cyborg(Human, Robot): def run(self): pass de...
import pygame import mapaController import cheater import spriteLoader as tiles import random import time import os import sys class Player: def __init__(self): self.xp = 0 self.nivel = 1 self.sprite_atual = tiles.playerDict[pygame.K_s] # 24, 35 (final em cima) ...
# Generated by Django 2.1.2 on 2019-02-21 14:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('PC', '0008_auto_20190221_1153'), ] operations = [ migrations.AlterField( model_name='nuevanot', name='imagen', ...
class Puzzle: def __init__(self, cells): self.cells = cells @property def unsolved_cells(self): counter = 0 for cell in self.cells: if cell.val is None: counter += 1 return counter @property def total_possibilities_left(self): cou...
import pandas as pd import numpy as np import os #Takes in csv file and converts it to a txt file with corresponding price list training_data = pd.read_csv('') val_array = [] for i, row in training_data.iterrows(): val_array.append(row['Price']) #a_file = open("5_set.txt", "w") #np.savetxt(a_file, val_array, ...
import collections import sys MCU = collections.namedtuple('MCU', ['ports', 'pins_per_port']) MCU_LIST = { 'STM32F0': MCU(ports=['A', 'B', 'C', 'D', 'F'], pins_per_port=16), 'STM32F4': MCU(ports=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], pins_per_port=16), 'STM3...
import environment import tensorflow as tf import numpy as np import collections epsilon = 1 gamma = .9 alpha = .001 iterations =50 decay_rate = 1/iterations test_iterations = 50 max_moves = 100 win_reward = max_moves * 2 loss_reward = -win_reward max_memory_size = iterations * max_moves batch_size = int(max_moves/...
#!/usr/bin/env python import ujson import logging from typing import ( Dict, List, Optional, ) from sqlalchemy.engine import RowProxy from hummingbot.logger import HummingbotLogger from hummingbot.connector.exchange.radar_relay.radar_relay_order_book_message import RadarRelayOrderBookMessage from humming...
''' 0! = 1 1! = 1 2! = 2 * 1 = 2 3! = 3 * 2 * 1 = 6 4! = 4 * 3 * 2 * 1 = 24 ''' def fatorial(num): mult = 1 for i in range(num, 0, -1): mult *= i return mult print(fatorial(5))
#!/usr/bin/python import sys import tqdm import numpy as np import prody from pyRMSD.matrixHandler import MatrixHandler sys.path.append('/home/domain/silwer/work/grid_scripts/') import extract_result as er import util res = er.PepExtractor( database=sys.argv[1], resfile=sys.argv[2]) mpi = util.init_mpi() ...
import tensorflow as tf import numpy as np import cv2 from Unet_util import * class Config(): lr = 0.01 batch_size = 128 conv_kernel_size = 3 conv_stride = 1 deconv_kernel_size = 3 deconv_stride = 2 pool_kernel_size = 2 pool_stride = 2 l2_lambda = 0.0000001 color_num = 3 cla...
import torch import torch.nn as nn from torch.nn import init import torch.optim as optim import torch.nn.functional as F import torch.tensor from torchvision import datasets, transforms from torch.autograd import Variable # Add your own dataset as data_loader # Hyperparameters def conv2x2(in_c, out, kernel_size=3, ...
import logging import os from .utils import validate_inputs_outputs, get_size_of_dir l = logging.getLogger("[small_size]") DEFAULT_SMALLER_THAN_PCT = 0.1 class SmallSize: """Checks if the outputs size complies with our size conditions. The default condition, that can be overwritten by setting SMALLER_THAN_...
emp = {'Name': 'Anuj', 'Age': 18, 'Gender': 'Male'} print(type(emp)) print(emp) jtp = dict({1: 'Java', 2: 'T', 3: 'Point'}) print(jtp) dt = dict([{1, 'Ashish'}, {2, 'Singh'}, {3, 'Rohila'}]) print(dt, '\n') print("emp['Name']: ", emp['Name']) print("emp['Age']: ", emp['Age']) print("emp['Gender']: ", emp['Gender']) p...
import variables import json import requests import random YOUTUBE_CHANNELS_LIST_ID = 'https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id={0}&maxResults=50&key={1}' YOUTUBE_CHANNELS_LIST_USERNAME = 'https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername={0}&maxResults=50&key...
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from plotter import Plotter from data_splitter import DataSplitter from regressor import Regressor from sklearn.metrics import mean_squared_error from math import sqrt min_max_scaler = MinMaxScaler() df = pd.read_csv("market-price-2...
import smh import pickle from matplotlib import pyplot import sklearn.metrics import sys sys.path.append('../common/') import evaluation import dataLoader # Folder paths objectsRankingFile = 'allObjetsRankingFile.pickle' groundTruthFile = 'googleGroundTruth_selected.pickle' allObjetsToFileRanked = [] with open(object...
from omnipytent import * from omnipytent.ext.idan import * @task def run(ctx): local['./main.py'] & BANG @task def debug(ctx): CMD.VBGstartPDB3('main.py') @task def explore(ctx): local['ipython3']['-i', './main.py'] & TERMINAL_TAB @task def symlink_easypy(ctx): local['ln']['-s', local.path('/file...
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function from flask import request, g, make_response, jsonify from . import Resource from .. import schemas import ast class TimeslotsTimeslot(Resource): def get(self, timeslot): result = [] with open('dentists.txt', 'r') as f:...
import json from redis_client import RedisClient if __name__ == "__main__": params = json.load(open("redis_conf.json")) client = RedisClient(params) print(client.get("key1")) client.set("key1", "value1") print(client.get("key1"))
import pyfarms.naadsm def main(): pyfarms.naadsm.load_naadsm()
from matplotlib.dates import date2num import datetime as dt import logging import numpy as np import os import scipy.io as sio import networkNames as names import mospat_inc_directories as IncDir import IncludeFile as IncF from INetwork import INetwork from aux_operations import naive_num2date class Sodar(INetwor...
from collections import deque cola = deque() while True: print('1) Agregar documento a la cola de impresion') print('2) Imprimir') print('3) Salir') opcionmenu = input() if opcionmenu == '1': print('Se encontraron los siguientes archivos en la carpeta actual.') ...
import torch from pytorch_lightning import LightningModule class AveragePooling(LightningModule): """ Performs average pooling on the last hidden-states transformer output. """ def __init__(self): super(AveragePooling, self).__init__() def forward(self, attention_mask, encoder_outputs): ...
# coding:utf-8 __author__= "love_huan" #正则表达式的使用
""" Provides classes for creating RTMP (Real Time Message Protocol) for servers and clients. prekageo - https://github.com/prekageo/rtmp-python/ nortxort - https://github.com/nortxort/pinylib/ RTMP general information: http://www.adobe.com/devnet/rtmp.html RTMP Specification V1.0: http://wwwimages.adobe.com/content/d...
import random import math import pygame from pygame.draw import rect from pygame.mixer import pause # class includes methods to draw the map itself class RRTMap: def __init__(self, start, goal, mapDimensions, obsDim, obsNum): self.start = start self.goal = goal self.mapDimensions...
from flask import Flask from flask import render_template from localsettings import DEBUG app = Flask(__name__) # filters # ----------------------------------------------------------------------------- def children_are_same_orientation(row): return len({item['orientation'] for item in row}) == 1 @app.template...
# Generated by Django 3.0.1 on 2020-01-09 12:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('FinaceNote', '0008_auto_20200109_1510'), ] operations = [ migrations.AddField( model_name='upload', name='user_role'...
import numpy as np import matplotlib.pyplot as plt from math import factorial, log as ln t = [] v = [] infile = open("running.txt","r") for line in infile: tnext, vnext = line.strip().split(",") t.append(float(tnext)) v.append(float(vnext)) infile.close() def dv(x,y): dv=[0] for i in range(1,len...
import time import os import json from datetime import date import glob import imageio FREQUENCY = 10 IMAGES_DIR = 'timelapse/' def copy_photo(i): today_date = date.today().strftime('%Y_%m_%d') dir = os.path.join(IMAGES_DIR, today_date) try: os.stat(dir) except: os....
from utils import Config from models import MLP import gym import torch import numpy as np from utils import Logger from agents import MBPO """ the hyperparameters are the same as MBPO, almost the same on Mujoco and Inverted Pendulum """ algo_args = Config() algo_args.n_warmup=int(5e3) """ rainbow said 2e5 sample...
from turtle import * shape("turtle") speed(-1) for i in range (3, 7): for n in range (i): if i % 2 == 1: color('blue') else: color('red') forward(100) left(360 / i)
from django.apps import AppConfig class DrivingInstructorBuddy(AppConfig): name = 'drivingInstructorBuddy' def ready(self): import drivingInstructorBuddy.signals
# Generated by Django 2.2.4 on 2020-12-25 10:41 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('whcapp', '0001_initial'), ] operations = [ migrations.CreateModel( name='Profile', ...
""" modify ArrayQueue, so that the user can input a variable "maxlen", default value is None. if the user choose to set it, then the enqueue can trigger QueueFull exception. """ from example_queue import ArrayQueue from example_queue import Empty class Full(Exception): pass class ArrayQueueWithLengthLimit(Ar...
# -*- coding:utf-8 -*- """ 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出 斐波那契数列的第n项(从0开始,第0项为0)。n<=39 """ class Solution: # def Fibonacci(self, n): # # write code here # if n == 0: # return 0 # if n == 1 or n == 2: # return 1 # else: # return self.Fibonacci(n - 1...
# coding: utf-8 # In[1]: import cv2 import numpy as np import time # In[2]: IMG_SIZE = 50 LR = 1e-3 # In[3]: MODEL_NAME = 'dogsvscats_ver3_-{}-{}.model'.format(LR, '2conv-basic') # In[4]: import tflearn from tflearn.layers.conv import conv_2d, max_pool_2d from tflearn.layers.core import input_data, dro...
import csv import datetime from django.http import HttpResponse, StreamingHttpResponse from django.contrib import admin from django.urls import reverse from django.utils.safestring import mark_safe from .models import Order, OrderItem class OrderItemInline(admin.TabularInline): model = OrderItem raw_id_fiel...
# # copyright_notice # """glu module """ try : from opengltk.extent._glulib import * from opengltk.wrapper.glu_wrapper import * from opengltk.wrapper import glu_wrapper from opengltk import util except : gluPerspective =None gluPickMatrix =None gluUnProject =None gluErrorString =None ...
import numpy as np SENTIMENTS = [ 'anger', 'disgust', 'sadness', 'happiness', 'fear', 'surprise' ] def parse(utterances: list) -> dict: sents = [np.random.choice(SENTIMENTS) for i in utterances] conf_sents = [np.random.rand() for i in utterances] re...
# -*- coding: utf-8 -*- # Автор: Гусев Илья # Описание: Генератор батчей с определёнными параметрами. from typing import List, Tuple import pymorphy2 import numpy as np from russian_tagsets import converters from rnnmorph.data_preparation.grammeme_vectorizer import GrammemeVectorizer from rnnmorph.data_preparation.p...
#!/usr/bin/env python import asyncio import logging from typing import ( List, Dict, Optional, Coroutine ) from decimal import Decimal from web3 import Web3 from web3.contract import Contract from web3.datastructures import AttributeDict from hummingbot.logger import HummingbotLogger from hummingbot....
#!/usr/bin/env python #-*-coding:utf-8-*- ''' Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of positive numbers less than or equal to n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=...
def selectionSort(vetor): n = len(vetor) #Pego o tamanho do vetor na minha variavel n for i in range(n-1): #Laço que é responsável por descartar os valores que já são considerados como minimos min = i #Variavel que sempre guardará a primeira po...
# Generated by Django 2.2.1 on 2019-06-08 11:06 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('faculty', '0003_lecture_lec_batch'), ] operations = [ migrations.RemoveField( model_name='lectu...
# -*- coding: utf-8 -*- from unittest import TestCase class TestCore(TestCase): def test_package(self): pass
# Generated by Django 2.2.5 on 2019-10-21 14:07 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('students', '0001_initial'), ('workers', '0001_initial'), ] operations = [ migra...
N = int( input()) S = input() ans = 1 now = S[0] for i in range(1, N): if now == S[i]: continue now = S[i] ans += 1 print(ans)
''' author: juzicode address: www.juzicode.com 公众号: 桔子code/juzicode date: 2020.11.10 ''' print('\n-----欢迎来到www.juzicode.com') print('-----公众号: 桔子code/juzicode \n') import os,sys from email.header import Header from email.utils import parseaddr, formataddr from email.mime.text import MIMEText import email import p...
import numpy as np import matplotlib.pyplot as plt from mnist_utils import * def get_nearest_neighbour(training_data, sample): tmp = training_data if len(training_data.shape) > 2: #basically flattening the last dimensions of the trainingdata tmp = training_data.reshape(training_data.shape[0], -1) d...
# -*- coding: utf-8 -*- { 'name': "Smile Account Export", 'summary': "", 'description': "", 'author': "Smile", 'category': 'Accounting', 'version': '1.0', 'depends': ['account'], 'data': [ 'security/account_export_security.xml', 'security/ir.model.access.csv', '...
''' Created on Dec 13, 2013 @author: Raul ''' class MaterialType(): ''' Material Type ''' video="0" text="1" supported_materials=[video,text] def get_uni_type(self,lang,name): t = self.get_chapters(lang).index(name) return self.get_chapters("uni")[t] def g...
#!/usr/bin/env python __author__ = "Pruthvi Kumar, pruthvikumar.123@gmail.com" __copyright__ = "Copyright (C) 2018 Pruthvi Kumar | http://www.apricity.co.in" __license__ = "Public Domain" __version__ = "1.0" import argparse from colorama import Fore, Style from nucleus.execgen import ExecGen from nucleus.metagen impo...
import time import random from MSExploit import MSExploit class MSExploit_File_Upload(MSExploit): def __init__(self, name): MSExploit.__init__(self, name) self.fileType = "" self.fileName = "SneakyScript.exe" self.wormServer = "" self.t = None #Create def Create(self): while True: fType = raw_input(...
class Solution: def numUniqueEmails(self, emails): """ :type emails: List[str] :rtype: int """ result = set() for email in emails: simplified_email = "" at_found = False plus_found = False for j in range(len(email)): ...
n,x = map(int, raw_input().split()) count = 0 for i in range(1,n+1): while i != 0: if i % 10 == x: count += 1 i = i // 10 print(count) # #include<iostream> # using namespace std; # # int main () { # # int n=0,x=0; # int count=0; # cin>>n>>x; # for(int i=1;i<=n;i++) { # ...
#!/usr/bin/python #\file mouse_poly.py #\brief certain python script #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Feb.21, 2018 import numpy as np import cv2 def OnMouse(event, x, y, flags, param): if event==cv2.EVENT_LBUTTONUP: poly.append([x,y]) elif event==cv2.EVENT_RBUTTONUP: ...
import subprocess def ping_ip_addresses(ip_addresses): pinged = [] notpinged = [] for ip in ip_addresses: result = subprocess.run( ["ping", "-c", "3", ip], stdout=subprocess.PIPE, stderr=subprocess.PIPE ) if result.returncode == 0: pinged.append(ip) ...
# -*- coding: utf-8 -*- # © 2016 ONESTEiN BV (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models, api class HrHolidays(models.Model): _inherit = 'hr.holidays' @api.multi def compute_interval(self): res = super(HrHolidays...
def make_album(artist, album, amount_songs=""): dictionary = {'artist': artist, 'album': album} if amount_songs: dictionary['amount_songs'] = amount_songs return dictionary while True: print("Please enter an artist, album name and the amount of songs on the album(not needed)!") print("inp...
class Heap(object): # MAX heap HEAP_SIZE = 10 def __init__(self): self.heap = [0] * self.HEAP_SIZE self.currentPosition = -1 def insert(self, item): if self.isFull(): print('Heap is full') return self.currentPosition = self.currentPosition + 1 self.heap[self.currentPosition] =...
# Imprimindo o antecessor e o sucessor de um numero num = int(input('Entre com um numero inteiro: ')) print(f'O antecessor de {num} é {num - 1}\ne o sucessor de {num} é {num + 1}')
from os.path import join import pandas as pd from mvmm_sim.mouse_et.MouseETPaths import MouseETPaths def load_aligned_data(): # load metadata fpath = join(MouseETPaths().raw_data_dir, '20200625_patchseq_metadata_mouse.csv') metadata = pd.read_csv(fpath, index_col=0) metadata = metada...
# Generated by Django 2.2.5 on 2020-05-02 06:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Questionaires', '0008_response_responseitem'), ] operations = [ migrations.AlterField( model_name='responseitem', na...
""" This code is taken from https://github.com/choasma/HSIC-bottleneck More particularly, from https://raw.githubusercontent.com/choasma/HSIC-bottleneck/master/source/hsicbt/math/hsic.py Hence, we acknowledge the work of Wan-Duo Kurt Ma et al. and their paper 'The HSIC Bottleneck: Deep Learning without Back-Propagatio...
#!/usr/bin/env python3 # # Copyright (C) 2019 The Android Open Source Project # # 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 re...
#!/usr/bin/env python import setuptools setuptools.setup(name='orwell::admin', version='1.0', description='Orwell admin interface, server part. Depends on client part.', author='Orwell', url='https://github.com/orwell-int/messages', packages=['orwell', 'orwell.admin'], install_requ...
from itertools import permutations from nummath import isPrime,number for i in list(permutations([7,6,5,4,3,2,1])): if isPrime(number(i)) == True: print(number(i)) break
import sys import time from application.lib.instrum_classes import * from application.lib.instrum_panel import FrontPanel import instruments class Panel(FrontPanel): def __init__(self, instrument, parent=None): super(Panel, self).__init__(instrument, parent) self.title = QLabel(instrument.name...
import logging import typing import pygame from constants import CLIENT_STARTED, CLIENT_AWAIT, PLAYER_BUY_WORKER, PLAYER_BUY_WARRIOR, PLAYER_FINISH_STEP, \ PLAYER_ACTION_ATTACK from models.data.game import GameModel from models.game.player import Player from network import Network from views.buttons import Button f...
#Created by Will McDonald #for use in dataClass.py #created 6/5/17 #This file can be used to define functions that are used in other files from decimal import * #called as addUncert(filtDataSet,line) in dataClass.py where 'line' is the current line in the ensdf file def addUncert(datalist, currentLine): # print(...
'''We're dealing with two types of dispatchers here. One is the decorator-based dispatcher that can handle args passed into the decorator. The other does everything by calling user-defined functions to generate possible names of the dispatchable methods, with no decorator nonsense required. But ideally there should be ...
import numpy as np import torch from torch import nn from torch import optim from torch.autograd import Variable from torch.nn import functional as F from utils import batch_generator from utils import nb_classes from utils import nb_postags from utils import nb_chunktags from utils import max_sentence_size from lang_m...
def ExistChave(dicionario, chave): return chave in dicionario def TipoValor(valor): return type(valor) def isStatement(queryDic): if 'select' in queryDic and 'from' in queryDic: if('name' in queryDic['from']) and (type(queryDic['from']['name']) is str) and ('value' in queryDic['from']) and (type(q...
# Person (два свойства: 1. теперь full_name пусть будет свойством, а не функцией (одно поле, мы ожидаем - тип строка и # состоит из двух слов «имя фамилия»), а свойств name и surname нету, 2. год рождения). # Реализовать методы, которые: # • выделяет только имя из full_name # • выделяет только фамилию из full_name; #...
# Copyright (C) 2008 Sambit Bikas Pal, IISERK # Author: Sambit Bikas Pal , Email: sam@botcyb.org , sambit@iiserkol.ac.in # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version...
#!/usr/bin/python3 """ Generate navigable small world graphs. This script makes use of NetworkX to generate navigable small world graphs. This tool creates adjacency list files (.adj) whose filename represent the characteristics of the graph created. """ from keyname import keyname as kn import networkx as nx dims ...
''' Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets(both uppercase and lowercase) and numeric digits. Example: "abcde" -> 0 # no characters repe...
import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import matplotlib.pyplot as plt import time import math import multiprocessing from contextlib import contextmanager from src.Maze import Maze from src.PathSpecification import PathSpecification from src.Ant import Ant from src...
import sys import spotipy import random from sklearn.cluster import KMeans import numpy as np import statistics import math import pandas as pd # connect to spotify API from spotipy.oauth2 import SpotifyClientCredentials client_id = 'a85a76090c7e4e30ac2d5f08b73b2219' client_secret = '40e28d4fd9d9411081214d0c6a7a8298...
from django.contrib import admin # Register your modelx here. from .models import Contact, KITUser, Event, PublicEvent, MessageTemplate, \ SentMessage, SMTPSetting, CoUserGroup, ContactGroup, FundsTransfer,\ UploadedContact, CustomData, KITUBalance, KITActivationCode,\ ...
import math import vtk from PythonMetricsCalculator import PerkEvaluatorMetric # This should supersede the trace trajectory method # Use in combination with Slicer Markups To Model to get better visualizations of the trajectory # Slicer Markups To Model allows visualization methods to be customized class VisualizeTraj...
""" @author:ming @file:process_test.py @time:2021/10/28 """ from multiprocessing import Process """ 多进程 """ # class MyProcess(Process): # def __init__(self, name): # super(MyProcess, self).__init__() # self.name = name # # def run(self) -> None: # for i in range(1000): # ...
from setuptools import setup setup( name='utlyz', version=1.0, py_modules=[ 'fbcli', 'cricbuzz', 'lyrics', 'searching', 'news', 'football', 'xkcd' ], install_requires=[ 'click', 'bs4', 'BeautifulSoup', 'mechanize', 'requests', 'google', 'wikipedia', ], entry_points={ 'console_scrip...
# -*- coding: utf-8 -*- """ Created on Mon Dec 23 23:51:20 2019 @author: Cai """ import Sweep import Petal import numpy as np def demo_Sweep(): depot = np.array([[0,0]]) customers_location = np.array([[1,1], [1,-1], [-1,1], [-1,-1]]) customers = [] label = 0 for cl in customers_location: ...
import logging from typing import Optional, Dict from hummingbot.core.data_type.order_book_message import OrderBookMessage, OrderBookMessageType from hummingbot.core.event.events import TradeType from hummingbot.core.data_type.order_book import OrderBook from hummingbot.logger import HummingbotLogger from . import bin...
# -*- coding: UTF-8 -*- import sys, os sys.dont_write_bytecode = True import platform import json isWin = False isOSX = False def init() : global isWin, isOSX curSys = platform.system() isWin = curSys == 'Windows' isOSX = curSys == 'Darwin' init() if isOSX : import termios def press_any_key_exit(msg="Press ...
from django.contrib import admin from .models import Teacher # Register your models here. @admin.register(Teacher) class TeacherAdmin(admin.ModelAdmin): list_display = ['teacher','is_group_master','belong_to'] search_fields = ['teacher__username',]
# -*- coding: utf-8 -*- """ Created on Fri Feb 7 09:10:47 2020 @author: emilyk """ import SimpleITK as sitk import re from pathlib import Path import numpy as np import pandas as pd from scipy.stats import pearsonr import matplotlib.pyplot as plt dirname = Path.cwd() from segmentationVolume import segVol from utils i...
#网页解释 #创建beautifulsoup对象 from bs4 import BeautifulSoup import re html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/...
from django import forms from django.utils.translation import gettext_lazy as _ from portal.widgets import CDSRadioWidget class SearchForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.label_suffix = "" # Removes : as label suffix search_text = form...
import datetime import os import json from django.conf import settings from django.contrib.auth import get_user_model from django.core.validators import RegexValidator from django.core.exceptions import ValidationError from django.db import models from django.dispatch import receiver from django.db.models.signals impo...
#-*- coding:Latin-1-* from django.db import models class Etiquette (models.Model): denomination = models.CharField(max_length = 200) type = models.CharField(max_length = 200, blank = True) def __unicode__(self): return self.denomination class Meta: verbose_name = "etiquette" ve...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================= # Created By : Krikor Herlopian # Created Date: Tue April 06 2021 # Email Address: kherl1@unh.newhaven.edu # ============================================================================= cl...
from scapy.all import * ip = IP(src=sys.argv[1],dst='224.0.0.102') udp = UDP() hsrp = HSRP(group=1, priority=230,virtualIP='129.31.176.0') send(ip/udp/hsrp, iface='wlan0',inter=3,loop=1)
from collections import Counter N = int( input()) S = input() Q = 10**9+7 C = Counter(S) ans = 1 for c in C: ans *= C[c]+1 ans %= Q print((ans-1)%Q)
import datetime import unittest import os import sys sys.path.append("..") import time import threading import multiprocessing #from CliTestAutomation.cliEnvSetup.cmdconfig import cmdConfig from cliEnvSetup.cmdconfig import userOne, userTwo, userThree, Paths class Kubernetes_Multiusers_03(unittest.TestCase): d...