text
stringlengths
38
1.54M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Yuri' from setuptools import setup, find_packages setup( name='selenium-webdriver-manager', version='1.0.1', description='Simplify management of selenium-drivers for different browsers', author='Yuri', author_email='yuri_zhong@epam.com'...
# encoding: utf-8 """ This is the official entry point to IPython's configuration system. There are two ways this module can be used: 1. To customize various components of IPython. 2. To access to configuration information for various components of IPython. Customization ============= Configuration information ...
import sys import os def main(): # operators: +, -, *, /, parentheses x = 1 y = 2 print(x + y) print(x * y) print(x / y) print(x - y) # BODMAS - brackets of division multiplication addition subtraction z = 7 print(x + y * z) print((x + y) * z) print(2 // 7) # integer di...
''' for row in range(1, 10): str1="" space=" " for col in range(1,row+1): if(row==3 and col==2) or (row==4 and col==2): space=" " else: space=" " str1+=(str(row)+"*"+str(col)+"="+str(row*col)+space) print(str1) ''' hang=0 while hang<=8: han...
#!/usr/bin/env python3 import socket import readline import urllib.parse import re # Bootstrap: $repl.set_buffer 0, Object.http_get('http://XXX:6666/$init') # Usage: Type in a command to execute it # Commands: # .load: Load an execute a file from the server # .exit: Quit the REPL on the Switch OUTPUT_RE = re.compile(...
#!/usr/bin/env python3 from pyquery import PyQuery as pq from lxml import etree import urllib import re import json import sys urls_tmp = [] urls = { "atom": [], "rss": [] } def get_content_type(url): try: f = urllib.request.urlopen(url) content_header = (f.info().get(...
import os import csv import numpy as np import PIL from PIL import Image def getcsvlines(path, delimiter=" "): text = [] with open(path, "r") as csvfile: reader = csv.reader(csvfile, delimiter=delimiter) for row in reader: text.append(row) return text output = "build/" outpu...
""" Copyright 2017-2022 Department of Electrical and Computer Engineering University of Houston, TX/USA ********************************************************************************** Author: Aryan Mobiny Date: 8/1/2017 Comments: ********************************************************************************...
import os from nose.tools import raises from unittest import TestCase from graphkit import Manager, GraphKitException from .util import fixture_uri class ManagerTestCase(TestCase): def setUp(self): super(ManagerTestCase, self).setUp() self.data, self.uri = fixture_uri('demo.yaml') def test...
import math def pythagoras(a,b): return math.sqrt(a**2+b**2) a = 3 b = 4 c = pythagoras(a,b) print("Als een driehoek twee rechte zijdes heeft van lengte ", a, "en", b, "dan heeft de schuine zijde lengte", c)
EMPTY_INDENT = ' ' PIPED_INDENT = '| ' SPLIT_INDENT = '├──' ELBOW_INDENT = '└──' ARRAY_INDEX = '─┐' def is_flat(data): return isinstance(data, list) or isinstance(data, set) or isinstance(data, tuple) def data_struct_as_tree(data, indent='') -> str: out_str = '' if isinstance(data, dict) and len(...
# These dictionaries are merged with the extracted function metadata at build time. # Changes to the metadata should be made here, because functions.py is generated thus any changes get overwritten. functions_override_metadata = { } functions_additional_burst_pattern = { 'FancyBurstPattern': { 'python_nam...
from django.db import models class Register(models.Model): cont = models.IntegerField(default=10, unique=True) email = models.EmailField(max_length=50, primary_key=True) name = models.CharField(max_length=20) psw = models.CharField(max_length=20) class Expenditure(models.Model): email = models.F...
def is_palindrome(string) -> bool: if len(string) <= 1: return True return string[0] == string[-1] and is_palindrome(string[1:-1])
__all__ = ['grade_assignment1'] class TestFunction(object): def __init__(self, function, str_test): self.func = function self.run_test_suite() self.str_test = 'Testing {}'.format(str_test) def run_test_suite(self): methods = [method for method in getmembers(self, ismethod) ...
from .target import Target import src.resources as res class Watermelon(Target): # def __init__(self, image, pos, screen, debug: bool = True): def __init__(self, pos, screen, debug: bool = False): watermelon = res.gfx('watermelon.png', convert=True) Target.__init__(self, watermelon, pos, s...
import math class Optimizer(object): def __init__(self, matches): self.team_size = 2 self.matches = matches self.players = self.get_players() self.match_limit = self.get_match_limit(self.players) self.player_game_limit = self.get_player_game_limit(self.players) self.player_game_counts = self....
"""Gets the dominant colors in an image""" from sklearn.cluster import KMeans import numpy as np import cv2 from vision.images import show_debug def centroid_histogram(clt): """Gets number of different clusters and returns a normalized histogram from number of pixels assigned to each cluster. For example: 'ce...
# coding:utf-8 # =============================== # 类的继承 # class Parent: # # def __int__(self): # parentAttr = 1 # def myMethod(self): # print "父类方法" # def setAttrZ(self,setattr): # self.parentAttr = setattr # def getAttr(self): # print self.parentAttr # # class Child(Pare...
if __name__ == "__main__": user_input = int(input("How many times do you want to AYAYA?")) string = "AYAYA" for i in range(user_input): print(string)
frase = 'Curso em Vídeo Python' print(frase) print(frase[3]) print(frase[3:13]) print(frase[:13]) print(frase[13:]) print(frase[1:15]) print(frase[1:15:2]) print(frase[1::2]) print(frase[::2]) print(frase.count('o'))#o =! O #Pega a frase, joga para maiúscula, e conta a quantidade de 'O"s print(frase.upper().count('O'...
#!/usr/bin/python # -*- coding: utf-8 -*- ''' This module provides a basic assembler for a simcpu. @author: Nicola Coretti @contact: nico.coretti@gmail.com @version: 0.1.0 ''' import re import sys import argparse # Instructions ----------------------------------------------------------------- # does nothing NOP = 0...
from config import DATABASE import numpy as np import psycopg2 from postgis.psycopg import register from datetime import datetime, timezone from util import utc_timestamp def filename(step, start_time, end_time): ts_s = datetime(2019, 10, 10, start_time[0], start_time[1], start_time[2]) ts_s = int(utc_timesta...
#!/usr/bin/eny python3 #sutimar pengpinij #590510137 #Lab 08 #problem 4s #204111 Sec 003 def main(): n = int(input()) print(series(n)) def series(n): if n <= 0: return 0 elif n == 1: return 1 elif n == 2: return 3 else: return (2**(n-1))+ser...
#!/usr/bin/env python import sys import re import subprocess import os.path def usage(): sys.stderr.write("usage: %s symboldir crashfile\n" % sys.argv[0]) sys.exit(1) if len(sys.argv) != 3: usage() build_path = sys.argv[1] crash_filename = sys.argv[2] def addr2line(lib, addr): lib_name = os.path.bas...
# -*- coding: utf-8 -*- """ Created on Tue Feb 9 23:05:20 2021 @author: kastu """ import os import csv #1.Open the csvfile csvpath = os.path.join("Resources","budget_data.csv") cnt = 0 totalProfitLoss = 0 greatestmnt = "" cgreatestinc = 0 fgreatestinc = 0 flowestinc = 0 profit = 0 loss = 0 #2.Read the csvfile with...
# coding: utf-8 # Create DEM FITS files for all the recorded shocks in CR-NEI-hydro import numpy as np from astropy.table import Table import os import astropy.io.fits as fits import time path_files = os.getcwd() + '/' filename = 'DEM_allages_FS.dat' dem = [] with open(path_files + filename) as Dem: for n, ...
''' ************************************************ ____ ____ _ ___ __ / ___/ ___| / |/ _ \ / /_ | | \___ \ | | (_) | '_ \ | |___ ___) | | |\__, | (_) | \____|____/ |_| /_/ \___/ Problem set 1 Question 1 A common problem in computer science is finding patterns within data. This problem will simula...
# Always restore open sites when qutebrowser is reopened. # Equivalent of Firefox's "Restore previous session" setting. c.auto_save.session = True # Load a restored tab as soon as it takes focus. c.session.lazy_restore = True # Unlimited tab focus switching history. c.tabs.focus_stack_size = -1 # Close when the last...
import pathlib from setuptools import setup README = (pathlib.Path(__file__).parent / "README.md").read_text(encoding="utf-8") setup( name="PyFuzzy-renamer", version="0.2.2", description="Uses a list of input strings and will rename each one with the most similar string from another list of strings", ...
import flask from flask import Flask, request, jsonify from imageai.Prediction.Custom import CustomImagePrediction import os import os.path from keras import backend as K import json from cv2 import imread from cv2 import CascadeClassifier # load the photograph # load the pre-trained model # ---------------------------...
"""Implementation of partial-become rule.""" # Copyright (c) 2016 Will Thames <will@thames.id.au> # # 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 limi...
import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mavAgenda.settings") django.setup() from landing.models import * #################### # General Education #################### # English - except English 1050, 1090, and 1100 english = Course.objects.filter(course_subject='ENGL') eng_req = Re...
#-- #@(#)stats.py # # stats # Copyright(c) 2011 Supreet Sethi <supreet.sethi@gmail.com> from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor from twisted.internet import task from recieve_pb2 import Event from logging import basicConfig, info, debug, warning import logging from ...
import os import sys sys.path.append(os.path.join( os.path.abspath(os.path.dirname(__file__)), '../parser/config') ) import numpy as np import word2vec as wv from config import * ROOT = PATH_DATA_WORD2VEC BIN_PATH = ''.join([ROOT, 'text.bin']) class Vector(object): model = None pos_model = None arclabe...
#!/usr/bin/python import alsaaudio capabilities = { "volume" : True, "bass" : False, "mid" : False, "treble" : False } app_modes = { "RAD" : True, "AIR" : True, "SPOT" : True, "AUX" : False, "USB" : False } # init the alsa software mixer def init(): ...
# # @lc app=leetcode id=295 lang=python3 # # [295] Find Median from Data Stream # # https://leetcode.com/problems/find-median-from-data-stream/description/ # # algorithms # Hard (38.01%) # Total Accepted: 140.3K # Total Submissions: 354.3K # Testcase Example: '["MedianFinder","addNum","addNum","findMedian","addNum"...
import numpy as np import matplotlib.pyplot as plt import pandas as pd ''' mylist=[[2,3,-5],[21,-2,1]] a=N.array(mylist,dtype='d') b=N.zeros((3,2,4),dtype='d') c=N.arange(10) d=[1,2,3,4,5] e=N.zeros((4,5,2),dtype='d') f=N.array([[2,3.2,5.5,-6.4,-2.2,2.4], [1,22,4,0.1,5.3,-9], [3,1,2.1,21,1.1,-2]]) g=N.arange(6) h...
#==============================================# # if __name__ == "__main__" # #==============================================# #Lets create 2 .py files. #mymath.py def add(a,b): """Function that will add the 2 passed parameters""" return a + b #Print the output of function when passed 2 pa...
# Import Connetion.py for DB Instance import sys # sys.path.append('../') sys.path.insert(0, sys.path[0]+'\\database') from connection import Database def test_connection(): # Creating a Connection new_instance = Database() cnx = new_instance.database_connector() cursor_variable = cnx.cursor() ...
from urllib import quote_plus from django.contrib.localflavor.us.us_states import US_STATES, US_TERRITORIES from django.contrib.localflavor.us.models import PhoneNumberField from django.db import models from django.template.defaultfilters import slugify from django.utils.translation import ugettext as _ from sunlightc...
from elasticsearch import Elasticsearch import sys import json import getopt import time es = None def put(index_name, doc_type, id, doc, tries=0): res = None failed = False try: res = es.index(index=index_name, doc_type=doc_type, id=id, body=doc) except Exception: failed = True ...
num=int(input()) sam=input().split()[:num] dub1=[] for i in range(0,num): if i%2==0: if not int(sam[i])%2==0: dub1.append(sam[i]) else: if int(sam[i])%2==0: dub1.append(sam[i]) for i in dub1: print(i,end=" ")
import urllib.request # 发送请求 import requests import re # 正则表达式 from bs4 import BeautifulSoup # 1.获取网页源码 def gethtml(): # 封装代码 url = 'http://ncov.dxy.cn/ncovh5/view/pneumonia' User_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36' ...
# -*- coding:utf-8 -*- __author__ = 'leezp' __date__ = 20191231 import asyncio import aiohttp import aiomultiprocess import aiofiles import queue import datetime import random from lxml import etree import urllib3 import UA_Pool as UApool import re import argparse def parse_args(): parse = argpars...
def sum_numbers(input_file): my_sum = 0 for line in open(input_file): my_sum += int(line) print str(my_sum)[0:10]
''' tests the common.logger.Logger class, which is responsible for logging messages to disk, and for reading them back ''' from common.logger import Logger from common.message import Message from contextlib import contextmanager from tests import TestCase, test_main import os import shutil from datetime import datetim...
""" Main wrapper of NPL data processor packages """ '''___Built-In Modules___''' from os.path import dirname import sys '''___Third-Party Modules___''' '''___NPL Modules___''' sys.path.append(dirname(__file__)) from ProductProcessingTool import ProductProcessingTool '''___Authorship___''' __author__ ...
import torch import torch.autograd as autograd def calc_gradient_penalty(netD, real_data, fake_data, batch_size, lda, view): alpha = torch.rand(batch_size, 1) alpha = alpha.expand(batch_size, real_data.nelement()/batch_size).contiguous().view(view) alpha = alpha.cuda() interpolates = alpha * real_dat...
import json import ftplib import searchItems import string import re class BoxServer: def __init__(self): with open('config.json', 'r') as json_data: config = json.load(json_data) boxAddress = config["serverSettings"]["address"] username = config["serverSettings"]["username"] ...
''' Daniela é uma pessoa muito supersticiosa. Para ela, um número é sortudo se ele contém o dígito 2 mas não o dígito 7. Então, na opinião dela, quantos números sortudos existem entre 18644 e 33087, incluindo os extremos? Resposta: 7995 ''' contador = 0 for c in range(18_644, 33_088): if '2' in str(c) and '7' not...
def cube(number): """Returns the cube of a number""" cube_number = number ** 3 print "The cube of %d is %d" % (number, cube_number) return cube_number print cube(2)
import pygame, sys import numpy from Actors.Footprint import Footprint class Ant(): """description of class""" __id = 0 def __init__( self, size ): """description of class""" self.footprint = Footprint( size ) self.__antx = 0 self.__anty = 0 se...
import os import ray import abc import json import logging import numpy as np import pandas as pd import tensorflow as tf from inspect import signature from utils.local_settings import VERBOSE from sqlalchemy import Table from sqlalchemy.engine import create_engine from sqlalchemy.schema import MetaData from sqlalchem...
import sys import os import tkinter.filedialog import tkinter.messagebox from PIL import Image,ImageTk import pdb import time from selenium import webdriver from selenium.webdriver.chrome.options import Options import csv from datetime import datetime import base64 import json from requests import Request, Session from...
import Id name = Id.get_name() addr = Id.get_addr() dob = Id.get_dob() print("name:", name) print("addr:", addr) print("dob:", dob)
from panda3d.core import WindowProperties, NodePath class FakeScreen3D: def __init__(self, gameEngine, screen_number, shuttle_angle=0, shift_x=0, shift_y=0.0): self.gameEngine = gameEngine self.screen = screen_number self.cam_node = self.gameEngine.make_camera(self.gameEngine.win, ...
# -*- coding:utf-8 -*- import os import glob import csv import random import shutil # 文件转移 path = './train/*' path_t='./train_1' if not os.path.exists(path_t):os.mkdir(path_t) image_paths = glob.glob(path) i=0 for path in image_paths: path2=glob.glob(os.path.join(path,'*')) if len(path2)>50: if not o...
def hIndex(pubs): n = len(pubs) freqs = [0] * (n + 1) # create a list of the count of papers # where the citation score is equal to the # list index score. If the score is greater # than the number of papers published, then # count it towards the end of the list. for pub in pubs: if pub >= n: f...
import argparse import sys import time import numpy import paramiko args = None class bcolors: HEADER = "\033[95m" OKBLUE = "\033[94m" OKGREEN = "\033[92m" WARNING = "\033[93m" FAIL = "\033[91m" ENDC = "\033[0m" BOLD = "\033[1m" UNDERLINE = "\033[4m" def get_args(): parser = ar...
def count(num): cnt = 0 print '{0:b}'.format(num) while num: cnt +=1 num = num & (num-1) return cnt print count(15)
import sys import temp #import的时候 __name__ = temp from PyQt5.QtWidgets import QApplication, QWidget,QToolTip,QLabel,QLineEdit,QPushButton,QCheckBox,QProgressBar,QComboBox,QTextEdit from PyQt5.QtGui import QFont, QIcon, QPixmap class Example(QWidget): def __init__(self): super().__init__() self.initU...
import nltk #nltk.download('maxent_ne_chunker') #nltk.download('words') #This program categorize the word phrase into "Person", "Organization", etc. paragraph = "The Taj Mahal was built by Emperor Shah Jahan" words = nltk.word_tokenize(paragraph) tagged_words = nltk.pos_tag(words) namedEnt = nltk.ne_chunk(tagged...
# Data Preprocessing Template # Importing the libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split dataSet = pd.read_csv("Salary_Data.csv") X = dataSet.iloc[:,0:1].values # Strain Data in 2d araay y = dataSet.iloc[:,1].values # 1D ar...
from django.contrib import admin from examination.models import Examination admin.site.register(Examination)
from lib.models.tag import Tag import unittest class TestTag(unittest.TestCase): def test_constructorParsesDictionary(self): # Arrange name = 'testCard' tagId = '123' organizationId = '012' color = 'green' dictionary = {'name': name, 'tagId': tagId, 'color'...
#!/usr/bin/env python3 """test drivers""" import os import platform import re import shutil import sys import time import traceback from pathlib import Path from allure_commons._allure import attach from allure_commons.model2 import Status, StatusDetails from arangodb.installers import create_config_installer_set, Ru...
import numpy as np import random class RandomPlayerPositionGenerator: def __init__(self, seed = -1): self.seed = seed random.seed(self.seed) def get_position(self, field, player_radius): return np.array([random.uniform(-field.length / 2 + player_radius, 0), random.uni...
# O mesmo professor do desafio anterior quer sortear a ordem #de apresentação do trabalho dos alunos. Faça um programa que #leia o nome dos quatro alunos e mostre a ordem sorteada import random from random import shuffle print('Bem vindo ao gerador de Listas Randômicas 1.0.') a1 = str(input('Digite o nome do segundo...
import ROOT,math,sys import math from array import array dataEvts=221 numBkgEvts=210 points=500 scale=1.2 errorEvts=20 x=[];y=[];xMinus=[]; xPlus=[];x2Minus=[]; x2Plus=[];x3Minus=[]; x3Plus=[]; xerrorpos=[]; xerrorneg=[]; x2errorpos=[]; x2errorneg=[]; x3errorpos=[]; x3errorneg=[] for i in range(0,points): numEvts = ...
#!/usr/bin/env python3 import os.path import sys try: project_root = os.path.dirname(__file__) sys.path.insert(0, project_root) except Exception: project_root = None from py2many.cli import main if __name__ == "__main__": main()
import pandas as pd import numpy as np import matplotlib.pyplot as plt # df = pd.DataFrame(np.random.rand(6,4), # index=['one', 'two', 'three', 'four', 'five', 'six'], # columns=pd.Index(['A', 'B', 'C', 'D'], name='Genus')) # df.plot(kind='bar') indexs = ['17-AAG', 'AEW541', 'AZD05...
#! /usr/bin/python # Multi-word anagram solver specifically optimized for the # Dinosaur Comics puzzle from 2010-03-01: # http://www.qwantz.com/index.php?comic=1663 # # Usage: # multianagram.py <guess> # where "guess" is any sequence of words, separated by # spaces. The program will attempt to fill out the rest o...
import numpy as np import math # The function takes two dimension inputs for the filter image; # the third filter is D0, which defines the circle area of the High Pass Filter; def highGaussian(M, N, D0): # Initializing the filter with ones; since the filter is a complex function, # it has two channels, ...
'''def palidrom(n): num=n d=0 rev=0 while n>0: d=n%10 n=int(n/10) rev=rev*10+d if(num==rev): return True else: return False x=int(input('enter the no')) if palidrom(x): print(x,'palidrom') else: print(x,'not palidrom') ''' # function which re...
import os import glob from argparse import ArgumentParser import pandas as pd import numpy as np import utils def arguments(): parser = ArgumentParser() parser.add_argument( "--dir", "-d", type=str, help="Path to the directory containing the CSV files to ensemble", ) pa...
from django import forms from .models import Question from .models import Answer from users.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm class QuestionForm(forms.ModelForm): class Meta: model = Question fields = [ 'question_title', ...
from django.views import generic from .models import Post, Comment from .forms import CommentForm from django.http import HttpResponseRedirect from django.urls import reverse from django.contrib import messages from django.shortcuts import render class IndexView(generic.ListView): template_name = 'home.html' c...
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface import hashlib from datetime import datetime from itemadapter import ItemAdapter ...
# # file: goldjunge.py # # coder: moenk # # purpose: simple backtest with expert advisor for strategies like golden cross and death cross # # using: stockstats for trading KPI # import pandas as pd from pandas.plotting import register_matplotlib_converters from stockstats import StockDataFrame import matplotli...
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter import matplotlib.ticker as mtick import os.path import scipy.interpolate import sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') import common_plotting import matplotlib.gridsp...
# import modules import requests # Request headers set Subscription key which provides access to this API. Found in your Cognitive Services accounts. headers = { 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': '6b83d43d62544a8a90b837b8be390a87', } body = dict() body["url"] = "http:/...
#!usr/bin/perl # DAXxXTER MD5 Cracker v1.2 # coded by : rio suyanto # rio_suyanto00@yahoo.co.id system('cls'); system( 'title DAXxXTER MD5 Cracker v1.2'); use strict; use warnings; use Digest::MD5 qw(md5_hex); sub usage(){ print <<EOF; ----------------------------------------- | DAXxXTER MD5 Cracker v1.8 ...
from sklearn import tree, preprocessing import graphviz import numpy as np X = np.array([ ['Home', 'Out', '1-NBC'], ['Home', 'In', '1-NBC'], ['Away', 'Out', '2-ESPN'], ['Away', 'Out', '3-FOX'], ['Home', 'Out', '1-NBC'], ['Away', 'Out', '4-ABC'], ]) Y = np.array([ 'Win', 'Lose', 'Wi...
# -*- coding: utf8 -*- from urllib import request import http.cookiejar url = 'http://www.baidu.com' print('---------------------') print('The First Method:') response1 = request.urlopen(url) print(response1.getcode()) print() print(len(response1.read())) print('---------------------') print('The Second Method:') ...
""" The Element class is a simple structure that takes to parameters name and value and initializes its attributes self.name and self.value with those parameters. This class was created exclusively for the Heap class to insert and delete elements by comparing the attribute value When this class is used in the functio...
import fishing_report.fishing_report from fishing_report.weather import weather import json with open('conf/fish_report.conf', 'r') as f: config = json.load(f) coords = config['coords'] weather = weather(coords) print(weather.tonightweather)
from datetime import timedelta, datetime, time from tc2.stock_analysis.AbstractForgetfulModel import AbstractForgetfulModel from tc2.stock_analysis.ModelWeightingSystem import SymbolGrade, SymbolGradeValue from tc2.data.data_structs.price_data.SymbolDay import SymbolDay from tc2.data.data_structs.price_data.Candle imp...
import pymysql.cursors from db_connection import DBConnection import json import pandas as pd import itertools from collections import defaultdict class BusinessFeatureAnalysis: def __init__(self,code): self.code=code def queryData(self): connection=DBConnection.getConnection() try: ...
from tkinter import* root=Tk() root.title("Simple calc") #Setup Display: Display=Entry(root,width=35,borderwidth=5) Display.grid(row=0,column=0,columnspan=3,padx=10,pady=10) try: #Setup function: def clic_me(number): current=Display.get() Display.delete(0,END) Display.insert(0,str(current)+...
import numpy as np import operator import os def createDataSet(): group = np.array([[1.0,1.1],[1.,1.],[0.,0.],[0.,0.1]]) labels = ['A','A','B','B'] return group,labels def classify0(inx,dataset,labels,k): datasize = dataset.shape[0] diff = np.tile(inx,(datasize,1)) - dataset sum = np.sum(np.squ...
import datetime from App.exts import db from App.models import BaseModel class MovieCollect(BaseModel): __tablename__ = 'moviecollect' movie_id = db.Column(db.Integer, db.ForeignKey('movie.id')) # 所属电影,在movie表中创建关联 user_id = db.Column(db.Integer, db.ForeignKey('user.id')) # 所属用户,在user表中创建外键关联 add_t...
def stringify(obj): return "!-!-" + str(obj) + "-!-!" def simplify(some_str): return some_str.replace("!", "")[:12] def white_begone(some_str): return some_str.trim().replace(" ", "").replace("\t", "") def indexify(some_str, index): result = stringify(index) + some_str result = simplify(result) ...
import flask from . import db_session from .posts import Post from .comments import Comment blueprint = flask.Blueprint( 'post_api', __name__, template_folder='templates' ) @blueprint.route('/api/posts') def get_news(): db_sess = db_session.create_session() posts = db_sess.query(Post).all() ...
from django.conf.urls import include, url from django.contrib import admin from accounts import views urlpatterns = [ url(r'^chat/', include('chat.urls')), url(r'^admin/', admin.site.urls), url(r'^accounts/', include('accounts.urls')), url(r'^logout/$', views.user_logout, name='logout'), url(r'^$',...
# MIP written by GAMS Convert at 12/13/18 10:24:48 # # Equation counts # Total E G L N X C B # 43 17 0 26 0 0 0 0 # # Variable counts # x b i s1s s2s sc ...
#extract Id & UserId from Comments XML and filter out rows that don't have an UserId def extract_filter_comments(comment_root): ''' Extract the necessary fields and filter any duplicate row or row having missing fields for Comments XML file in a domain :param comment_root: :return List of rows eac...
''' This lambda function serves request from Amazon API Gateway to get all posts from Amazon DynamoDB ''' import json import boto3 import os def list_data(): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(os.getenv("DYNAMODB_TABLE")) response = table.scan() posts = [] for item in re...
from airflow.hooks.postgres_hook import PostgresHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class LoadFactOperator(BaseOperator): ui_color = '#F98866' log_entry = "[LoadFact]" insert_sql = """ INSERT INTO {} {}; COMMIT; """ ...
import json dict ='{"name": "David", "age": 6, "class": "I"}' list ='["Red", "Green", "Black"]' string ='"Python Json"' int ='1234' float ='21.34' a=json.loads(dict) b=json.loads(list) c=json.loads(string) d=json.loads(int) e=json.loads(float) print(a) print(b) print(c) print(d) print(e) print(type(a))