text
stringlengths
38
1.54M
import pytest import json from unittest.mock import Mock, call from app.libs.redis_cache import RedisCacheException from app.libs.api import CachedApi MOCK_URL = 'https://host' RESPONSE_CATEGORY1 = '{"categoryId": 1, "title": "Category1 title"}' RESPONSE_CATEGORY2 = '{"categoryId": 2, "title": "Category2 title"}' RES...
from __future__ import print_function from builtins import range import os import sys import time import json #from PIL import Image # set env var needed by native library os.environ["MALMO_XSD_PATH"] = os.getcwd() + "/schemas" import MalmoPython class Malmo(): def __init__(self): init() self.ah ...
a = int(input("numero1: ")) a1 = int(input("numero2: ")) t = 0 b = 1 d = 0 while (a>0) and (b<a): if (a%b == 0): d = b + d b = b + 1 t = t + 1 else: b = b + 1 t1 = 0 b1 = 1 d1 = 0 while (a1>0) and (b1<a1): if (a1%b1 == 0): d1 = b1 + d1 b1 = b1 + 1 t1 = t1 + 1 else: b1 = b1 + 1 print(d) print(d1) if ...
# Generated by Django 2.0.5 on 2018-09-03 11:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('AmadoAccounting', '0032_salarydetail_description'), ] operations = [ migrations.AddField( model_name='salarydetail', ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from conans import ConanFile, tools, AutoToolsBuildEnvironment from conans.errors import ConanInvalidConfiguration import os import glob class LibiconvConan(ConanFile): name = "libiconv" version = "1.15" description = "Convert text to and from Unicode" ur...
import sys, time, math if sys.version[0] == '2': raw_input("This client only works with python 3, and you're using python 2. You can download python 3 from python.org.\nPress enter to exit.") quit() from tppflush import * if len(sys.argv) < 2: input("To run this client, please supply an IP address from the comman...
import face_recognition import cv2 import numpy as np import time # เปิดการใช้ webcam video_capture = cv2.VideoCapture(0) frame_size = (int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))) print(frame_size) print(cv2.CAP_PROP_FPS) prevT...
from selenium.webdriver.common.by import By class MainPageLocators(): LOGIN_LINK = (By.CSS_SELECTOR, "#login_link") class LoginPageLocators(): # локаторы для формы логина LOGIN_FORM = (By.CSS_SELECTOR, "#login_form") EMAIL_INPUT = (By.CSS_SELECTOR, "#id_login-username") PASSWORD_INPUT = (By.CSS_SE...
""" operators = {"addition":"1","subtraction:":"2","Multiplication":"3","Division":"4"} print("Please select which operation do you want to do in Maths:",operators) selection = input("select operation which you wanted to do:") num1 = int(input("Enter first number:")) num2 = int(input("enter second number:")) if selec...
import os import numpy as np foldpath = "./data" class analysis(): def __init__(self,filename): self.datapath = os.path.join(foldpath,filename) self.data = self.readData() self.aver = self.averge() self.subAver = self.subAv() self.cov = self.coveriable() self.feaVec = self.convFeaVec() self.feaVects = s...
# Sinnvoller Gebrauch von Whitespace i = i + 1 submitted += 1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b) # Aber so nicht: i=i+1 submitted+=1 x = x*2-1 hypot2 = x* x + y *y c = (a + b)* (a - b)
import cv2 import numpy as np def create_blank(width, height, color=(0, 0, 0)): """Create new image(numpy array) filled with certain color in BGR""" image = np.zeros((height, width, 3), np.uint8) # Fill image with color image[:] = color return image def draw_half_circle_rounded(image...
from django.utils import autoreload from django.core.management.base import BaseCommand, CommandError from optparse import make_option import re address_port_re = re.compile(r"""^(?: (?P<address> (?P<ipv4>\d{1,3}(?:\.\d{1,3}){3}) | # IPv4 address (?P<ipv6>\[[a-fA-F0-9:]+\]) | # IPv6 addre...
# version 2 # client # REST API: # dbs: CRUD # tables: CRUD # /dbs/<db_name> # /dbs/<db_name>/tables/<db_name> # server # build query with input from API call # >> projection, table, op, conditions # if with_conds: # query = f'query {projection} ...' #...
from typing import Dict from helpscout.endpoints.endpoint import Endpoint class User(Endpoint): """User endpoint.""" def list(self, **kwargs) -> Dict: """Get all users. Doc page: https://developer.helpscout.com/mailbox-api/endpoints/users/list/ """ response = self.base_get_r...
from googleapiclient.discovery import build from pprint import pprint # CLIENT_SECRET_FILE = 'client' API_KEY = "AIzaSyDLHZt0LlS4ZybFCJKZOnJSoPJQJlRRg28" API_NAME = 'youtube' API_VERSION = 'v3' SCOPES = ['https://www.googleapis.com/auth/youtube'] # service = Create_Service(CLIENT_SECRET_FILE, )
str1 = 'aa' str2 = 'bb' list1 = [1, 2] list2 = [10, 20] t1 = (1, 2) t2 = (10, 20) dict1 = {'name': 'Python'} dict2 = {'age': 30} # +: 合并 print(str1 + str2) print(list1 + list2) print(t1 + t2) # print(dict1 + dict2) # 报错:字典不支持合并运算
import tensorflow as tf import numpy as np sess = tf.Session() inputs =[ [[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]], [[5, 5, 5], [6, 6, 6]] ] print (inputs[0]) print (inputs[1]) print (inputs[2]) print ('\n') print (sess.run(tf.slice(inputs, begin=[1, 0, 0], size=[1, 1...
from mongoengine import * import datetime from .models import * import datetime import re def create_group(user_list, group_name): grps = WorkGroup.objects(name=group_name) if len(grps) > 0: raise ValueError("Group name '{}' has been used!") new_grp = WorkGroup(name=group_name, members=user_list) new_grp...
import hashlib import logging import os import re from utils import make_soup from time import sleep from datetime import datetime from scrapers.base_scraper import OddScraper ranking_regex = re.compile('\(#\d+\)') #regex to remove rankings in the team names logging.basicConfig(level="INFO") class InteropScraper(Od...
#!/usr/bin/python3 ########################################################################## # Postgres Partition maintenance Script for native partitioning in PostgreSQL version = 3.2 # Author : Jobin Augustine ########################################################################## import sys,datetime,argparse,p...
from django.conf.urls import url from inicio import views urlpatterns = [ url(r'^$', views.ViewHome.as_view(), name='home'), url(r'^about/$', views.ViewAbout.as_view(), name='about'), url(r'^galery/$', views.ViewGalery.as_view(), name='gallery'), url(r'^info/$', views.ViewInfo.as_view(), name='info'),...
# %timeit magic # import random # %timeit rolls_list = [random.randrange(1, 7)for i in range(0, 6_000_000)]
from display import handleDrawing def bucketSort(array, *args): bucket = [] for i in range(len(array)): bucket.append([]) n = len(bucket) for j in array: index_b = int(j/n) bucket[index_b].append(j) handleDrawing(array, j, -1, index_b, -1) for i ...
import matplotlib.pyplot as plt print(plt.style.available) values = range(1,6) squares = [x**2 for x in range(1,6)] plt.style.use('seaborn-dark-palette') fig, ax = plt.subplots() ax.plot(values,squares,linewidth=3) ax.set_title("Kwadraty",fontsize=20) ax.set_xlabel('Wartosć',fontsize=14) ax.set_ylabel('Wartość do k...
from __future__ import unicode_literals from django.apps import AppConfig class UploadtocloudConfig(AppConfig): name = 'uploadtocloud'
from room import Room from player import Player from item import Item import os # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons"), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north ...
# -*- coding: utf-8 -*- from Candy import * from Level import * from Map import * from Score import * from Snake import * class GameWorld(object): """ GameWorld The game world """ def __init__(self, sense): """ Initialize the game world :param sense The ...
import sys import Pyro4 import os import hashlib #list_workers= ['PYRO:obj_407b5d663ba94cdc974651d5433b6b35@10.151.254.104:50099','PYRO:obj_407b5d663ba94cdc974651d5433b6b35@10.151.254.104:50099','PYRO:obj_407b5d663ba94cdc974651d5433b6b35@10.151.254.104:50099','PYRO:obj_407b5d663ba94cdc974651d5433b6b35@10.151.254.104:50...
import abc from typing import List, Union from werkzeug.exceptions import HTTPException from domain.evenements.entities.tag_entity import TagEntity TagsList = List[TagEntity] class AlreadyExistingTagUuid(HTTPException): code = 409 description = "Tag already exists" class NotFoundTag(HTTPException): c...
''' If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. Not all numbers produce palindromes so quickly. For example, 349 + 943 = 1292, 1292 + 2921 = 4213 4213 + 3124 = 7337 That is, 349 took three iterations to arrive at a palindrome. Although no one has proved it yet, it is thought that some numbe...
from tkinter import * root = Tk() root.title("DummyFit") root.geometry('340x720') root.resizable(0, 0) lbl = Label(root, text="DummyFit", font=("Arial Bold", 50)) lbl.grid(column=0, row=0) head1 =Label(root, text="Input ---", font=("Arial Bold", 10)) head1.grid(column=0, row=1) txt1 = Entry(root,width=10,) t...
from qiniu import QiniuMacAuth, http # 密钥队初始化 access_key = 'your_AK' secret_key = 'your_SK' q = QiniuMacAuth(access_key, secret_key) url = 'http://ai.qiniuapi.com/v1/text/censor' # 请求url data = { "data": { "text": "你我,ak47" }, "params": { "scenes": ["spam"] } } ret, in...
# -*- coding: utf-8 -*- text="En cette journée mondiale de lutte contre le sida, rappelons qu'il est l'affaire de TS & TTES, un combat qui doit continuer ici et là-bas".decode("utf8") pat1=re.compile(r'(http|https)://[^\s]*',re.IGNORECASE | re.DOTALL) pat2=re.compile(r"[',;\.:/!?()\"#*%]",re.IGNORECASE | re.DOTALL) pa...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ABE 651 Assignment 2 Due 1/31 17:00 Exercise 6.5from ThinkPython2 (p.61) This is a program that prompts the user for two values and then computes the greatest common divisor (GCD) @author: wagne216 """ # Prompt user for inputs value_1 = input('Please choose first ...
import cv2 import numpy as np import glob from generator import preprocess_labels from sklearn.model_selection import train_test_split def load_files(folder="Train", reduce=False): images = [] masks = [] for file in glob.glob("./" + folder + "/CameraRGB/*.png"): img = cv2.imread(file) img = cv2.cvtCo...
""" Model for approximate system dynamics """ import torch import torch.nn as nn from torchlib.utils.layers import linear_bn_relu_block class ContinuousMLPDynamics(nn.Module): def __init__(self, state_dim, action_dim, nn_size=64): super(ContinuousMLPDynamics, self).__init__() self.discrete = Fal...
#-*- coding:utf-8 -*- """ " ip2region python seacher client module " " Author: koma<komazhang@foxmail.com> " Date : 2015-11-06 """ import struct, io, socket, sys class Ip2Region(object): __INDEX_BLOCK_LENGTH = 12 __TOTAL_HEADER_LENGTH = 8192 __f = None __headerSip = [] __headerPtr = []...
# -*- coding: utf-8 -*- """ node class. this class is the base class for all the node type in the tree. global variable- parmetersInTheWorld- represent the amount of parm we have - debugMode- represent the run mode this class maintain the updates between the calculated arguments such as probability, dis...
def compute_gcd(x,y): #find the smaller smaller = min(x,y) gcd = 1 for i in range(1,smaller+1): if((x%i == 0) and (y%i==0)): #gcd will be alterted each time the condition is true, so do #not need find the maximum. gcd = i return gcd num1 = int(input("Fi...
#! /usr/bin/env python # # Configure PyInstaller for the current Python installation. # # Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public...
import cgi, json import os import mysql.connector class Saver: def __init__(self): self.conn = mysql.connector.connect( user="mchavez8", password="mchavez8mysql123", host="localhost", database="mchavez8_chado" ) self.curs = self.conn.cursor() def __del__(self): ...
"""read_res_mfdn_transitions.py Provides simple example of reading and accessing MFDn postprocessor results. In practice, such results may need to be "merged" with results from mfdn. Required test data: data/mfdn-transitions/runtransitions00-transitions-ob-Z3-N3-Daejeon16-coul1-hw15.000-Nmax02.re...
import sqlite3 import requests def get_url_id(url): return int(url.split('/')[-2]) def insert_film(cursor, film_id): url = 'https://swapi.co/api/films/'+str(film_id)+'/' response = requests.get(url) data = response.json() params = [ film_id, data['title'], data['episode_id'], ...
import random p = random.random() class RandomP: @staticmethod def f(): return 0 if random.random() < p else 1 class Random01: def random01(self): t = "00" while t in ["00", "11"]: t = str(RandomP.f()) + str(RandomP.f()) return 0 if t == "01" else 1 r = Ran...
from django.shortcuts import render import pymysql from bbb.models import Yinyue from bbb.models import Shouji from django.shortcuts import HttpResponse from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage def index(request): yinyue_list = Yinyue.objects.all().order_by("id") # 一定要排...
from django.db import models # Create your models here. class Customer(models.Model): class Meta: db_table = 'customer' first_name = models.CharField(max_length=45) last_name = models.CharField(max_length=45) def __str__(self): return self.first_name class AcInvoices(models.Model)...
def strxor(a, b): # xor two strings (trims the longer input) #a = hex(a) #b = hex(b) return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)]) flag = "zenseCTF{0tp_0n1y_0nc3}" #n0w y0u kn0w 0tp 15 0n3 71m3}" print(len(flag)) key = "This is going to be a phrase of length 42" print(len(key)) p1 = "...
class Solution: def canPartition(self, nums): """ :type nums: List[int] :rtype: bool """ if nums==[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1...
import sys DEGREE_COUNT_PER_HOUR = 360 / 12 DEGREE_COUNT_PER_MINUTE = DEGREES_PER_HOUR / 60 DEGREE_COUNT_PER_SECOND = DEGREE_COUNT_PER_MINUTE / 60 hour_count, minute_count, second_count = map(int, sys.stdin) print( hour_count * DEGREE_COUNT_PER_HOUR + minute_count * DEGREE_COUNT_PER_MINUTE + second_count ...
# coding: utf-8 #!/usr/bin/python #libraries and modules used in our analysis import sys import pickle import pandas as pd sys.path.append("../tools/") from sklearn.feature_selection import SelectKBest import matplotlib.pyplot as plt from sklearn.pipeline import Pipeline from sklearn.preprocessing import RobustScal...
#Python Print "Hello World!" print "I am Rubin.I am coming!" print 'I try change the file from the Git windows client 22:00 10/12' print 'update 22:12 hehe on the website' #2015-10-15 13:00 by Maidao update
#elice_3_3_27.py import sklearn.decomposition import numpy as np import pandas as pd import elice_utils def main(): df = input_data() # 2 pca, pca_array = run_PCA(df, 1) # 4 print(elice_utils.draw_toy_example(df, pca, pca_array)) def input_data(): # 1 df = pd.DataFrame({'x': X, 'y': Y})...
from wallace.db.base import Model, KeyValueModel, RelationalModel from wallace.db.base import DataType from wallace.db.base import Boolean, ByteArray, Float, Integer, JSON, Moment from wallace.db.base import Now, String, Unicode, UUID, UUID4 from wallace.db.base import DBError, DoesNotExist, ValidationError from wallac...
from machine import Pin from apa102 import APA102 clock = Pin(14, Pin.OUT) # set GPIO14 to output to drive the clock data = Pin(13, Pin.OUT) # set GPIO13 to output to drive the data apa = APA102(clock, data, 128) # create APA102 driver on the clock and the data pin for 8 pixels def intensidad(value=128): ...
import random from turtle import Turtle from turtle import Screen from snake import Snake import random class Food(Turtle): """ This Class is responsible for creating Food and Bonus Food for snake""" def __init__(self): super().__init__() # self.create_food() def create_food(self): ...
import turtle import random wn=turtle.Screen() t1=turtle.Turtle() t2=turtle.Turtle() t3=turtle.Turtle() t1.speed(7) t2.shape("turtle") t2.color("Green") t2.penup() t3.shape("turtle") t3.color("Black") t3.speed(5) t3.penup() size1=100 size2=50 pos1=(-300,0) pos2=(-150,-200) pos3=(130,100...
import requests import paho.mqtt.client as PahoMQTT import json import re import random, string def get_random_string(length): letters = string.ascii_lowercase result_str = ''.join(random.choice(letters) for i in range(length)) return result_str class SuperMicroserviceClass(object): def ...
# Exercício 4.9 # Cálculo para financiamento da casa própria casa = float(input('Digite o valor do imóvel desejado:')) salário = float(input('Digite o valor de seu salário atual:')) qtde = float(input('Digite o número de anos em que deseja pagar o imóvel:')) prestmax = (salário*(30/100)) prestreq = (casa/(qtde*12)...
import os import sys import time import googleapiclient import googleapiclient.discovery import googleapiclient.errors if "YOUTUBE_API_KEY" not in os.environ: print("YOUTUBE_API_KEY not provided") sys.exit(0) # Build playlist set save to file api_service_name = "youtube" api_version = "v3" youtube = googleap...
"""MyRunningCar URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/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') Cla...
a = [1, 1, 2, 3, 4, 5, 8, 10, 15, 20, 100] i = 0 while a[i] < 5: print(a[i]) i = i+1 if a[i] >= 5: break i = 0 list = [] while a[i] < 5: list.append(a[i]) i = i+1 if a[i] >= 5: break print(list)
from Crypto.PublicKey import RSA from Crypto import Random def setup_ot(): prng = Random.new().read key = RSA.generate(1024, prng) r1 = Random.get_random_bytes(8) r2 = Random.get_random_bytes(8) publickey = key.publickey() return publickey, r1, r2 def select_one(key, r1, r2, select): nonce...
""" Title: 'Task 1' - Main Author: Caleb Otto-Hayes Date: 4/2/2021 """ import cipher, testing, sys def main() -> None: """ Main method to call test cases and user input to convert text. """ # Run input unless an argument is provided print('Converted text: \'' + ciphe...
from opentera.db.Base import BaseModel from opentera.db.SoftDeleteMixin import SoftDeleteMixin from opentera.db.SoftInsertMixin import SoftInsertMixin from opentera.db.models.TeraTestTypeProject import TeraTestTypeProject from sqlalchemy import Column, ForeignKey, Integer, Sequence from sqlalchemy.orm import relationsh...
# -*-coding:utf-8 -*- """ Created on 2015-05-21 @author: Danny<manyunkai@hotmail.com> DannyWork Project """ from __future__ import unicode_literals from django.contrib import admin, messages from django.core.urlresolvers import reverse from django.http import Http404, HttpResponseRedirect from core.modeladmin impor...
"A B C D" class data(): def __init__(self): self.items=[] def push(self,i): self.items.append(i) def get(self): return self.items def pop(self): self.items.pop() def empty(self): return self.items==[] def peek(self): if not self.empty(): return self.items[-1] ...
from pandas import DataFrame import constants as c import drive_test as drive import dataresource as collector import database_handler as db import pandas as pd def reorder_columns(data_frame): db_match_dataframe = DataFrame() required_columns = db.get_columns(c.SCHEMA, c.TABLE) if "id" in required_column...
import matplotlib.pyplot as plt import numpy as np """ Bifurcations are transitions between dynamical states used in nonlinear dynamics. This is a saddle-node bifurcation defined by dx/dt = r-x^2 It has equilibrium points at x_eq = +/- sqrt(r) and critical condition found by taking the derivative of dx/dt = F(x) so w...
from django.contrib.auth import get_user_model from django.db import models class Event(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) name = models.CharField(max_length=255, verbose_name='nazwa') description = models.CharField(max_length=255, verbose_name='opis') ...
# From Alex Drlica Wagner # https://cdcvs.fnal.gov/redmine/projects/des-sci-release/repository/entry/users/kadrlica/catalog_coadd/trunk/code/utils.py#L275 import warnings from astroquery.vizier import Vizier from astropy.coordinates import SkyCoord import astropy.units as u import astropy.io.fits as pf import numpy as ...
# -*- coding:utf-8 -*- import time def f1(): start_time = time.time() for a in range(0, 1001): for b in range(0, 1001): for c in range(0, 1001): if a + b + c == 1000 and a ** 2 + b ** 2 == c ** 2: print('a:%d,b:%d,c:%d' % (a, b, c)) end_time = time.t...
import numpy as np from imageio import imwrite import os import os.path def save_to_png(orig_im, mask, im_number, image_path): """ This function overlay a mask (segmentation) on an original image and save it as a .png file. Arguments: orig_im - original image without segmentation mask - bi...
# game.py import os import random #from random import choice from dotenv import load_dotenv print("Rock, Paper, Scissors, Shoot!") load_dotenv() PLAYER_NAME = os.getenv("PLAYER_NAME", default="Player One") print("-------------------") print(f"Welcome '{PLAYER_NAME}' to my Rock-Paper-Scissors game...") print("-----...
# https://www.hackerrank.com/challenges/staircase/problem def staircase(n): for i in range(1, n+1): line = '' for x in range(n-i): line += ' ' for x in range(i): line += '#' print(line) def staircase_hacker(n): for i in range(n): print(' ' * (n -...
from keras.models import load_model ,Model import numpy as np from PIL import Image from PIL import ImageEnhance import cv2 import os '''对图片进行测试''' model=load_model('pre-trained_CNN_model.h5') '''将图片转换为所需要的格式''' filepath='Image_test' for filename in os.listdir(filepath): imgfile=filepath+'/'+file...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch import torchvision import numpy as np import os from maskrcnn_benchmark.structures.bounding_box import BoxList from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask from maskrcnn_benchmark.structures.keypoint imp...
import os.path import random import numpy as np import pandas as pd from collections import deque from keras import optimizers from keras.models import Sequential from keras.layers.core import Dense from keras.layers import BatchNormalization import utilmodel as utm # directory for saving model files MODEL_PATH = 'mo...
a=2 # global b=5 # global def outer(): # enclosed function global b b=b+6 #UnboundLocalError: local variable 'b' referenced before assignment b=6 # enclosed variable print(b) # b=6 def inner(): # nested function or inner function c=5 # local variable print(a) # 2 ...
from datetime import datetime from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from Pruefung import Pruefung from Aufsicht import Aufsicht from Raum import Raum from SemesterGruppe import SemesterGruppe from Studiengang import Studiengang from ZeitSlot import ZeitSlot from Base import Base ...
"""Module for the FeatureNGram class""" import logging import sys logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) streamhandler = logging.StreamHandler(stream=sys.stderr) formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') streamhandler.setFormatter...
''' Project 2 - Scores Analysis and Bar Chart - Spring 2020 Author: <Nick Cerne, ncerne00> This program <describe your program here>. I have neither given or received unauthorized assistance on this assignment. Signed: <Nicholas Richard Cerne> ''' import turtle def draw_bar(integer): turtle.pensize(4) i = ...
#usr/bin/env python3 #by will #background is background1 import pygame import sys import os ''' Objects ''' class Platform(pygame.sprite.Sprite): #(x location, y location, img height, img file) def__init__(self,xloc,yloc,imgw, imgh): pygame.sprite.Sprite.__init__(self) self.image = pygame.Sur...
import cv2 import time import serial cap = cv2.VideoCapture(1) ser = serial.Serial('/dev/cu.usbserial-1460', 9600, timeout=0.5) def all_led_off(): time.sleep(1.5) led = 'alloff' ser.write(led.encode()) time.sleep(1.5) def all_led_on(): time.sleep(1.5) led = 'allon' ser.write(led.encode())...
from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from django.views.generic import * from labApp.forms import* # Create your views here. class MainPage(Template...
#! /usr/bin/env python """Checker for thesis-with-multiple-authors.""" from __future__ import annotations import colrev.qm.quality_model # pylint: disable=too-few-public-methods class ThesisWithMultipleAuthorsChecker: """The ThesisWithMultipleAuthorsChecker""" msg = "thesis-with-multiple-authors" def ...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np def abre_archivo (fn): array = [] for line in fn.readlines(): array.append(line.rstrip('\n').split(',')) for i in range (len(array)): for j in range (len(array[i])): ar...
# -*- coding: utf-8 -*- ''' @project: Pycharm_project @Time : 2019/6/27 17:19 @month : 六月 @Author : mhm @FileName: 1、用栈实现队列.py @Software: PyCharm ''' ''' 栈的顺序为后进先出,而队列的顺序为先进先出。 使用两个栈实现队列,一个元素需要经过两个栈才能出队列, 在经过第一个栈时元素顺序被反转, 经过第二个栈时再次被反转,此时就是先进先出顺序。 使用栈实现队列的下列操作: push(x) – 将一个元素放入队列的尾部。 pop() – 从队列首部移除元素。 peek() – 返回队列首部...
#!/usr/bin/python # # Copyright (c) 2015 MoreOptions. All rights reserved. # # Author: ankush@moreoption.co # # This class implements the helper functions for flipkart api # import os import pycurl import string from StringIO import StringIO class Request(object): def __init__(self): pass def send_request(s...
from __future__ import print_function import random,os,sys,binascii from Crypto.Util.number import isPrime from decimal import * try: input = raw_input except: pass getcontext().prec = 3000 def keystream(key): random.seed(int(os.environ["seed"])) p = random.randint(3,30) while not isPrime(p): p = random.randint(...
# Copyright (c) 2019, salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: MIT # For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT import torch import torch.nn as nn from base.modules.intrinsic_motivation import IntrinsicMotivationModule class Intri...
from mpi4py import MPI import numpy as np from math import sin from matplotlib.pyplot import * def sincSquareMPI(x): """Return the sinc(x) = (sin(x)/x)**2 of the array argument x. """ # assume the array length can be divided by the number of processes retVal = np.zeros_like(x) tempVals = np.z...
# # Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net> # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRAN...
import os from flask import Flask, render_template, request, redirect, url_for from werkzeug.utils import secure_filename import logging app = Flask(__name__) # 日志系统配置 # 日志器设置日志级别(日志器来自于 flask) app.logger.setLevel(logging.DEBUG) # 处理器(处理器来自于 logging 模块) handler = logging.FileHandler('my.log', encoding='UTF-8') l...
import typing from abaqusConstants import * from .AnalyticSurface import AnalyticSurface from .AnalyticSurfaceSegment import AnalyticSurfaceSegment from .BeamOrientationArray import BeamOrientationArray from .OdbDatumCsys import OdbDatumCsys from .OdbMeshElementArray import OdbMeshElementArray from .OdbMeshNodeArray i...
import unittest from src import roman_numbers class TestRomanNumbers (unittest.TestCase): def test_should_return_error_on_invalid_string (self): #roman_num = roman_numbers.RomanNumber("XCP") #self.assertTrue(False) with self.assertRaises(Exception): roman_num = roman_numb...
#!/usr/bin/python from pyspark import SparkContext from pyspark.sql import HiveContext import numpy as np import matplotlib.pyplot as plt import pandas as pd import sys #CREATE A TABLE WITH showing changes in distraction levels over time if __name__ == '__main__': #get data sc = SparkContext() sqlContext = HiveC...
#!/usr/bin/env python """ Shows how to create an image using numpy """ import cv2 import numpy as np width = 800 height = 600 n_channel = 3 data_type = np.uint8 # can also use float types img = np.zeros((height, width, n_channel), dtype=data_type) cv2.circle(img, (300, 300), 100, (255, 0, 0), cv2.FILLED) win_...
import pickle from News import getNewsList from Tokenizer import tokenize from Tokenizer import invalidToken from Normalizer import normalize from BTree import Node from BTree import BTree from BTree import calAllIdf from BTree import storeDictionary from BTree import loadDictionary from RankedBased import loadNormFac...
from django.shortcuts import render import requests from bs4 import BeautifulSoup from django.http import JsonResponse import re def get_hiver_data_as_api(request): p_tag_list=[] h1_tag_list=[] h2_tag_list=[] h3_tag_list=[] h4_tag_list=[] anchor_tag_list=[] li_tag_list = [] span_tag_li...