text
stringlengths
8
6.05M
# --------------------------------------------------------------------------- # extract_basin_DEM_statistics.py # Created on: 2014-07-22 18:31:56.00000 # (generated by ArcGIS/ModelBuilder) # Usage: extract_basin_DEM_statistics <Basin> # Description: extract elevation and slope characteristics for a basin shapef...
import tensorflow as tf from tensorflow.contrib.keras import layers from tensorflow.contrib.keras import initializers from app.layer.util import sparse_dropout, get_dotproduct_op from app.utils.constant import KERNEL, BIAS # Code borrowed from # * https://keras.io/layers/writing-your-own-keras-layers/ # * https://gith...
from django.shortcuts import render,redirect,HttpResponse from django.contrib.auth.hashers import make_password,check_password from account import models import json # Create your views here. def index(request): return redirect("/login/") def login(request): ret = {'status': False, 'error': "用户名或密码错误!!!", 'data': ...
import json from pathlib import Path from typing import Any, Callable, Optional, Tuple import PIL.Image from .utils import download_and_extract_archive, verify_str_arg from .vision import VisionDataset class Food101(VisionDataset): """`The Food-101 Data Set <https://data.vision.ee.ethz.ch/cvl/datasets_extra/foo...
import argparse import torch import numpy as np from models.networks.efficient_det_5 import get_net from models.fitter import Fitter from scripts.dataloder import get_dataloader from scripts.load_config import load_config def run_inference(): results = [] for images, image_ids in data_loader: predi...
from django.contrib import admin from Professor.models import Professor class ProfessorAdmin(admin.ModelAdmin): fieldsets = [ ('Professor', {'fields': ['usuario']}), ] list_display = ('usuario',) admin.site.register(Professor, ProfessorAdmin)
import math import matplotlib.pyplot as plt from Tkinter import * import Tkinter, Tkconstants, tkFileDialog fig, ax = plt.subplots() ax1 = fig.add_subplot() class Periodic(object): def __init__(self,endTime): """ Intializing the constructor @param endTime: Total time for plotting ...
__author__ = 'aoboturov' from load_data import target, users, items, log import pandas # How many unique users are in the target set? assert target.ix[:, 'user_id'].nunique() == 601 # How many unique items are in the target set? assert target.ix[:, 'item_id'].nunique() == 1161 # Are there any out of sample users i...
from epqcrypto.symmetric.hashing import hash_function from epqcrypto.persistence import save_data, load_data def hash_public_key(hash_function, public_key): """ usage: hash_public_key(hash_function, public_key) => public_key_fingerprint Returns a hash of public key, suitable for use as an identifier. ...
from flask import Flask import logging from logging.handlers import RotatingFileHandler from flask.logging import default_handler app = Flask(__name__) app.config.from_object('config.Config') logfile = app.config['ACCESS_LOGFILE_NAME'] logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logHandler = ...
import numpy as np from keras.layers import Dense from keras.models import Sequential def build_model(): model = Sequential() model.add(Dense(16, input_dim=16, activation='relu')) model.add(Dense(64, activation='relu')) model.add(Dense(4, activation='linear')) model.compile(loss='mse', optimizer="s...
import sys input_1 = '' input_2 = '' ds = None # Example: AL[G][O]R[ ]I[ ]T[H][M] ==> 6 # AL T R U I S T I C # # Recursive algorithm # # Running time is roughly between O(2^n) and O(3^n) # # Calculate all the possibilities and get the minimum # 1. Basecase is when either i or j is 0, then we just retu...
# should_continue = True # if should_continue: # print("Hello") # known_people = ["Jhon", "Anna", "Mary"] # person = input("Enter the person you know: ") # if person in known_people: # print("You know {}!".format(person)) # else: # print("You don't know {}!".format(person)) # numbers = [1, 2, 3, 4, 5, 6...
import numpy as np import pandas as pd from funcfile import * from sklearn import linear_model from sklearn.svm import LinearSVC from sklearn.pipeline import Pipeline from sklearn.preprocessing import PolynomialFeatures #read data df = pd.read_csv("week2.csv",comment="#") print(df.head()) x = np.array(df.iloc[:, 0:2])...
from channels.routing import include import scoring.routing routes = [ include(scoring.routing.routes, path='^/websocket/'), ]
class Solution: def lemonadeChange(self, bills): my_bill_5 = 0 my_bill_10 = 0 my_bill_20 = 0 success = True for bill in bills: if bill == 5: my_bill_5 += 1 elif bill == 10: if my_bill_5 > 0: my_bill_10 += 1 my_bill_5 -= 1 else: succes...
lower=int(input('lower:')) upper=int(input('upper:')) for num in range(lower,upper+1): if num>0: temp=num s=0 while temp>0: fact=1 dig=temp%10 for i in range(1,dig+1): fact=fact*i s+=fact temp//=10 if s==num:...
import nltk from glob import glob from sklearn.model_selection import KFold from sklearn.metrics import accuracy_score from nltk.stem import WordNetLemmatizer from nltk import word_tokenize import pickle matrix = [] lemmatizer = WordNetLemmatizer() #processa o vocabulário, gera os tokens, lemas e filtra o texto, retir...
from __future__ import print_function, absolute_import import logging import re import json import requests import uuid import time import os import socket import argparse import uuid import datetime import apache_beam as beam from apache_beam.io import ReadFromText from apache_beam.io import WriteToText from apache_be...
from SWTApp import app print("hello trout") if __name__ == '__main__': app.run()
from peewee import * import random import sys import os import time db = PostgresqlDatabase('flashcards', user="postgres", password='', host='localhost', port=5432) db.connect() class BaseModel(Model): class Meta: database = db class Cards(BaseModel): spanish = CharField() english = CharF...
import os import pandas as pd import plotly.express as px import plotly.io as pio import streamlit as st # consts APP_ROOT = os.path.dirname(os.path.abspath(__file__)) # data df = pd.read_csv( "{APP_ROOT}/data/data.csv".format(APP_ROOT=APP_ROOT), ) # style st.markdown( """ <style>.reportview-container ....
from fractions import gcd class Solution: # @param A : list of integers # @param B : list of integers # @return an integer def maxPoints(self, A, B): from fractions import gcd class Solution: # @param A : list of integers # @param B : list of integers ...
import numpy as np from scipy import linalg from scipy.integrate import dblquad #For Olivier and qcm #Copyright Charles-David Hebert class ModelNambu: """ """ def __init__(self, t: float, tp: float, tpp:float, mu: float, z_vec, sEvec_c) -> None: """ """ self.t = t ; self.tp = tp; self.mu =...
from .body import get_body_spec, get_body_generator from .brain import get_brain_spec, get_brain_generator from .robot import get_tree_generator, make_planar __author__ = 'Elte Hupkes'
from json import load from pprint import pprint as pp import requests # https://docs.pinata.cloud/api-pinning/pin-by-hash BASE_URL = 'https://api.pinata.cloud' PIN_BY_HASH = f'{BASE_URL}/pinning/pinByHash' def pin_request_body(cid, name): # TODO: skip name if missing, set creator as kv if not name: name ...
# This file is part of beets. # Copyright 2019, Rahul Ahuja. # # 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, mod...
#pin = "881120-1068234" pin = "881120-2068234" gender = int(pin[-7]) #성별은 주민번호 뒷자리 첫번째 숫자다 print("성별 숫자 : {0}".format(gender)) if gender==1: print("남성") elif gender==2: print("여성")
import datetime import pytz class Account(object): #simple account class with balance @staticmethod def _current_time(): utc_time = datetime.datetime.utcnow() return pytz.utc.localize(utc_time) def __init__(self , name , balance): self.__name = name self....
import datetime from rest_framework import generics, viewsets from docxtpl import DocxTemplate, RichText from django.http import HttpResponse from collections import OrderedDict from rest_framework.permissions import IsAuthenticated, AllowAny import html2text from ..models import AcademicPlan, Zun, WorkProgramIn...
import sys import queue input = sys.stdin.readline w = int(input()) h = int(input()) thing = [] start = None rooms = [] num_rooms = 0 visited = set() for _ in range(h): thing.append(list(input().strip())) for i in thing[-1]: if i != 'O' and i != '#': num_rooms += 1 if '1' in thing[-1]: start = (_, thi...
#!/usr/bin/env python3 """ This example shows how to generate basic plots and manipulate them with FEA In this case, we'll generate a 4D model and ruse FEA to find all possible 2D and 3D reduced models. We'll then solve for the solution spaces by breaking up each solution and finding the maximum and minimum values in...
def printSubprocessStdout(message, colors=True): if colors: print('\033[92m' + message.decode() + '\033[0m', end='') else: print('Subprocess: ' + message.decode(), end='')
# -*- coding: utf-8 -*- """ Created on Mon Nov 4 10:22:30 2019 DCE Preprocess, gets all of the inputs needed for the optimized DC_Eig_par function INPUT: DEM, cellsize, w, OUTPUT: cy cx cz @author: matthewmorriss """ import numpy as np def DCE_preprocess(DEM, cellsize, w): [nrows, ncols...
age = 56 count = 0 while count < 3: guess_age = int(input("age:")) if guess_age == age: print("lucky you,you get it..") break elif guess_age < age: print("think smaller....") else: print("think bigger....") count +=1 else: #当w...
# Generated by Django 2.1.7 on 2019-03-15 15:30 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('contest', '0006_auto_20190315_0024'), ] operations = [ migrations.AddField( model_name='submission', ...
#!/usr/bin/python import os import fileinput def getLocalRepo(): '''None->str Returns the path in localRepoPath.txt, which should contain the path of the local repository If it does not exist or file is empty, it will return an empty string ''' fname = "localRepoPath.txt" #textfile containing path ...
def cross(A, B): """Cross product of elements in A and elements in B.""" return [r + c for r in A for c in B] rows = "ABCDEFGHI" cols = "123456789" boxes = cross(rows, cols) row_units = [cross(row, cols) for row in rows] col_units = [cross(rows, col) for col in cols] square_units = [cross(rs, cs) for rs in [...
import unittest import json import time import tests.helpers as h class TestCluster(unittest.TestCase): # @h.timeout(60) def test_cluster_query(self): config_a = {"cluster": {"protocols": [{"type": "nativerpc", "port": 2000}], "useLocal": True, "tags": {"foo":...
''' Utilities functions ''' from __future__ import unicode_literals import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import pandas as pd import numpy as np import os import os.path as osp import utils import argparse import torch import math import numpy.linalg as linalg import scipy.linalg imp...
fiboSeq =[] a,b = 7,8 counter =1 print str(counter) + " " +str(a) print str(counter) + " " +str(b) while (counter<11): fiboSeq.append(a) a,b=b,a+b print str(counter) + " " + str(b) counter += 1 print fiboSeq ''' 1. Choose two smallish numbers (less than 10) 2. Add the two numbers and ...
from spack import * class Qgraf(Package): """FIXME: Put a proper description of your package here.""" homepage = "http://www.example.com" url = "https://gosam.hepforge.org/gosam-installer/qgraf-3.1.4.tgz" version('3.1.4', sha256='b6f827a654124b368ea17cd391a78a49cda70e192e1c1c22e8e83142b07809dd'...
#!/usr/bin/env python from __future__ import division from dateutil.parser import parse from copy import copy import os import csv import random import numpy as np import pandas as pd from sklearn import svm from sklearn import tree from sklearn.metrics import classification_report #class GenFeature: # def __init__...
from django.db import models from django.contrib.auth.models import User class Client(models.Model): """fishgirl's clients""" client_name=models.CharField("Nome", max_length=200, unique=True) client_address=models.CharField("Endereço", max_length=200) client_contact=models.CharField("Contacto", max_len...
# -*- coding: utf-8 -*- # vi:tabstop=4:expandtab:sw=4 """Transliterate Unicode text into plain 7-bit ASCII. Example usage: >>> from unidecode import unidecode: >>> unidecode(u"\u5317\u4EB0") "Bei Jing " The transliteration uses a straightforward map, and doesn't have alternatives for the same character based on langu...
# Import the commands module and run the fmr.R script. import subprocess #~ You can also use "commands" module #~ This script should be in the same directory as 'fmr.R' MyRScript = 'fmr.R' p = subprocess.Popen("Rscript --verbose " + MyRScript, \ stdout=subprocess.PIPE, shell=True) (output, err) = p.communicate() i...
import torch from torch import nn class MultiSampleDropout(nn.Module): def __init__(self, in_features, out_features, num_samples=5, dropout_rate=0.5): super().__init__() self.num_samples = num_samples for i in range(num_samples): setattr(self, 'dropout{}'.format(i), nn.Dropout(...
from datetime import timedelta from datetime import date import pandas as pd import pandas.io.sql as sqlio import psycopg2 import ta # The DAG object; we'll need this to instantiate a DAG from airflow import DAG # Operators; we need this to operate! from airflow.operators.bash_operator import BashOperator from airflow....
# -*- coding: utf-8 -*- import json import numpy as np import copy import time import os import os.path as op import sigraph import pandas as pd import random #Pytorch import torch import torch.nn as nn import torch.optim as optim from torch.utils.tensorboard import SummaryWriter #Brainvisa from soma import aims from ...
import vectorEntrenamiento as vE TrainingSet = [] TrainingSet.append( vE.VectorEntrenamiento( [23.3, 5, 15.2, 97.1], 0 ) ) #Enero TrainingSet.append( vE.VectorEntrenamiento( [27.2, 5.4, 16.3, 124.8], 0 ) ) #Febrero TrainingSet.append( vE.VectorEntrenamiento( [29.7, 6.4, 18.1, 201.4], 0 ) ) #Marzo TrainingSet.append( ...
#!/usr/bin/env python import pygame import mimo from utils import utils from utils import neopixelmatrix as graphics from utils import ringpixel as ring from utils.NeoSprite import NeoSprite, AnimatedNeoSprite, TextNeoSprite, SpriteFromFrames from utils.NewsProvider import news from utils import constants from random...
def reverseArray(alist): alist.reverse() print(alist) list1=[1, 2, 3, 4, 5, 6] list2=[89, 2354, 3546, 23, 10, -923, 823, -12] list3=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 18...
# -*- coding: utf-8 -*- """Functions to get data from NWP models. So far just TDS data and the public ECMWF FTP site. """ import abc import dataclasses import datetime import getpass import os import typing import urllib.request from contextlib import closing import numpy as np import xarray from metpy.constants impo...
import numpy as np import sys import math import time def coutingSort(lista,exp): B,C,k = [],[],10 for i in range(k): C.append(0) for j in range(len(lista)): C[int((lista[j] / exp) % 10)] += 1 B.append(0) for i in range(1,k): C[i] = C[i] + C[i-1] for j in range((len(lista)-1),...
''' Created on Mar 28, 2015 @author: anthonydito ''' import cPickle import logging import socket import threading import os from Tkinter import * logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] (%(threadName)-15s) %(message)s', ) class opponent(Frame): ...
name=input(str("Please input your name:")) phone=input(str("Please input your phone number:")) item=input(str("Please enter the name of the product you would like to purchase:")) price=float(input("Price of the product:")) qty=int(input("Quantity to purchase:")) subtotal=(price*qty) tax=(subtotal*0.06) total=(...
# This example uses a MovieWriter directly to grab individual frames and # write them to a file. This avoids any event loop integration, but has # the advantage of working with even the Agg backend. This is not recommended # for use in an interactive setting. # -*- noplot -*- import numpy as np import matplotlib matpl...
import sys, os import json load_img_list = [] num_chair = 0 chair_anno = [] with open('./instances_train2017.json', 'r') as load_f: load_dict = json.load(load_f) for key in load_dict: print(key) if key=='images': load_img_list = load_dict[key] print('num of images:%d'%le...
from django.shortcuts import render def get(request): return render(request, 'movies/index.html')
''' Original use of functions by Adam Bolton, 2009. http://www.physics.utah.edu/~bolton/python_lens_demo/ ''' # This code allows you to view the deflection gradients in both x and y directions. def deflection(lamp=1.5,laxrat=1.) import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridsp...
#Created on January 6, 2015 #@author: rspies # Python 2.7 # This script plots the mean pbias for the period surrounding an event of a specified magnitude. # Numerous events are chosen at each basin based on the criteria that eliminate smaller events # and events that may be impacted by multiple events. import o...
__author__ = "Narwhale" import os file_size = os.stat('第八周-第02章节-Python3.5月-上节回顾2.avi ').st_size print(file_size)
#! /usr/bin/python # coding=utf-8 import time import select import sys import os import RPi.GPIO as GPIO import numpy as np import picamera import picamera.array from picamera import PiCamera import matplotlib.pyplot as plt import matplotlib.image as mpimg import time import cv2 import math import threading import pid...
# Generated by Django 3.2.3 on 2021-05-16 18:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('categories', '0002_alter_categories_name'), ] operations = [ migrations.CreateModel( ...
#system import os import sys import logging import re import time import importlib import inspect import pkgutil #app import click import six from pprint import pprint from rich.console import Console from rich.table import Column, Table from PyInquirer import (Token, ValidationError, Validator, print_json, prompt, ...
""" http://2018.igem.org/wiki/images/0/09/2018_InterLab_Plate_Reader_Protocol.pdf """ import json from urllib.parse import quote import sbol3 from tyto import OM import labop import uml from labop.execution_engine import ExecutionEngine from labop_convert.markdown.markdown_specialization import MarkdownSpecialization...
from datetime import datetime, timedelta from pytz import timezone d = datetime(2012, 12, 21, 9, 30, 0) print d central = timezone('US/Central') loc_d = central.localize(d) print loc_d band_d = loc_d.astimezone(timezone('Asia/Kolkata')) print band_d d = datetime(2013, 3, 10, 1, 45) loc_d = central.localize(d) p...
import math import GLOBAL from document import Document class Competitor: def __init__(self, logo, rect, speed): self.__logo = logo self.__rect = rect self.__target = None self.__speed = speed def getRect(self): return self.__rect def selectTarget(self, docs, player): if self.__target a...
# -*- coding: utf-8 -*- # Icon made by Freepik from www.flaticon.com import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from neuralynx import * from program import * if hasattr(Qt, 'AA_EnableHighDpiScaling'): QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) i...
from yattag import Doc, indent import os class SubWorkflowAction: def __init__(self, name, flow): self.name = name self.sub_wf_path = flow def as_xml(self, indentation=False): doc, tag, text = Doc().tagtext() with tag('sub-workflow'): with tag('app-path'): ...
print("word"[0:3])
import logging import time import random import time import json from os.path import join from . import dependencies import urllib3 import requests urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) from .json_uploader.json_uploader import JsonUploader from .station_info.station_info import StationIn...
__author__ = 'Bill' import cProfile cProfile.run("from generate_palindromes import generate_palindromes; generate_palindromes(10**10)")
class Aresta: def __init__(self, verticeA, verticeB, w): self.verticeA = verticeA self.verticeB = verticeB self.w = w def setVerticeA(self, verticeA): self.verticeA = verticeA def setVerticeB(self, verticeB): self.verticeB = verticeB def setW(self, ...
# -*- coding: utf-8 -*- import scrapy from DaoMuBiJiSpider.items import DaomubijispiderItem class DaomubijiSpider(scrapy.Spider): name = 'daomubiji' allowed_domains = ['daomubiji.com'] start_urls = ['http://www.daomubiji.com/'] # "http://seputu.com/" def parse(self, response): """ 提取...
from django.utils.text import slugify # this function removes white space and put hyphens def unique_slug_generator(model_instance, title, slug_field): """ :param model_instance: :param title: :param slug_field: :return: """ slug = slugify(title) model_class = model_instance.__cl...
import pdb value = [1,2,3,4,5,6,7,8,9,10] for val in value: mysum = 0 mysum += val pdb.set_trace() print(mysum) import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s', datefmt = '%m/%d/%y %I:%M%S %p') logging.debug("This msg will be ig...
pyth = input("Do you know Python") js = input("Do you know JavaScript") csharp = input("Do you know csharp") if pyth == "Yes" and js == "No" or csharp == "Yes": print("JS is mandatory, Please try letter") elif pyth == "Yes" and js == "Yes" or csharp == "No": print("Welcome to CodeScript") else: print("Bett...
from __future__ import print_function import copy import random import datetime MAX = 1e10 class Team43: def __init__(self): self.termVal = MAX self.limit = 5 self.count = 0 self.gameweight = [[6,4,4,6],[4,3,3,4],[4,3,3,4],[6,4,4,6]] self.weight = [[2,3,3,2],[3,4,4,3],[3,4,...
""" THIS IS AN EXAMPLE INPUT FILE. NOT REQUIRED FOR THE SCRIPT TO WORK. """ from flask import Flask, request, redirect import os import jinja2 ## create template directory # grab the location of the folder for the current file, and append "templates" # as folder name template_dir = os.path.join(os.path.dirname(__nam...
# -*- coding: utf-8 -*- """ Created on Tue May 19 12:16:36 2015 @author: Martin Nguyen """ from numpy import random from StableIOPClass import StableIOP class TreatmentBlock2 (object): def __init__ (self,Attribute,params,medicalRecords): self.Attribute = Attribute self.params = params self....
#!/usr/bin/env python3.6 from copy import deepcopy import json import random def get_keys(data): """Generate list of keys to all (nested) attributes of data. Example: get_keys({'a': 1, 'b': [1, 2]}) -> [('a',), ('b',), ('b', 0), ('b', 1)] """ keys = [] if isinstance(data, dict): for...
"""liantang URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-ba...
from django.urls import path from . import views from home.dash_apps.finished_apps import simpleexample from home.dash_apps.finished_apps import app from home.dash_apps.finished_apps import app_user, tabel, table_amministrazione urlpatterns = [ path('', views.home, name='home'), path('welcome.html', views.hom...
# Report on people doing triage work in a project. This was originally # implemented so nova-core could track this in our weekly meetings. import sys import datetime from launchpadlib.launchpad import Launchpad if len(sys.argv) != 2: print 'Usage:\n\t%s projectname' % sys.argv[0] sys.exit(1) projectname = s...
# Stephanie Gillow # CS110 # I pledge my honor I have abided by the Stevens honor system. h = input("Enter your height in inches: ") w = input("Enter your weight in pounds: ") bmi = (int(w)*720)/(int(h)*int(h)) if bmi > 26: print("Your BMI is above the healthy range.") elif bmi < 19: print("Your BMI is below ...
################################################## # Anton Rubisov 20150109 # # University of Toronto Sports Analytics Group # # # # Scraping CrossFit Open information from # # http://games.crossfit.com/athlete/ # ##############...
# Oferece uma interface simplificada para que o cliente não se preocupe com a complexidade dos subsistemas class Igreja: def realiza_reserva(self): print('reserva da igreja realizada com sucesso') class Decoracao: def contrata_decoracao(self): print('Decoração contratada') class Grafica:...
d={(x,x+1):x for x in range(10)} print d t=(5,6) print d[t] print type(t)
import numpy as np list_a = np.array([25.6, 84.3, 12.7, 62.8]) list_b = np.array([5.21, 34.3, 98.2, 46.4]) print list_a * list_b print list_a * 2
#!/usr/bin/env python # coding: utf-8 # Copyright (c) Qotto, 2019 """ KafkaConsumer class This class consume event / command / result in Kafka topics. Todo: * In function listen_store_records, add commit store (later V2) """ import asyncio import json from logging import Logger, getLogger from typing import Lis...
import gym import numpy as np from draw import * from Agent import Agent from new_env import * class Main(): def __init__(self): self.layer_number = 3 self.env = Env_graph(200, 5, 233) self.limit = 200 self.agent = Agent(10,1,range(5),delete_by_env_model = True) self.eps =...
import checkPosition def board(positionNow) : board = [ [" ","E","B","I","2","I","B","E","B","E"," "," "," "," "," "," "], [" ","I"," "," ","B"," "," "," "," ","W","B"," ","E","B","I",' '], [" ","M"," "," ","I","E","B","W"," "," ","E","B","I"," ","D",' '], [" ","E","B","...
from flask import Flask, render_template, request , redirect , url_for from db import dbconnection from conversion import get_dict_resultset import pandas as pd conn = dbconnection() cur = conn.cursor() app = Flask(__name__) @app.route('/contacts', methods=['GET','POST']) @app.route('/contacts/<method>/<contact_id...
import requests from bs4 import BeautifulSoup # # r = requests.get("http://www.baidu.com") # r.status_code # print(r) # # r.encoding='utf-8' # print(r.text) #显示网页内容 # def getHTMLText(url): # try: # r = requests.get(url) # r.raise_for_status() # 如果状态值不等于200,引发HTTPError异常 # r.encoding = r....
#http://live.amasupercross.com/xml/sx/RaceResults.json? import urllib2 import twitter import time import pandas as pd import itertools import random import config import json import re from xml.etree import cElementTree as ET MX = False #for MX and SX mode tweet_this = False top_x_dict = {0 : 10, 10 : 5, 15 : 3} po...
from django.db import models # Create your models here. class Album(models.Model): singer=models.CharField(max_length=30) singer_album=models.CharField(max_length=30) genre=models.CharField(max_length=30) def __str__(self): return self.singer + "---" + self.singer_album class Song(mode...
# This Python file uses the following encoding: utf-8 import sys import os from PySide2.QtWidgets import QApplication, QWidget from PySide2.QtCore import QFile from PySide2.QtUiTools import QUiLoader class App(QWidget): def __init__(self): super().__init__() self.setWindowTitle("SWS_FACE_RECOGNI...
# Copyright 2021 DAI Foundation # # 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,...
import os from distutils.core import setup from distutils.sysconfig import get_config_vars exec_prefix, libdir = get_config_vars('exec_prefix', 'LIBDIR') if libdir.startswith(exec_prefix + '/'): libdir = libdir[len(exec_prefix)+1:] plugindir = os.path.join(libdir, 'nagios/plugins') fd = open('VERSION','rw') vers...