text
stringlengths
8
6.05M
# Taking arguments direct from the command line when ran from sys import argv script, first, second, third = argv # The arguments variable holds args passed to script when ran print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second print "Your third varia...
import os import time from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait def outputSadNo(driver): time.sleep(3) regno=driver.find_element_by_xpath(".//*[@id='Field8777']/input").get_attribute("value") ...
from unittest import TestCase from os.path import dirname from scrapy.http import HtmlResponse from scrapy.settings import Settings from scrapy.item import DictItem from scrapy.exceptions import DropItem from slybot.spidermanager import SlybotSpiderManager from slybot.dupefilter import DupeFilterPipeline _PATH = dir...
# -*- coding: utf-8 -*- """ Created on Thu Mar 12 08:13:00 2020 @author: pedro """ # -*- coding: utf-8 -*- """ Created on Mon Mar 2 08:06:33 2020 @author: pedro """ # test case 1 dimensions = [3,2] your_position = [1,1] guard_position = [2,1] distance = 4 # test case 2 dimensions = [300,275] your_position = [150,...
import os import tensorflow as tf # Suppress warnings and log information. os.environ['TF_CPP_MIN_LOG_LEVEL']='2' # # Graph definition. # a = tf.constant(2, name='a') # b = tf.constant(3, name='b') # x = tf.add(a,b, name='add') # # Create summary writer. # writer = tf.summary.FileWriter('./graphs', tf.get_default_gr...
# Generated by Django 3.2 on 2021-04-21 12:58 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='showchart', fields=[ ('id', models.BigAutoFie...
from Scapy_Control import * from TCP_flow_control import * from smb2command.Create_Close import * from smb2command.NBSession import * from smb2command.Negotiate import * from smb2command.Read import * from smb2command.SMB2Header import * from smb2command.SessionSetup import * from smb2command.Tree import * from smb2com...
import os import sys import shutil import subprocess import misc from datetime import datetime def start_log(log = 'sconstruct.log'): '''Begins logging a build process''' misc.check_lfs() if misc.is_unix(): sys.stdout = os.popen('tee %s' % log, 'wb') elif sys.platform == 'win32': sys....
import day06_part1, day06_part2 def test_part1_example(): input = [0, 2, 7, 0] assert day06_part1.solve(input) == 5 def test_part1(): input = list(map(int, open("day06_input.txt").read().split('\t'))) assert day06_part1.solve(input) == 6681 def test_part2_example(): input = [0, 2, 7, 0] ...
def readNumber(line, index): number = 0 while index < len(line) and line[index].isdigit(): number = number * 10 + int(line[index]) index += 1 if index < len(line) and line[index] == '.': index += 1 keta = 0.1 while index < len(line) and line[index].isdigit(): ...
"""Infrastructure subscription storages module.""" import json from collections import defaultdict, deque from contextlib import asynccontextmanager from typing import Iterable, Deque, Dict, Union import aioredis from .utils import parse_redis_dsn SubscriptionData = Dict[str, Union[str, int]] class SubscriptionS...
#import sys #input = sys.stdin.readline from heapq import heappush, heappop def main(): N = int( input()) AB = [ tuple(map(lambda x: int(x)-1,input().split())) for _ in range(N)] K = 4*10**5 V = [False]*K ANS = [-1]*N C = [0]*K E = [[] for _ in range(K)] h = [] for i, ab in enumerate...
def insert_sort(alist): for i in range(1,len(alist)): current_val = alist[i] position = i while position > 0 and current_val < alist[position-1]: alist[position] = alist[position-1] position -=1 alist[position] = current_val return alist chaine =[5,0,4,3,1...
# https://codility.com/programmers/task/tape_equilibrium def main(): print(solution([3,1,2,4,3])) # 1 def solution(A): head = A[0] tail = sum(A[1:]) smallest_difference = abs(head-tail) for x in xrange(1,len(A)-1): head += A[x] tail -= A[x] diff = abs(head - tail) ...
# -*- coding: utf-8 -*- # @Author: lc # @Date: 2017-07-25 17:00:26 # @Last Modified by: WuLC # @Last Modified time: 2017-09-11 21:12:42 ############################################################################################ # train AlexNet from scratch for image classification, that is facial expression recog...
class Employee: no_of_leaves=3 def __init__(self,ename,esalary,erole): self.name=ename self.salary=esalary self.role=erole def printdetails(self): return f"the name is{self.name}.salary is {self.salary}.role is{self.role}" @classmethod def __repr__(self): ...
from app.models.users import Users from app.models.assets import Assets from app.models.user_asset import User_asset from app import db from datetime import datetime from sqlalchemy import and_, distinct def release_asset(asset_id, email): user_id = Users.query.with_entities(Users.id).filter(Users.email == email).fi...
import sys def main(): def check_rock(posision_Ox, posision_Oy, wking_posision_Ox, wking_posision_Oy, list1): rook_move_Ox = [-1,1,0,0] rook_move_Oy = [0,0,1,-1] for i in range(0,4): Ox = posision_Ox Oy = posision_Oy while Ox >= 97 and Ox <= 104 a...
from ..models import Autobase as AutobaseDatabase from .. import app from . import default_config from .twitter_autobase import Autobase as AutobaseApp import logging logger = logging.getLogger(__name__) autobase_app = dict() # {'app_name':object, 'app_name_2':'error'} # Change default_config type object to dictiona...
# 스타 토너먼트 # 두 사람이 무조건 이겨서 다음 라운드에 진출한다고 가정했을때, # 과연 둘은 몇 라운드에서 붙는지? import math import sys # A, B가 인접 번호인지? def is_neighbor(A, B): N = math.ceil(max(A, B)/2) # 인접한 N번째 수들의 합은 3+4(N-1)이다. # 1:2 3:4 5:6 7:8 9:10 ... # 3 7 11 15 19 ... # 4 4 4 4 if A + B == 3 + (4 ...
from PyQt5.QtCore import QObject, pyqtSignal, QTimer, QThreadPool, QRunnable class PlayListScanner(QObject): dataLoaded = pyqtSignal(list) catId = 1 def __init__(self, dataSource): super().__init__() self.dataSource = dataSource self.timer = QTimer() self.timer.setInterv...
"""Author Arianna Delgado Created on June 18, 2020 """ """ Lambdas""" """ Anonymous Functions (no name).""" """Lambdas argument: logic expression --> return a function""" """Create a lambda that will calculate the cube of a given number""" f = lambda num: num ** 3 print(f(2))
# This is a sample Python script. # Press Umschalt+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. from __future__ import division import random import sys from mido import Message, MidiFile, MidiTrack, MAX_PITCHWHEEL i...
from django.db import models from django.contrib.auth.models import User from datetime import date class Mood(models.Model): mood = models.CharField(max_length=100) person = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateField(default=date.today) streak = models.SmallIntegerFiel...
n = 2 ** 1000 print sum((int(x) for x in str(n)))
#移动操作图片识别准确度, 此设置为默认值, 调用方法时仍可指定 moveConfidence = 0.9 #点击操作图片识别准确度, 此设置为默认值, 调用方法时仍可指定 clickConfidence = 0.9 #移动操作鼠标移动时间, 此设置为默认值, 调用方法时仍可指定 moveDuration = 0 #点击操作鼠标移动时间, 此设置为默认值, 调用方法时仍可指定 clickDuration = 0 #拖拽时间, 此设置为默认值, 调用方法时仍可指定 dragDuration = 0.3 #灰度匹配 grayscale = False #默认图片格式, 此设置为默认值, 调用方法时仍可指定 imageType...
def positive(x): return x>0
import sys movements={ "U":"j -= 1", "D":"j += 1", "L":"i -= 1", "R":"i += 1" } def dibuja_lab(size, route): maze = [["o" for i in range(size)] for i in range(size)] global i global j i = 1 j = 1 maze[j][i] = "x" for step in route: exec(movements[step], globals()) ...
#!/usr/bin/python # -*- coding: utf-8 -*- # @author: caramel def record_account(is_cheap3, good_price3, buy_amount4): if is_cheap3: total_cost = good_price3 * buy_amount4 print '跟老爸说完话,老妈走进卧室,在小本子记了买菜花销 %d元' % (total_cost) else: print '于是,进屋做其他事情了。' def talk_with_daddy(is_cheap3,buy_amount3): if is_cheap...
import random randomizer_questions = None randomizer_options = None def shuffle_question_num(question_num, active_section): if randomizer_questions is not None: return randomizer_questions[active_section-1][question_num-1] else: return question_num def response_transform (number, question_num...
def sorted_string(s1,s2): list_s1=list(s1) list_s2=list(s2) list_s1.sort() list_s2.sort() pos1=0 mtch=True while pos1<len(s1): if list_s1[pos1]==list_s2: pos1+=1 else: mtch=False return mtch
# -*- coding: utf-8 -*- ''' @author:王佳镭 ''' from Database.models import get_db from Database.tables import Favorite from FileHandler.Upload import AuthKeyHandler def TRresponse(item,url,retdata,isfav): authkey= AuthKeyHandler() m_trresponse = dict ( Tid=item.Tid, Tsponsorid=item.Tsponsorid, ...
from copy import deepcopy import pygame BLACK = (0, 0, 0) WHITE = (255, 255, 255) def minimax(position, depth, max_player, game, alpha, beta): if depth == 0 or position.winner() != None: return position.evaluate(), position if max_player: best_move = None for move in g...
from GetPokemon.models import Evolution_chain,Pokemon from rest_framework import viewsets from rest_framework import permissions from .serializers import Evolution_chainSerializer, PokemonSerializer class Evolution_chainViewSet(viewsets.ModelViewSet): queryset = Evolution_chain.objects.all() serializer_class =...
# Generated by Django 2.1.4 on 2019-01-13 17:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('speciality', '0036_auto_20190111_1651'), ('clientele', '0009_auto_20190113_1531'), ] operations = [ migrations.CreateModel( ...
""" 文件指针:就相当于光标,即,指向当前文件操作开始的位置 对文件进行任何的读写操作,都会修改文件指针的文职位置 r和w模式打开文件,指针都会在文件的起始位置 a模式打开文件,指针默认在文件末尾 tell():文件对象调用该方法,返回的是当前文件指针的读写位置,值是当前位置距离文件开头的字节数 seek(offset,whence):文件对象调用该方法,可以设置操作文件对象的指针位置 offset:偏移量,即距离whence指定的位置的字节数+数代表向右,-数代表向左 whence:设置偏移量的起始位置,取值有(0,1,2)0...
#!/usr/bin/python import rospy import time import numpy as np from ackermann_msgs.msg import AckermannDriveStamped from sensor_msgs.msg import LaserScan from ar_track_alvar_msgs.msg import AlvarMarkers import right import left class Follow_Wall(): def __init__(self): #:::::::::::::::::::::::::::...
# Bringing it all together! # This chapter will allow you to apply your newly acquired skills toward wrangling and extracting meaningful information from a real-world dataset—the World Bank's World Development Indicators. You'll have the chance to write your own functions and list comprehensions as you work with iterat...
import tkinter as tk from tkinter import * from Main.Auto_LR import LR from Main.Auto_MLR import MLR root=tk.Tk() root.title("Price Bite") root.geometry('{}x{}+0+0'.format(*root.maxsize())) root.tk.call('wm', 'iconphoto', root._w, PhotoImage(file="/Users/abhishek/Downloads/test/img/globe.png")) canvas =...
# Based on generate_pointcloud.py file which is copied in the same repository import argparse import sys import os from PIL import Image from DataStructures import Vertex, Triangle, DepthMap, BoundingBox focalLength = 525.0 centerX = 319.5 centerY = 239.5 scalingFactor = 1000.00 BIG = 9999999.99 #yeah, below follows...
# coding=utf-8 import centaFetcher, sys from centaFetcher import * def main(): host = "127.0.0.1" port = 3306 user = "root" password = "" database = "scrape" if len(sys.argv) == 4: action = sys.argv[1] startID = sys.argv[2] endID = sys.argv[3] fetcher = centaFetcher() fetcher.connectDB(host, port, us...
# -*- coding: utf-8 -*- ######################################################### # python import os import sys import logging import traceback import json import re import urllib import requests import threading # third-party # sjva 공용 # 패키지 from .plugin import logger, package_name from .model import ModelSetting, ...
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine from sqlalchemy import ForeignKey from sqlalchemy import Column, Integer, String, DateTime from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy.orm import relationship, backref engine = create_engine("sqlite...
''' First version of this uses azure-keyvault 1.1 As of October 2019, they updated the API 4.0.0 which uses very different approach to credentials. Today you need to provide SP credentials as it doesn't use any shared cache. Also need to install (pip) one more library - azure-identity. ''' from azur...
import pygame from pygame.locals import * import sys import time import random
import pymysql import requests from bs4 import BeautifulSoup from abc import * import crawling class Yes24BookCrawling(crawling.Crawling, ABC): def __init__(self, main_url, db_host, db_port, db_user, db_pw, db_name, db_charset): super().__init__(main_url, db_host, db_port, db_user, db_pw, db_name, db_cha...
#List to Dictionary Function for Fantasy Game Inventory #this function displays custom inventory def displayInventory(inventory): print('Inventory:') items_total = 0 #it loops over our inventory to print individual item and total items in inventory # k is key, v is value for k,v in inventory.items(): ...
""" Title: Basic Momentum V2 Desc: Apply a simple momentum strategy to 2hr candle stick data Author: Yassin Eltahir Date: 2017-09-11 """ # Required Packages import pandas as pd import numpy as np import seaborn as sns # Pretty Up the Plots %matplotlib inline sns.set() # Source Historical Data & Create Timestamp...
""" This is a solution to the HouseCanary Paper Streets coding challenge (http://bit.ly/2d9Ee8g). """ def count_paper_streets(x_intercepts: list, y_intercepts: list, homes: list) -> int: """ Finds the number of groups of paper streets on the map represented by the given x & y intercepts and homes A stree...
from main import notion from commands.run_daily_reset import run_daily_reset from commands.run_update_duration import run_update_duration if notion.UPDATE_DURATION: print("UPDATE_DURATION : ", run_update_duration()) if notion.DAILY_RESET: print("DAILY_REST : ", run_daily_reset())
def runneth_over(): runneth_over() runneth_over()
a=["e","a","f"] a.sort() print (a)
from panflute import * import uuid import redis import json def action(elem, doc): pass def finalize(doc): meta = doc.get_metadata() r = redis.Redis() try: if 'slug' not in meta: doc.metadata['slug'] = MetaString(str(uuid.uuid1())) r.mset({doc.get_metadata('slug'): json...
# Author: Lokesh Kodali # Date: 02-25-2017 # iterative version of PageRank algorithm from math import log, pow import operator class pageRank: def __init__(self): self.d = float(0.85) self.N = 0 # size of input self.P = {} self.PR = {} # page rank for each page self...
import io, argparse, os if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--input', type = str, help = 'input to data set folder (e.g. 2000, 3000)') parser.add_argument('--lang', type = str, help = 'language') parser.add_argument('--r', type = str, help = 'with or without replac...
import os import json import requests # to send GET requests to the server from bs4 import BeautifulSoup # to parse HTML of the page # user needs to input a topic and a number for number of files (max 20 images) GOOGLE_IMAGE = \ 'https://www.google.com/search?site=&tbm=isch&source=hp&biw=1873&bih=990&'...
import sys sys.stdin.readline() xs = map(int, sys.stdin.readline().split(' ')) res = [] t = 0 s1 = set() s2 = set() ss1 = 0 ss2 = 0 s = sum(xs) for ix in range(len(xs)): ss1 += xs[ix] ss2 += xs[len(xs) - ix - 1] if s % ss1 == 0: s1.add(ss1) if s % ss2 == 0: s2.add(ss2) s1 &= s2 f...
# -*- coding: utf-8 -*- """ Created on Wed Jan 2 12:34:53 2019 @author: Desenvolvimento 01 """ import numpy as np import matplotlib.pyplot as mp import pandas as pp file = pp.read_csv("Data.csv") idepe_cal =file.iloc[:,:-1].values depe_val = file.iloc[: , -1].values # missing data from sklearn.prepro...
""" LeetCode - Medium """ """ Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Note: Division between two integers should truncate toward zero. The given RPN expression is always valid. That means the expr...
# 2 class ApplyTask(Exception): pass # 3 class ApplyActionError(ApplyTask): pass class ApplySiteError(ApplyTask): pass class ApplyTypeError(ApplyTask): pass class ApplyRequestError(ApplyTask): pass class SpiderDoNotExists(Exception): pass class ListParseDoNotExists(Exception): pass ...
#!/usr/bin/env python3 """ test for the Program module. """ import unittest from base_test import PschedTestBase from pscheduler.program import run_program class TestProgram(PschedTestBase): """ Program tests. """ def test_return_code(self): """""" status, stdout, stderr = run_prog...
from collections import Mapping from marshmallow import fields, utils from six import string_types from .collection import set_related, clear_related, ListDescriptor from .exceptions import ImproperlyConfigured, ValidationError from .registry import get_model, get_polymorphic_model from .utils import cached_property,...
from django.conf.urls import url from stats import views urlpatterns = [ url(r'^$', views.statistics, name='statistics'), url(r'^statistics/$', views.statistics, name='statistics'), url(r'^login/$', views.user_login, name='login'), url(r'^register/$', views.user_register, name='user_registration'), ...
#!/usr/bin/env python import argparse parser = argparse.ArgumentParser() parser.add_argument('--vocab', '-v', required=True) args = parser.parse_args() for v in open(args.vocab): v = v.strip().decode('utf-8') v_wakachi = ' '.join(list(v)) if v == u'<eps>': v_wakachi = u'<eps>' elif v == u'blank': v_wakachi = u'b...
# coding=utf-8 import datetime import os import configparser from bs4 import BeautifulSoup import requests import shutil import numpy as np from PIL import Image from PIL import ImageOps from astropy.io import fits from astropy.table import Table as tb import sys from astropy.io.votable import parse,writeto,parse_singl...
from random import choice from requests import exceptions as req_exc from bs4 import BeautifulSoup from lxml.html.clean import clean_html, Cleaner user_agent_list = ['Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36', 'Mozilla/5.0 (Windows...
#!/usr/bin/env python3 import argparse from collections import namedtuple import math from svgwrite import Drawing Hexagon = namedtuple('Hex', 'vertices type') def generate_hexagonal_board(radius=2): """ Creates a board with hexagonal shape. The board includes all the field within radius from center of ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import time import openpyxl import tkinter as tk from tkinter import ttk import tkinter.messagebox import re import DbUtil def init(): # 窗口 window = tk.Tk() window.title('图书管理系统') window.geometry('450x300') # 画布放置图片 canvas = tk.Canvas(window, height=...
#!/usr/bin/env python # -*- coding: utf-8 -*- from bottle import * from testbackend import skicka from spotifybackend import search_artist import json HOST = "localhost" @route('/search') def search_artist(): """ queryn här ifrån sparas i artist som sedan söker i spotify och returnerar json, om man vill d...
import typing def iter_header_paths() -> typing.Iterator[str]: # header_paths = glob( # "../../third-party/Empirical/include/emp/**/*.hpp", # recursive=True, # ) yield from ( "base/macros.hpp", "config/config.hpp", "data/DataNode.hpp", "data/DataFile.hpp", "datastructs/...
""" use random.randrange(n) to model the function of random.shuffle(list). random.shuffle shuffles the list in place, here i will return a new list """ import random def shuffle(data): result = data[:] for i in range(len(data)-1): index = random.randrange(i, len(data)) # i <= index < len(data) ...
from django.shortcuts import render from .models import Post from .forms import PostForm from django.contrib.auth import get_user_model from django.shortcuts import redirect from django.http import Http404 me = get_user_model().objects.get(username='admin') # Create your views here. def post_list(request): posts ...
# -*- coding: utf-8 -*- """ Created on Sun Aug 30 21:12:16 2020 @author: enix45 """ import torch import torch.nn as nn #import torch.nn.functional as F #from nets.resnet import _weights_init import math import utils.DNAS as dnas from nets.sr_utils import MeanShift class EDSRBlockGated(...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/7/2 17:00 # @Author : TheTao # @Site : # @File : prepare_data.py # @Software: PyCharm import os import shutil import pandas as pd import pickle import jieba.posseg as psg from collections import Counter from data_process import split_text from cnra...
import math import os from collections import OrderedDict from struct import pack, calcsize from nltk.corpus import stopwords from sortedcontainers import SortedDict STOPWORDS = frozenset(stopwords.words('english')) class SPIMI: def __init__(self): self.doc_info = {} # to store doc_len and max_tf for d...
#!/usr/bin/python # -*- coding: utf-8 -*- # @author: Fanyujie # 今日的作业 # 有十种菜 # 白菜、萝卜、西红柿、甲鱼、龙虾、生姜、白芍、西柚、牛肉、水饺 # # 1. 老妈来到了菜市场,从下标 0 开始买菜,遇到偶数的下标就买 # 遇到奇数的下标就不买,买的数量为下标 + 1 斤 # (请写程序模拟整个过程) # (注意单一职责原则) # (注意灵活使用 def 函数(代码块)) # # 【提示】: # 输出结果可能为 # ‘老妈来到菜市场 # 老妈看到白菜,买了 1 斤 # 老妈继续逛 # 老妈看到x...
# from Geron, 14_recurrent_neural_networks # Demonstrate dynamic_rnn # # import numpy as np import tensorflow as tf def reset_graph(seed=42): tf.reset_default_graph() tf.set_random_seed(seed) np.random.seed(seed) reset_graph() n_steps = 2 n_inputs = 3 n_neurons = 5 X = tf.placeholder(tf.float32, ...
import time import math import numpy as np import scipy import scipy.sparse import scipy.sparse.linalg import scipy.io import heapq import random from klampt.math import vectorops # ============================================================================= # Install OSQP # pip install osqp # conda install -c conda-f...
print(" Please enter a celsius temperature") num_1 = float(input()) print("The equivalent Fahrenheit temperature is:") print((9/5) * num_1 + 32)
# Denoting Test Child Branch print("This is a test program for the Child_Branch")
import unittest, numpy, contextlib from nutils import sparse @contextlib.contextmanager def chunksize(n): chunksize = sparse.chunksize try: sparse.chunksize = n yield finally: sparse.chunksize = chunksize class vector(unittest.TestCase): def setUp(self): super().setUp() self.data = nump...
suma = 0 n=0 print("Unesite broj ili =") while True: x=input() if x=='=': print(" Srednja vrijednost brojeva je: " + str(suma/n)) break suma+=int(x) n+=1
import pytest @pytest.allure.feature('Nodes') @pytest.allure.story('Page CT') @pytest.mark.usefixtures('init_page') class TestPageCT: @pytest.allure.title('VDM-343 Page CT - creation') def test_page_ct_creating(self): self.node.fill_page_ct_mandatory() url = self.driver.current_url se...
from .evaluate import evaluate_model __all__ = [ "evaluate_model", ]
i=0 header = "" with open("../../Femesh/EIGENVAL") as fp, open("spindownFe.txt","w") as f: for line in fp: i=i+1 if i>7: numbers = line.split() if len(numbers) == 4: header = line elif len(numbers) == 5: #data num1 =...
# Generated by Django 2.2.4 on 2019-11-26 07:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('QualiaII', '0006_auto_20191126_0041'), ] operations = [ migrations.AddField( model_name='tblapc', name='marca', ...
from math import sqrt from random import randint class Point: def __init__(self,x,y,z): self.x = x self.y = y self.z = z self.tup = (x,y,z) #pixel coordinates to be updated by the space.update a b function self.a = None self.b = None self.pixel = No...
from django import forms import patient from patient.forms import Patient_detail_form from django.shortcuts import redirect, render from django.views import View from patient.models import Patient_detail,Appointment from .import forms # from django .contrib import auth from django.contrib.auth.models import auth,User #...
''' Created on Nov 8, 2015 @author: Jonathan ''' def minimumVotes(votes): changes = 0 while max(votes) != votes[0] : changes += 1 votes[votes.index(max(votes))] -= 1 votes[0] += 1 if votes.count(votes[0]) != 1: changes += 1 return changes if __name__ == '__main__': ...
#!/usr/bin/env python3 # # Development Order #4: # # Determine the duration of a specified test. # import datetime import pscheduler json = pscheduler.json_load(exit_on_error=True); #Rationale for timing values: https://docs.google.com/spreadsheets/d/1-5NABml5QcdBkCoF211HAFam8PGCpZkAaajcx8RII0M/edit?usp=sharing #...
import os from flask import current_app from sqlalchemy import * from sqlalchemy.pool import NullPool class DDBBBase: def __init__(self): self._uri = None self._engine = None self._conexion = None self._metadata = None self._username = None self._userpass = None ...
""" transfer(S, T): transfer elements in S to T, the top element in S will be in the bottom of T """ from example_stack import ArrayStack from example_stack import Empty def transfer(S, T): while not S.is_empty(): T.push(S.pop()) if __name__ == '__main__': S = ArrayStack() for i in range(10)...
from django.db import models CHOICES = ( ('M', 'Male'), ('F', 'Female') ) class ContactForm(models.Model): full_name = models.CharField(max_length=50) email = models.EmailField() gender = models.CharField(choices=CHOICES, max_length=128) mobile = models.IntegerField(max_length=10) address = ...
class RepeatStringEasy: def maximalLength(self,s): longest = "" for i in range(1,len(s)): lcsVal = self.lcs(s[0:i], s[i:]) if len(lcsVal) > len(longest): longest = lcsVal return len(longest) * 2 def lcs(self,a,b): #initalize grid lcsGrid = [[0 for y in ...
from typing import TYPE_CHECKING if TYPE_CHECKING: from onegov.wtfs import WtfsApp class UserManual: def __init__(self, app: 'WtfsApp'): self.app = app self.filename = 'user_manual.pdf' self.content_type = 'application/pdf' @property def exists(self) -> bool: assert s...
import time import datetime def current_time_mills() -> int: return round(time.time() * 1000) def date(mills: int) -> str: return datetime.datetime.fromtimestamp(round(mills / 1000)).strftime("%d.%m.%Y") def hour(mills: int) -> str: return datetime.datetime.fromtimestamp(round(mills / 1000)).strftime(...
import numpy as np # Load the training data data = open('kafka.txt', 'r').read() chars = list(set(data)) data_size, vocab_size = len(data), len(chars) print ('data has %d chars, %d unique' % (data_size, vocab_size)) # Encode/Decode char/vector char_to_ix = {ch:i for i, ch in enumerate(chars)} ix_to_char = { i:ch for ...
#!/usr/bin/env python """ _DCCPFNALImpl_ Implementation of StageOutImpl interface for DCCPFNAL """ from __future__ import print_function import os try: from commands import getoutput except ImportError: # python3 from subprocess import getoutput import logging import subprocess from WMCore.Storage.StageOu...
from webtest import Upload from tests.shared.utils import create_image, get_meta def test_view_images(client): assert client.get('/images', expect_errors=True).status_code == 403 client.login_admin() images_page = client.get('/images') assert "Noch keine Bilder hochgeladen" in images_page ima...
#import sys #input = sys.stdin.readline def main(): N = int(input()) L = list(map(int, input().split())) ans = 0 for i in range(N-2): for j in range(i+1, N-1): for k in range(j+1, N): a = L[i] b = L[j] c = L[k] if a < b+...