text
stringlengths
38
1.54M
#coding: utf-8 # Inverte Dicionário # (C) 2016, Yovany Cunha/UFCG, Programaçao I def insere_ordenado(elem,lista_elem): for i_elem in range(len(lista_elem)): if lista_elem[i_elem] > elem: lista_elem.insert(i_elem,elem) return def inverte_dicionario(dic): invertido = {} for i...
# Solution of; # Project Euler Problem 392: Enmeshed unit circle # https://projecteuler.net/problem=392 # # A rectilinear grid is an orthogonal grid where the spacing between the # gridlines does not have to be equidistant. An example of such grid is # logarithmic graph paper. Consider rectilinear grids in the Carte...
#!/usr/bin/python # Add iRules to virtual server # Author: apined12@its.jnj.com # Name: jnj_f5_addnewrule if __name__ == "__main__": import bigsuds import getpass from jinja2 import Environment, FileSystemLoader import yaml import sys import jnjf5tools print "Enter device credentials\n...
import unittest from webtool import app from twilio.rest import Client from SensitiveData import * class LuckyShoeTestCase(unittest.TestCase): def setUp(self): app.config["TESTING"] = True def tearDown(self): pass def test_lucky_shoe_page(self): tester = app.test_client(self) ...
#!/usr/bin/python3 import math import numpy as np import matplotlib.pyplot as plot def train_model(degree, x, y): model_parameters = np.polyfit(x, y, degree) return model_parameters[::-1] def predict_value(model_parameters, x): polynome = map(lambda i: model_parameters[i] * x**i, range(len(model_parame...
# Accessing elements within a tuple my_tuple = ("J", 'a', 'v', 'a', 's', 'c', 'r', 'i', 'p', 't') # We need to use index numbers to access elements print(my_tuple[0]) print(my_tuple[-1]) # Tuples are IMMUTABLE, they can't be changed # Lists are MUTABLE, they can be changed # Once you create a tuple, you can't change...
from unittest import TestCase from seqs.MinimumSpanningTree import MinimumSpanningTree class MSTTest(TestCase): def test_MST(self): """Check that MinimumSpanningTree returns the correct answer.""" G = { 0: {1: 11, 2: 13, 3: 12}, 1: {0: 11, 3: 14}, 2: {0: 13, 3:...
# -*- coding: utf-8 -*- # 如果我们已经把原始图片做成了一个列表清单(txt文件,一行一张图片),则可以不用LMDB格式作为输入数据,可以用ImageData作为数据源输入 from caffe import layers as L, params as P, to_proto path = './data/' train_list = path + 'train.txt' val_list = path + 'val.txt' train_proto = path + 'train.prototxt' val_proto = path + 'val.prototxt' def create...
from flask import Flask, request from flask_cors import CORS, cross_origin #pip install -U flask-cors app = Flask(__name__) cors = CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' @app.route('/candidato/inserir', methods=['POST']) def inserirCandidato(): print(request.data) return { 'message': 'Can...
''' Created on 11 fvr. 2016 @author: emmanuelcharon ''' import math from reader import Reader, Warehouse, Order, Load, Deliver, readFile def dist(r1, c1, r2, c2): d = math.sqrt((r1-r2)*(r1-r2) + (c1-c2)*(c1-c2)) return math.ceil(d) class Drone(object): def __init__(self, reader, ID): self.R = reader.WAREHO...
from django.urls import path from . import views urlpatterns = [ # localhost: 8000/trip -> views.dashboard path('', views.dashboard), # localhost: 8000/trip/new - views.new path('new', views.new), # localhost: 8000/trip/create path('create', views.create), #localhost: 8000/trip/<trip_id>/e...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
from vae_celebA.image_utils.face_aligner_2 import FaceAligner2 from vae_celebA.image_utils.video_camera import VideoCamera from vae_celebA.peters_extensions.attention_window import AttentionWindow import cv2 if __name__ == '__main__': FAST = False # windower = AttentionWindow(window_size=(200, 200), decay_rat...
from contextlib import closing from sklearn.feature_extraction import text from sklearn import decomposition from sklearn.preprocessing import normalize from language_cleaning import LCleaner import sys, codecs, pickle, time, resource def main(): tot_time1 = time.time() cleaner = LCleaner() titles = [] ...
#!/usr/bin/env python3 from collections import deque def flip(stack): return ''.join(['+' if c == '-' else '-' for c in stack[::-1]]) def is_all_happy(stack): return list(stack).count('+') == len(stack) def num_flips(stack): if is_all_happy(stack): return 0 flip_queues = deque() flip_...
from helpers.AoCHelper import * inputlines = read_input_lines('day8/day8input1.txt') def alter_program(index, program): new_program = [x for x in program] operation = program[index] if operation[0:3] == 'jmp': new_program[index] = operation.replace('jmp', 'nop') elif operation[0:3] == 'nop':...
import socket, threading #recebe mensagens enviadas pelo servidor e mostra elas ao usuário def mensagens(conexao: socket.socket): while True: try: msg = conexao.recv(1024) # caso há mensagem tentará decodificar a mensagem para mostrar ao usuário if msg: ...
def legrava1(): #este modulo é pra criar o arquivo 1 mestre print('{:*^30}'.format('Cadastro de alunos')) try: arq1=open('arq1.txt','r') ar1=arq1.readlines() #lê o arquivo para a lista ar1 arq1.close() except: ar1=[] #se o arquivo não existir, cria-se uma lista va...
from selenium import webdriver import time import xlsxwriter url='http://www.omniagmd.com/exhibitordirectory/arab-health' driver =webdriver.Firefox() driver.get(url) workbook = xlsxwriter.Workbook('demo.xlsx') worksheet = workbook.add_worksheet() list=[] c=1 while(c<=288): for a in driver.find...
# -*- coding: utf-8 -*- """ Created on Sun Apr 19 21:23:31 2020 @author: bejin """ import logging import threading import time import numpy as np df = np.random.rand(16384, 4) start = time.time() df1 = df.copy() duration = time.time() - start print(duration) data = [1] flag_st = False def rt_data(): while d...
from flask import render_template from app import app @app.route('/') @app.route('/index') def index(): # user = {'usrername' : 'lyana'} return render_template('index.html') @app.route('/snoop') def snoop(): return render_template('snoop.html') @app.route('/about') def about(): return render_template('about.ht...
from sixerrapp import views from django.urls import path urlpatterns = [ path('', views.home, name='home'), path('gigs/<int:id>/', views.gig_detail, name='gig_detail'), ]
from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtUiTools import * from PySide2.QtWidgets import * from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib import...
#!/usr/local/bin/python from parse_cordis import project_xml import sys import json if len(sys.argv) < 2: print "Usage: parse_cordis <RCN>" print " Example: parse_cordis 105875" print " Example: parse_cordis parse_cordis/tests/project.xml" print " Returns project information for the SyStemAge project from the ...
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ from odoo.exceptions import UserError class DishonourCheque(models.TransientModel): _name = "dishonour.cheque" present_date = fields.Date(string='Cheque Present Date', default=fields.Date.context_today, required=True) date_return = fields.D...
def hanoi(n,i,k): if(n==1): print("Move disk 1 from pin",i ,"to",k, sep=" ") else: tmp=6-i-k hanoi(n-1,i,tmp) print("Move disk",n,"from pin",i,"to",k, sep=" ") hanoi(n-1,tmp,k) hanoi(3,1,2)
#!/usr/bin/env python class Host(object): def __init__(self, ip = [], hostname = "", services = {}): self.ip = ip self.hostname = hostname self.services = services def getIp(self): return self.ip def setIp(self,ip): self.ip = ip def getHostname(self): return self.hostname def setHostname(self,hos...
#!/usr/bin/python2 # import scipy.io # d = scipy.io.loadmat('./emnist-balanced.mat') # print len(d) # print d['dataset'][0][0][0] # print d['dataset'][0][0].shape # import sys # sys.exit() import numpy as np import dataset as emnist import keras from keras.datasets import mnist from keras.models import Sequential fro...
''' M. Steven Towns 10/12/16 Homework 3 THIS MUST BE RUN WITH PYTHON 3 ''' class Deque: def __init__(self): self.items=[] def isEmpty(self): return self.items==[] def addFront(self,item): self.items.append(item) def addRear(self,item): self.items.insert(0,item) def removeFront(self): return self.items...
#!/usr/bin/env python3 import requests import os import json import time def auth(): """Obtain bearer token from OS environment. Once you have your bearer token, add it as an environment variable by typing `export 'BEARER_TOKEN'='<your_bearer_token>'` in the terminal. """ bearer_token = os.envi...
# Copyright 2020 Xilinx Inc. # # 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, ...
# coding: utf-8 from the_tale.common.utils.exceptions import TheTaleError class BillError(TheTaleError): pass class UnknownLastEventTextError(BillError): MSG = 'unknown last event text for bill %(bill_id)d' class ApplyBillInWrongStateError(BillError): MSG = 'trying to apply bill %(bill_id)d not in voting st...
import logging as log from typing import List from shared.int_code_computers.operations import Operation, OperationFactory from shared.int_code_computers.state import State class Program: logger = log.getLogger('Program') op_factory = OperationFactory() # Instance mappings state: State def __ini...
#!/usr/bin/python3 """ Basic WebApplication """ from flask import Flask from flask import render_template from models import storage from models.state import State from models.amenity import Amenity from models.place import Place from models.user import User import uuid app = Flask(__name__) @app.teardown_appco...
# -*- coding: utf-8 -*- from EXOSIMS.Prototypes.OpticalSystem import OpticalSystem import astropy.units as u import numpy as np import scipy.stats as st import os import astropy.io.fits as fits class KasdinBraems(OpticalSystem): """KasdinBraems Optical System class This class contains all variabl...
#!/usr/bin/env python # -*- coding: utf-8 -*-s from Prototipo.Schedulers.queues import * from Prototipo.Schedulers.scheduler import Scheduler class SchedulerPriorityPreemptive(Scheduler): # Se inicializa con un map donde las claves son las prioridades, y los valores es una queue, # el pcbTable, el agi...
#!/usr/bin/env python """ status.py - Phenny spacestatus module Author: Ward De Ridder """ import urllib2 import json def SpaceapiOpen(apiURL): u = urllib2.urlopen(apiURL) jsonSpaceAPI = json.load(u) u.close() spacestatus = "" return jsonSpaceAPI['state']['open'] def status(phenny, input): if S...
#coding by Dhamydau# from flask import Flask ,render_template ,g from mocks import Post from datetime import datetime import sqlite3 from flask import request from flask import redirect from flask import url_for,flash from flask_wtf import FlaskForm from wtforms import SelectField from flask_sqlalchemy import SQLAlch...
import re batRegex = re.compile(r'Bat(wo)?man') mo = batRegex.search("The Adventures of Batman") print(mo.group()) # returns 'Batman' mo = batRegex.search('The Adventures of Batwoman') print(mo.group()) # returns 'Batwoman' mo = batRegex.search('The Adventures of Batwowowoman') # print(mo.group()) # returns None ph...
class Solution: def longestPalindromeSubstring(self, s): """ :type s: str :rtype: str """ # 最长回文子串,要求子串连续,返回子串 # bbbab 返回bbb(bab) # 1. dp定义 # 定义dp[i][j]记录子串子串s[i:j+1]是否为回文子串 n = len(s) dp = [[0 for j in range(n)] for i in range(n)] ...
age = int(input('Enter the age: ')) if age < 1: print('You are a baby') elif not age < 1 and age < 13: print('You are a child') elif not 13 > age and age < 20: print('You are a teenager') else: print('You are an adult')
#*****************************************************************************************# # Class Name : Oscillator # # Class Description : Model of a Matsuoka Oscillator. # # Contains two different...
# https://leetcode.com/problems/split-array-with-same-average/ class Solution: def check_split(self, listed, sums, start, end, checked, other_sum, length, working_sum, working_length): temp = 10000000 if len(listed) <= 20 else 100 if (working_length, (sums[end] - sums[start - 1] + wor...
from django.shortcuts import render, redirect from django.conf import settings # Create your views here. def index(request): if not request.user.is_authenticated(): return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) context = {} return render(request, 'index.html', context)
import numpy as np print("Input the names of all the nodes : ") titles = [input("enter name {} : ".format(i + 1)) for i in range(int(input("no. of nodes : ")))] n = len(titles) graph_dict = {} for i in titles: graph_dict[i] = list(map(int, input("outlinks from {} : ".format(i)).split())) graph = np.array([graph_d...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Nov 14 13:17:32 2018 @author: tabor """ from thesaurus import Word import numpy as np from multiprocessing import Pool import pickle part = ['adj','adv','contraction','conj','determiner', 'interj','noun','prefix','prep','pron','verb', ...
# -*- coding: utf-8 -*- import os import csv import xlrd from xlutils.copy import copy; import time import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns #factory import random import simpy import time from functools import partial, wraps #sim_index import re fr...
""" This file contains the logic where we generate the individual weights. The weights are the weights used for the linear connections between individual blocks in the RNN cell """ import collections from torch import nn def generate_weights(input_size, hidden_size, num_blocks): """ This numbe...
from settings import WINDOW_WIDTH, WINDOW_HEIGHT from game.physicalobjects import InertialObject from game import resources from mock import MagicMock def test_InertialObject_init__motionless(): sut = InertialObject(img=resources.player_image) assert sut.velocity_x == 0.0 assert sut.velocity_y == 0.0 ...
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: flat_list=[] for row in matrix: for col in row: flat_list.append(col) def bs(nums, target, begin, end): chosed=(begin+end)//2 ...
import re from typing import Tuple import pytest from antlr4 import InputStream from graphviz import Digraph from wrappers import ParseTreeWrapper @pytest.fixture(scope="function", params=[ ('connect "/home/user/db";', 8), ('connect "/home/user/db" ', None), ('production var(S) to term(a);', 17), ('...
#Use a for loop to loop over the array. Print every name individually. arr = ["Aous", "Farzona", "Naznin", "Ibrahim", "Nouri"] for x in arr: print(x)
# Generated by Django 2.0 on 2018-10-19 13:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('backend', '0005_auto_20181019_1113'), ] operations = [ migrations.AlterField( model_name='bouton', name='id_action', ...
#coding:utf8 ''' Created on 2013-10-21 @author: lan (www.9miao.com) ''' from twisted.python import versions version = versions.Version('firefly', 1, 3, 3)
from django.contrib import admin from app.models import BookOverAllRating class BookOverAllRatingAdmin(admin.ModelAdmin): list_display = ('id', 'total_sum', 'total_count') list_filter = ('id', ) admin.site.register(BookOverAllRating, BookOverAllRatingAdmin)
import dlib import cv2 import numpy as np from crop import safe_crop def imresize(img, scale=None, output_wh=None): if scale is not None: h,w = img.shape[:2] output_wh = (int(w * scale), int(h * scale)) return cv2.resize(img, output_wh, interpolation=cv2.INTER_AREA) # INTER_AREA adds 10ms clas...
#!/usr/bin/python #execfile('gp_check_gaus.py') #this program determines how gaussian a group's vel dispersion and then checks #to see if it correlates w/ halo mass dispersion import random import numpy as np import matplotlib.pyplot as plt from matplotlib.mlab import griddata execfile('gp_wrapper.py') #choose which l...
from django.contrib import admin from models import * class DNSZoneAdmin(admin.ModelAdmin): search_fields = ['zonename'] admin.site.register(DNSZone, DNSZoneAdmin) class DHCPScopeAdmin(admin.ModelAdmin): search_fields = ['zonename'] admin.site.register(DHCPScope, DHCPScopeAdmin) class HostAdmin(admin.ModelAdmin...
import cv2 cap = cv2.VideoCapture(0) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) x = width // 2 y = height // 2 print("x" + str(x)) print("y" + str(y)) w = width // 4 h = height // 4 print("w" + str(w)) print("h" + str(h)) # Bottom rig...
from django.template.defaulttags import register @register.filter def rubric_css(rubric_type): return rubric_type.replace('_', '-')
def fibonacci(number): if number < 2: return number else: n_minus1 = 1 n_minus2 = 0 for x in range(1, number): result = n_minus1 + n_minus2 n_minus2 = n_minus1 n_minus1 = result return result for x in range(10): print("{} \t > ".fo...
import numba import numpy import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch import FloatTensor def onehot(indexes, N=None, ignore_index=None): """ Creates a one-representation of indexes with N possible entries if N is not specified, it will suit the maximum ...
# This module contains information about a Booking/Trip import random from .lib.pyroutelib2.models.route import Router from .lib.pyroutelib2.models.loadOsm import LoadOsm # Initializing map data MAP_DATA = LoadOsm("car") BASE_FARE = 3 MAX_SEATS = 3 RESPONSE_TIME = 60 # seconds PROCESS_TIME = 180 # seconds MAX_RAD...
# Generated by Django 2.2.7 on 2020-06-12 06:30 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('employee', '0001_initial'), ] operations = [ migrations.CreateModel( name='...
""" Module for managing setpoint shifting. DPT 6.010. """ from typing import List from xknx.remote_value import RemoteValue1Count class RemoteValueSetpointShift(RemoteValue1Count): """Abstraction for remote value of KNX DPT 6.010.""" def __init__( self, xknx, group_address=None, ...
class Rename(object): def __init__(self, record_reader, command_parts): self.command_parts = command_parts self.record_reader = record_reader def process(self): try: index = int(self.command_parts[0]) if index < 1: raise ValueError("Index must be ...
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders class SendMail: def __init__(self,sender,sender_PW,receiver): self.SERVER = 'smtp.gmail.com:587' self.SENDER_EMAIL = sender sel...
height = float(raw_input("Height in meters: ")) m3 = float(1000) grav = float(9.81) def calcPressure(h, s, g): pressure = h * s * g bar = pressure / 100000 print("%s bar") % bar calcPressure(height, m3, grav) raw_input()
#https://www.geeksforgeeks.org/find-the-two-repeating-elements-in-a-given-array/ import math def fact(n): if n == 0: return 1 else: return n * fact(n-1) def print_two_repeating_integers(arr): S = 0 P = 1 size = len(arr) n = size - 2 for i in range(size): S += arr[i]...
# -*- coding: utf-8 -*- """ Created on Mon Sep 16 10:47:30 2019 @author: BrysDom """ #Importing lib import numpy as np import matplotlib.pyplot as plt import pandas as pd #Importing dataset dataset = pd.read_csv('Ads_CTR_Optimisation.csv') #Implementing Thompson Sampling import random N=10000 d=1...
from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render, redirect from django.core.exceptions import ObjectDoesNotExist from .forms import AutorForm, LibroForm from .models import Autor, Libro from django.urls import reverse_lazy from django.views.generic import TemplateView, ListV...
""" @File :actor_critic.py @Author :JohsuaWu1997 @Date :2020/1/30 """ import torch cuda = torch.device('cuda') def hard_copy(target, source): for weight1, weight2 in zip(target, source): weight1.data = weight2.data.clone() def soft_copy(target, source, w=0.01): for weight1, weight2 in zip(targe...
#!/usr/bin/env python # coding: utf-8 # # TASK 2 # In[1]: ## Imporing all the necessary libraries import pandas as pd import warnings import spacy import en_core_web_sm warnings.filterwarnings('ignore') ## Reading the company 'descriptions.xlsx' and 'Industry Segments - Top 10 Keywords.xlsx' using pandas library ...
x, y = map(float, input().split()) if x > 0 and y > 0: print("Q1") elif x < 0 and y > 0: print ("Q2") elif x < 0 and y < 0: print ("Q3") elif x > 0 and y < 0: print("Q4") elif x == 0 and y > 0 or y < 0: print("Eixo Y") elif y == 0.0 and x > 0 or x < 0: print ("Eixo X") elif x == 0 and y == 0: ...
from sklearn.ensemble import GradientBoostingClassifier from sklearn.metrics import roc_auc_score import numpy as np from sklearn import metrics import scipy.io import time from sklearn.grid_search import GridSearchCV import scipy.io as scio def roc(test_label, predict, score): vaule = np.ones((1, 12)).ast...
#remake snake avec ecran acueil à améliorer !! import pygame import random import time from pygame.font import * import sys pygame.font.init() pygame.init() pygame.display.set_caption("test collision") largeur = 500 hauteur = 500 ecran = pygame.display.set_mode((largeur, hauteur)) #variables du player #changer icon win...
import torch import torch.nn.functional as F from torch.utils.data import DataLoader, TensorDataset from torchvision import datasets, transforms from torch.autograd import Variable from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt from chord import chordDiagram def clean_loader_cifar(args)...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 1 14:43:40 2018 @author: loey """ import time import re import sys import csv csv.field_size_limit(sys.maxsize) from nltk.tokenize import RegexpTokenizer filenames = dict() tokenizer = RegexpTokenizer(r'\w+') def main(): start_time = time.ti...
# -*- coding:utf-8 -*- import sys import os print("-" * 33) # abs path print(__file__) print(sys.argv[0]) # relative path print(os.path.basename(__file__)) print(os.path.basename(sys.argv[0]))
''' Created on Dec 27, 2012 @author: dough ''' from source import Source, IncompatibleRecorderError class DVBTSource(Source): def __init__(self, name, dvb_frequency=None, program=None): super( DVBTSource, self).__init__(name) self._dvb_frequency = dvb_frequency self._progra...
from bs4 import BeautifulSoup import re html_doc = "E:\\VS-Code-C\\CODES\\PY-codes\\zhihu\\爬虫\\bs4.html" html_file = open(html_doc, "r") html_handle = html_file.read() soup = BeautifulSoup(html_handle, "html.parser") # 1. 获取html文档头 print(soup.head) # 2. 获取某一个节点 print(soup.p) # 3. 获取节点中的属性 print(soup.p.attrs) # 4. 获...
# Copyright (C) 2015-2022 Virgil Security, Inc. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # (1) Redistributions of source code must retain the above copyright # notice, this li...
import numpy as np import scipy.optimize as opt import time # Settings L = 1.0 N = 64 # TODO dx = L / (N + 1) def Error(phi_result, lo, dx): error = 0.0 for i in range(1, phi_result.shape[0] - 1): for j in range(1, phi_result.shape[1] - 1): residual = dx**-2 * (phi_result[i + 1, j] + p...
from flask import Flask, render_template , request app = Flask(__name__) foods = [ { "title" : "bún riêu", "description" : "rất ngon", "link" : "https://www.hoidaubepaau.com/wp-content/uploads/2018/08/bun-rieu-cua-dong-mien-bac.jpg", "type" : "eat" }, { "title" : "bú...
import scrapy from scrapy import Request import json class meeylanSpider(scrapy.Spider): name = "hochiminh" url = 'https://api.meeyland.com/api/search' headers = { 'authority': 'api.meeyland.com', 'pragma': 'no-cache', 'cache-control': 'no-cache', 'accept': 'app...
from bs4 import BeautifulSoup import urllib.request import psycopg2 import time #-------------------------------------------------------------------------- author = "" name = "" price = 0 nWebsites = 0 bookbinding = "" editorial = "" language = "" ISBN = 0 book = [] #-------------------------------------------------...
import tensorflow as tf class CNN(tf.keras.Model): def __init__(self): super().__init__() self.conv1 = tf.keras.layers.Conv2D( filters = 32, kernel_size=[5,5], padding='same', activation=tf.nn.relu ) self.pool1 = tf.keras.layers.MaxPoo...
from facial_recognizer import facial_recognizer from video_camera import video_camera if __name__ == "__main__": face_decection = facial_recognizer("input/classifiers/haarcascade_frontalface_default.xml", "input/svm_training_photos", "input/svm_training_photos_cleaned") video_camera = video_camera("output/saved_vid...
# Find the Median ####################################################################################################################### # # In the Quicksort challenges, you sorted an entire array. Sometimes, you just need specific information about a # list of numbers, and doing a full sort would be unnecessary....
from random import * print(random()) # Random float: 0.0 <= x < 1.0 print(uniform(2.5, 10.0)) # Random float: 2.5 <= x < 10.0 print(expovariate(1 / 5)) # Interval between arrivals averaging 5 seconds print(randrange(10)) # Integer ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import googlemaps import six bool_to_str = lambda x: 'true' if x else 'false' class MapPath(object): points = [] weight = None color = None fillcolor = None geodesic = False error_msgs = { 'invalid_points_type': "Invali...
# coding=utf-8 from __future__ import absolute_import, division, print_function, unicode_literals import os from collections import namedtuple from copy import deepcopy from types import FunctionType from ..animations import bars, spinners from ..styles.internal import BARS, SPINNERS, THEMES def _style_input_factor...
from flask import Blueprint from app.ride.api import RideAPI ride_app = Blueprint('ride_app', __name__) ride_view = RideAPI.as_view('ride_api') ride_app.add_url_rule('/api/v1/rides/', defaults={'r_id': None}, view_func=ride_view, methods=['GET',]) ride_app.add_url_rule('/api/v1/rides/', view_func=ri...
# If else block if False: print("1") print("2") else: print("3") print("4") print("6")
from Start_up import* class Stopper(pygame.sprite.Sprite): def __init__(self, pos, kill_e, kill_b): # kill_e = Kill enemies (True or false) # kill_b = Kill bullets self.surface = pygame.Surface((10, height)) self.rect = self.surface.get_rect() self.rect.x = pos[0] s...
import csv import sys import django import psycopg2 from django.conf import settings from pathlib import Path root_directory = str(Path(__file__).resolve().parents[1]) sys.path.append(root_directory) from statistik.constants import IIDX from statistik.models import Song with open('misc/music.csv', encoding='utf-8') ...
# -*- coding: UTF-8 -*- import cv2 import os import numpy as np #输入成绩书封面图片路径,返回零件号大概区域的截图 def detectTable(imgpath): img = cv2.imread(imgpath) #由于opencv不支持读取中文路径,用以下方法代替cv2.imread img = cv2.imdecode(np.fromfile(imgpath, dtype=np.uint8), 1) #图片先转成灰度的 gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ...
#!/usr/bin/env python3 from sense_hat import SenseHat def main(): sense = SenseHat # sense.set_imu_config() print("hello world") if __name__ == "__main__": main()
""" 8. Ingresar nombres , luego buscar un nombre y de encontrarlo decir en qué posición está. """ def insertNames(): names = [] confirm = input('Do you like to input a name? y/n ') while confirm == 'y': names.append(input("What's the name? ")) confirm = input('Do you like to input another ...
# Name: Inzamam Kaleem Rahaman # Date: 27th February 2017 # File description: command line application for the generation of csv files # containing the data contained in the supplied NAMDEVCO xls files import argparse import glob import os from pyexcel_xls import get_data from datetime import dateti...