text stringlengths 38 1.54M |
|---|
#
#
#
#This is python example 2.
x= 10;
y= 25;
print 'x + y = ', x + y;
print 'x * y = ', x * y;
|
# Generated by Django 3.1.6 on 2021-04-21 04:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('order', '0022_auto_20210421_0430'),
]
operations = [
migrations.AddField(
model_name='block',
name='buyer_email',
... |
x= range(100,1000)
y=range(100,1000)
liste=[]
enbüyük=[111111]
for a in x:
for b in y:
sayi=str(a*b)
for t in range(0,len(sayi)//2):
if sayi[t]!=sayi[-t-1]:
break
else:
liste.append(sayi)
for each in liste:
if int(enbüyük[0])<int... |
# --*-- coding:utf-8 --*--
# for Python 2.7
from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as plt
from filature.bave import qvlbave
plt.figure(figsize=(10.0, 8.0))
bave = qvlbave.QVLBave(1200, 2.8, 1.8 / 2.8, 300.0 / 1200.0)
bave2 = qvlbave.QVLBave2(1200, 1.8 / 1200, 1 / ... |
# -*- coding: utf-8 -*-
# yumo
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
g_Ax = None
def InitSystem():
global g_Ax
fig = plt.figure()
g_Ax = fig.add_subplot(111, projection='3d')
def DrawTriList(triList):
for tri in triList:
g_Ax.add_collection3d(Poly3DCollection(... |
import time
def timeme(method):
def wrapper(*args, **kw):
start_time = time.time()
result = method(*args, **kw)
end_time = time.time()
print(method.__name__, int(round((end_time - start_time) * 1000)), "ms")
return result
return wrapper
|
# <p>Create a function running_average that returns a function.
# When the function returned is passed a value, the function returns the current
# average of all previous function calls. You will have to use closure to solve this.
# You should round all answers to the 2nd decimal place.</p>
'''
rAvg = running_average()... |
"""
Bite 313. Alternative constructors
In this Bite your are provides with a Domain class and a DomainException custom exception class.
You will add some validation to the current constructor to check if a valid domain name is passed in.
Next you will add a __str__ special method to represent the object (basically th... |
import numpy as np
from utils import bbox_utils
def encode_textboxes(y, epsilon=10e-5):
""" Encode the label to a proper format suitable for training TextBoxes PlusPlus network.
Args:
- y: A numpy of shape (num_default_boxes, 2 + 12 + 8) representing a label sample.
Returns:
- A numpy ar... |
import numpy as np
import cv2
# insert any image file you want here
img = cv2.imread('image.jpg')
# open window
cv2.namedWindow('Image', cv2.WINDOW_NORMAL)
# show image in window
cv2.imshow('Image', img)
cv2.imwrite("output.jpg", img)
print(img)
print(img.dtype)
print(img.shape)
# like console readline
cv2.waitKe... |
import json
import sys
import io
def stringToIntegerList(input):
return json.loads(input)
class ListNode:
def __init__(self,val=0,next=None):
self.val=val
self.next=next
def stringToListNode(input):
numbers=stringToIntegerList(input)
dummyRoot=ListNode(0)
ptr=dummyRoot
for ... |
# -*- coding: utf-8 -*-
from openerp import models, fields, api, _
from openerp.exceptions import UserError, ValidationError, Warning
class cashadvance(models.Model):
_name = 'comben.cashadvance'
sequence_id =fields.Char(string='Sequence ID')
@api.model
def create(self, vals):
vals['sequence_id'] = self.env['... |
import cMonster
import pygame
from cAnimSprite import cAnimSprite
import functions as BF
class cItemBouncer(cMonster.cMonster):
BSPRITEFAC = 1 #this is a little dirty. References the value assigned in cAnimSpriteFactory
def __init__(self,x,y,rot):
cMonster.cMonster.__init__(self,x,y,rot)
self.image = pygame... |
import re
class Validate:
def __init__(self, username=None, password=None, ver_password=None, email=None):
self.username = username
self.password = password
self.ver_password = ver_password
self.email = email
def username_val(self):
USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
return USER_RE.match(sel... |
__author__ = 'makarenok'
from model.contact import Contact
import random
def test_modify_contact_first_name(app, db, check_ui):
if app.contact.count() == 0:
app.contact.create(Contact(firstname="testFirstName", middlename="testMiddleName"))
old_contacts = db.get_contact_list()
contact = random.ch... |
__author__ = 'spijs'
from evaluationStrategy import EvaluationStrategy
import nltk
import nltkbleu
class BleuScore(EvaluationStrategy):
'''BLEU evaluation of the generated sentences
-> should ONLY be used for evaluating and sorting individual sentences.
multi-bleu.perl should be used for evluating full co... |
from __future__ import division # let 5/2 = 2.5 rather than 2
from Aerothon.ACPropeller import ACPropeller
from Aerothon.AeroUtil import STDCorrection
import numpy as npy
import pylab as pyl
from scalar.units import IN, LBF, SEC, ARCDEG, FT, RPM, OZF, GRAM, gacc, Pa, degR, W, inHg, K
from scalar.units import AsUnit
# ... |
#!/usr/bin/env python
#coding=utf-8
import os
#网站信息
WEB_URL='/'
WEB_NAME='上帝De助手 的博客'
WEB_SUBNAME='我只生产内容,我不是互联网的搬运工!'
WEB_TITLE='seo基础入门教程_网络营销入门学习_移动互联网创业项目故事'
WEB_KEYWORDS='seo基础入门教程,互联网络营销入门学习,移动互联网创业项目,互联网创业故事'
WEB_DESCRIPTION='发布有关seo相关的基础学习教程,开发seo相关的工具;学习互联网思维,并运用互联网思维进行网络营销策划;同时关注各行业互联网、移动互联网创业项目的发展。'
TEMPLATE... |
# -*- coding: utf-8 -*-
# Autor: Cristian Sáez Mardones
# Fecha: 18-04-2021
# Versión: 1.0.0
# Objetivo: Crear un juego de batallas pokemon
# Importación de archivo
# No hay
# Importación de bibliotecas
# Si hay
# Importación de funciones
# No hay
### Bibliotecas ###
# Biblioteca para el manejo de rutas
f... |
import time
import numpy as np
from sklearn.datasets import fetch_mldata
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
np.random.seed(0)
mnist = fetch_mldata('MNIST original')
data = np.hstack((mnist.data, mnist.target.reshape(-1, 1)))
np.random.shuffle(data)
# with ... |
from __future__ import division
import numpy as np
import pandas as pd
from multiprocessing import Pool
from matplotlib import pyplot as plt
def load_panel(a):
a = pd.read_pickle(a)
return a
def time_index(a):
a = a.reindex(index=a.index.to_datetime())
return a
def resamp(a):
a = a.resample('10T'... |
def identify_weapon(character):
if character == "Laval":
return "Laval-Shado Valious"
elif character == "Cragger":
return "Cragger-Vengdualize"
elif character == "Lagravis":
return "Lagravis-Blazeprowlor"
elif character == "Crominus":
return "Crominus-Grandorius"
elif... |
"""Functionality related to binding python functions to specific templated SQL statements."""
from dinao.binding.binders import FunctionBinder
__all__ = ["FunctionBinder", "errors"]
|
# Admission for anyone under age 4 is free
# Admission for anyone between the ages of 4 and 18 is $25
# Admission for anyone age 18 or older is $40
age = int(input('How old are you?\n'))
if age < 4:
print("The cost of your ticket is $0")
elif age < 18:
print("The cost of your ticket is $25")
else:
print("... |
import threading
import sqlite3
import Queue
import wx
class DBThread(threading.Thread):
"""
This thread is used to run SQL queries. It allows the UI to remain
responsive during queries that may take several seconds.
(Note: the fetch part of the query is usually the slow part. The execute
... |
from MainFrame import *
REFRESH_RATE = 1000
class Ele(Tk):
def __init__(self):
Tk.__init__(self)
self.minsize(width=800, height=800)
self.resizable(width=FALSE, height=FALSE)
MainFrame(master=self)
|
from datetime import datetime
import googlemaps
import os.path
import re
import xlwt
import yaml
# ---
# Init
# ---
book = xlwt.Workbook(encoding="utf-8")
sheet = book.add_sheet("Kilometers")
file_name_key = "key.txt"
file_name_addresses = "addresses.yaml"
file_name_distances = "distances.yaml"
file_name_data = "dat... |
# Standup Bot by Christina Aiello, 2017-2020
import re
import random
from logger import Logger
# For logging purposes
def format_minutes_to_have_zero(minutes):
if minutes == None:
return "00"
else:
if(int(minutes) < 10):
return "0" + str(minutes)
else:
return str... |
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from keras.models import Sequential
from keras.layers import Dense , Dropout , Lambda, Flatten
from keras.optimizers import Adam ,RMSprop
from sklearn.model_selection import train_test_split
train = pd.read_csv... |
SECRET_KEY = '-dummy-key-'
INSTALLED_APPS = [
'pgcomments',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
},
}
|
"""back URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... |
import numpy as np
import pandas as pd
import clean_data
import pdb
import copy
class LogisticReg:
"""Implement Algorithm 1 from Descent-to-Delete"""
def __init__(self, theta, l2_penalty=.1):
self.l2_penalty = l2_penalty
self.theta = theta
self.constants_dict = {'strong': self.l2_penal... |
################################################################################
# Cristian Alexandrescu #
# 2163013577ba2bc237f22b3f4d006856 #
# 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 ... |
import tensorflow as tf
from object_detection.utils import config_util
from object_detection.protos import pipeline_pb2
from google.protobuf import text_format
# Configurations des répertoires
WORKSPACE_PATH = 'boy_and_girl/workspace'
SCRIPTS_PATH = 'boy_and_girl/scripts'
APIMODEL_PATH = 'boy_and_girl/models'
ANNOTATI... |
"""Utilities functions."""
import pandas as pd
import torch as th
from pytoda.files import read_smi
from torch.utils.data import Dataset
class ProteinDataset(Dataset):
"""
Protein data for conditioning
"""
def __init__(
self, protein_data_path, protein_test_idx, transform=None, *args, **kwarg... |
# Default implementation of brute force KNN from Scipy
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from model import *
from util import split_train_test
import util
class default_knn:
samples = None
knn = None
scores = None
n = -1
k_max = -1
k_min = -1
def __init... |
#Each element greater that the current element is shifted forward
def insertionSort(length,elements):
for i in range(0,length):
temp = elements[i]
j = i
#if the prev element is greater than temp, then is shifted forward
#and j is decremented
while(j > 0 and elements[j-1] > temp):
elements[j] = elements[j-... |
from flask import Flask, request, redirect
import twilio.twiml
# Download the twilio-python library from http://twilio.com/docs/libraries
from twilio.rest import TwilioRestClient
# Find these values at https://twilio.com/user/account
account_sid = ""
auth_token = ""
client = TwilioRestClient(account_sid, auth_token)... |
abc = int(input())
a = abc // 100
bc = abc - a * 100
b = bc // 10
c = bc - b * 10
sum = a + b + c
print(sum)
|
import setup
PATH, ERRORS = setup.check_permissions()
JAVAC = "{}{}".format(PATH, "/resources/ui/javac.ui")
|
#!/usr/bin/python
#-*- coding:utf-8 -*-
#**********************************************************
#Filename: 177_get_max_min.py
#Author: Andrew Wang - shuguang.wang1990@gmail.com
#Description: ---
#Create: 2016-11-02 01:10:09
#Last Modifieda: 2016-11-02 01:10:09
#*****************************************************... |
class Solution():
def isMatch(self, s, p):
# matched[i][j] is True if the first one is opened
matched = [[False for _ in range(len(p)+1] for _ in range(len(s)+1)]
matched[0][0] = True
for i in range(len(s)+1):
for j in range(1, len(p)+1):
... |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ViewSetMixin
from django.http import FileResponse
import pymysql, os, time
import datetime
from django import forms
from operator import itemgetter
from itertools import groupby
from settings import... |
# Helpers
import copy
# Shapely **HAS** to be imported before anything else.
from shapely.geometry import mapping, shape
from shapely.prepared import prep
# Project configuration code
from geoplay.project import Project
# Data sources
from geoplay.data.zcta import ZCTA
from geoplay.data.stl_parks import StlParks
proj... |
# 用urllib.request 代替原来的 urllib2
import urllib.request
url = "http://www.baidu.com"
#用urllib.request.urlopen() 代替 urllib2.urlopen()
response1 = urllib.request.urlopen(url)
#打印请求的状态码
print(response1.getcode())
#打印请求的网页内容的长度
print(len(response1.read()))
|
from django.urls import path
from employee.views import EmployeeListAPIView, AddEmployeeAPIView, EmployeeAPIView
urlpatterns = [
path('', AddEmployeeAPIView.as_view(), name='create-employee'),
path('<int:pk>', EmployeeAPIView.as_view(), name='employee-view'),
path('list', EmployeeListAPIView.as_view(), na... |
n, a, b =map(int, input().split(" "))
counter = 0
for i in range(0,n+1):
li = map(int,list(str(i)))
s = sum(li)
if a <= s and s <= b:
counter = counter + i
print(counter) |
num_dict = {0:'', 1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine',
10:'ten', 11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen', 16:'sixteen', 17:'seventeen', 18:'eighteen', 19:'nineteen',
20:'twenty', 30:'thirty', 40:'forty', 50:'fifty', 60:'sixty', 70... |
from .source_list import SourceListModel
from .appraiser_tx import AppraiserTexas
from .inspector_tx import InspectorTexas
from .real_estate_sales_agent_tx import RealEstateSalesAgentTexas
from .re_license_applicant_tx import RealEstateSalesAgentApplicantTexas
from .real_estate_sales_agent_ok import RealEstateSalesAgen... |
import random
n = int(input())
mylist = []
for i in range(0,n):
mylist.append(random.randint(0,100000))
print(n)
for i in mylist:
print(i, end = " ")
|
# coding=utf-8
from .models import *
from django.http import HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.http import require_http_methods
from django.core.files.base import ContentFile
import json
from .serializer import *
from .message_templates import send_a... |
# coding: utf8
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import string
import datetime
import allure
import pytest
import requests
import selene
from selene import driver
from selene import tools
from selene.conditions import text, visible
from selene.api import *
import time
from selenium import we... |
from rest_framework import serializers
from core.models import Employee
from authentication.serializers import UserSerializer
from api.v1.department.serializers import DepartmentSerializer
from api.v1.designation.serializers import DesignationSerializer
from api.v1.ifs.serializers import IfsSerializer
from api.v1.compa... |
import sys
from locus import Locus
from collections import Iterator
import numpy as np
class Pileup_file(Iterator):
"""Class implements an iterator
of pileup file lines. Each line
parsed and returned as a Locus
object."""
def __init__(self, filename=None):
if filename:
self.in... |
import csv
from keras import backend as K
from keras.models import load_model
import numpy as np
import os
import sys
# inputs
model_input = sys.argv[1]
n_chars = int(sys.argv[2])
model_dir = sys.argv[3]
charset_file = sys.argv[4]
# to use GPU
os.environ["CUDA_VISIBLE_DEVICES"]="0"
# verify that a gpu is listed
K.te... |
import os
class Names:
"""File names saved here with paths"""
def __init__(self):
self.cases_dir = {"Mie02": "./data/zio/Mie_case02_retry_20200516_after_sorting/",
"Mie03": "./data/zio/Mie_case03_WL204_3rd_growing_after_sorting/",
"Mie02_10": "./dat... |
import torch.utils.data
import torch
from torch.utils.data import Dataset
class Data_Utility(Dataset):
'''
returns [samples, labels]
'''
def __init__(self, input_size, output_size, encode_length, time_steps, data):
self.input_size = input_size
self.output_size = output_size
s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 16 14:01:22 2020
@author: base
#--------------------------------
# If the link to the model should fail , it can be loaded and save with the following:
import subprocess
import sys
def install(git+https://github.com/rcmalli/keras-vggface.git):
... |
""" Module for removing background from image as a pre-processing step"""
import numpy as np
import cv2 as cv
def crop_image(img):
""" finds the max contour and crops image """
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
_, threshed = cv.threshold(gray, 240, 255, cv.THRESH_BINARY_INV)
kernel = cv.getSt... |
from codec import dump, dumps, load, loads
from codec import GeoJSONEncoder
from geometry import Point, LineString, Polygon
from geometry import MultiLineString, MultiPoint, MultiPolygon
from geometry import GeometryCollection
from feature import Feature, FeatureCollection
from base import GeoJSON
|
#!/usr/bin/env python
import sys
from sets import Set
if len(sys.argv) != 3:
print "Usage: {} <dataset> <output>".format(sys.argv[0])
print " dataset: File containing the data whose duplicates will be " \
"removed."
print " output: File where output data will be stored."
exit(1)
el... |
from typing import Any, IO, Text
import io
class GzipFile(io.BufferedIOBase):
myfileobj = ... # type: Any
max_read_chunk = ... # type: Any
mode = ... # type: Any
extrabuf = ... # type: Any
extrasize = ... # type: Any
extrastart = ... # type: Any
name = ... # type: Any
min_readsiz... |
from flask import Flask
from flaskext.sqlalchemy import SQLAlchemy
import archie.config
# startup and utils
app = Flask(__name__)
app.config.from_object(archie.config.TestingConfig)
db = SQLAlchemy(app)
import archie.views
import archie.install
# recreate the db from scratch
archie.install.begin()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Ziga Vucko'
from os.path import basename
from sys import argv
import time
from Util import Logger, Config, Batch, NELLDict, FeaturePreprocessor
t0 = time.time()
logger = Logger(type_='bp')
config = Config(logger=logger)
config.load()
nell = NELLDict(logge... |
from django import forms
from django.contrib import admin
from .models import Card
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from .models import Profile
# Define an inline admin descriptor for Employee model
# which acts a bit like a singleton
class ... |
#encoding:utf+8
import requests
def main():
import requests
# 要访问的目标页面
targetUrl = "http://test.abuyun.com"
# targetUrl = "http://proxy.abuyun.com/switch-ip"
# targetUrl = "http://proxy.abuyun.com/current-ip"
# 代理服务器
proxyHost = "http-pro.abuyun.com"
proxyPort = "9010"
# 代理隧道验证信... |
import numpy as np
import pandas as pd
from sklearn.pipeline import make_pipeline
from sklearn.experimental import enable_hist_gradient_boosting
from sklearn.ensemble import HistGradientBoostingClassifier, HistGradientBoostingRegressor
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardS... |
# file that holds all the routes of the API
from flask import Blueprint, jsonify, request
from bson import json_util
import json
import aws
import index
fitShare_api = Blueprint('fitshare_api', __name__)
######################################################################################
# ... |
import pusher
class Pusher:
pusher_client = None
@classmethod
def create_instance(cls):
cls.pusher_client = pusher.Pusher(
app_id='732495',
key='4df52d9bd8bcf616c85c',
secret='54e285d0324b0e65fcc8',
cluster='eu',
ssl=True
)
... |
from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
from keras.layers import Conv1D, MaxPooling1D
from keras.layers import GRU, Bidirectional
from keras.optimizers import Adam
import numpy as np
input_layer = Input(shape=(300,26), name='input' )
conv_2d = Conv1D(filters= 64, ... |
import report_transfer
import regional_report_transfer
import firm_report_transfer
import pmu_report_transfer
import bank_report |
#!/usr/bin/python3
try:
import json
import sys
save_to_json_file = __import__('7-save_to_json_file').save_to_json_file
load_from_json_file = __import__(
'8-load_from_json_file').load_from_json_file
except ImportError:
print("Import Error")
"""
script to add arguments to a JSON list
"""
try... |
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
INSTALLED_APPS += (
'django_nose',
)
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '7!@uqrj1=0riqnmyl+79jbsu5t$uz7=7rjc1+sx=1(%)o4ox6c'
EMAIL_BACKEND = 'dj... |
import tensorflow as tf
from text_rcnn_model import TRCNNConfig, TextRCNN
import numpy as np
import tensorflow.contrib.keras as kr
import time
from datetime import timedelta
import os
from data_process import Data
def get_time_dif(start_time):
"""获取已使用时间"""
end_time = time.time()
time_dif = end_time - sta... |
# Assignment 2.2
# 2.2 Write a program that uses input to prompt a user for their name and then welcomes them. Note that input will pop
# up a dialog box.
name = input("Enter your name ")
print("Hello " + name)
# Assignment 2.3
# 2.3 Write a program to prompt the user for hours and rate per hour using input to compute... |
from test_support import *
def test_exception():
t = rf.FpException("test")
assert t.what().startswith("test")
|
'''
random number generator
'''
import os
import binascii
import argparse
parser = argparse.ArgumentParser(description='generate random string')
parser.add_argument('size', metavar='size', type=int, help='length of the random string')
args = parser.parse_args()
string = binascii.b2a_base64(os.urandom(args.size))
... |
def Col(i):
if i%2:
return i*3+1
return i//2
i=int(input())
print(i,end=" ")
while(i:=Col(i)):
print(i,end=" ")
if i==1:
break
|
students_email = [
'nenavathpraveen10@gmail.com',
'sapna98saini@gmail.com',
'90.preeti@gmail.com',
'aryali012@gmail.com',
'venkateshmamidala39@gmail.com',
'somasekhardesigns@gmail.com',
'zeddkhan101@gma... |
# [DOCS]
# https://docs.python.jp/3/library/codecs.html
# rot暗号を解くためのスクリプト
import codecs
import sys
argv = sys.argv
if (len(argv) != 3):
print('Argument is less. Please add char and rot num.')
exit()
enc = argv[1]
rot_num = argv[2]
answer = ''
for letter in enc:
answer += chr(ord('A') + (ord(letter)-ord(... |
#!/usr/bin/env python3
from collections import Counter
import sys
def parse_line(l):
[ins, out] = l.split(" => ")
ins = ins.split(", ")
ins = [component.split(" ") for component in ins]
ins = {chemical: int(qty)
for [qty, chemical] in ins}
out = out.strip().split(" ")
return (o... |
# @desc: script that formats json array data to elastic bulk data
# @author: mladen milosevic
# @date: 25.02.2020.
import json
import time
inputFile = 'ebooks.json'
outputFile = 'ebooks-bulk.json'
start = time.process_time()
with open(inputFile, 'r', encoding = "utf8") as moviesFile:
movies = json.load(moviesFile)... |
from django.urls import path
from . import views
urlpatterns = [
path('',views.home),
path('views/',views.index),
path('map/',views.coordinates),
path('add/', views.add_squirrel),
path('views/<str:Unique_Squirrel_ID>/edit/',views.edit_squirrel),
path('stats/',views.stat... |
# Developed since: Feb 2010
import upy.core
import numpy
# Reference:
# Siegfried Gottwald, Herbert K"astner, Helmut Rudolph (Hg.):
# Meyers kleine Enzyklop"adie Mathematik
# 14., neu bearbeitete und erweiterte Aufl. -
# Mannheim, Leipzig, Wien, Z"urich: Meyers Lexikonverlag, 1995
# Abschn. 28.2. Ausgle... |
#Libraries
import RPi.GPIO as GPIO
import time
#GPIO Mode
GPIO.setmode(GPIO.BOARD)
#set GPIO Pins
Bin1 = 11
Bin2 = 13
Bpwm = 15
slow = 20
med = 50
fast = 100
GPIO.setup(Bin1,GPIO.OUT)
GPIO.setup(Bin2,GPIO.OUT)
GPIO.setup(Bpwm,GPIO.OUT)
rightTopPWM = GPIO.PWM(Bin1,slow)
rightTopPWM.ChangeFrequency(100)
rightTopPWM... |
#!/usr/bin/python
import git # Interacting with git
from git import Repo # Interacting with git Repositories
import shutil # for conveniently deleting local folder
import hashlib # for getting hash of file
import pexpect # for interacting with shell
from subprocess import Popen, PIPE, STDOU... |
import os
#os.rename("a.txt", "b.txt")
#os.remove("b.txt")
res = os.listdir("./anli")
print(res)
print(os.path.isdir("./anli/game"))
#os.mkdir("./anli/dirtest")
#os.rmdir("./anli/dirtest")
print(os.getcwd())
|
from distutils.core import setup
setup(
name='plugwise',
packages=['plugwise'],
version='0.2',
license='MIT',
description='A library for communicating with Plugwise smartplugs',
author='Sven Petai',
author_email='hadara@bsd.ee',
url='https://bitbucket.org/hadara/python-plugwise/wiki/Home',
download_ur... |
#!/usr/bin/env python3
"""
Author: Francis C. Dailig
Project Name: Project 1
Description: Code for Project 1. Three test cases: 1 - Small HTTP object; 2 - Large HTTP object; 3 - Simple HTTP Server
"""
import argparse
import socket
def testCase1():
"""
This function will run the first test case for project... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 10 23:37:09 2018
@author: zeeshan haider
"""
from IPython import get_ipython
get_ipython().magic('reset -sf')
import pyaudio
import wave
import os
import librosa
import numpy as np
import cPickle
path="E:\\All Data\\study\\MS\\2\\machine learning\\Project... |
"""
Python code snippets vol 38:
188-Calculate percentage
stevepython.wordpress.com
requirements: None
source:
https://docs.python.org/3/library/string.html#module-string
"""
points = 10
total = 300
print('Percentage of points from total is: {:.2%}'.format(points/total))
#Output:
#>>>Percentage of p... |
#!/usr/bin/python
import pandas as pd
from ete2 import Tree
import numpy as np
def Make_VJ_Matrix():
#format for calling location matrix_name['J_name'].loc['V_name']
V_names = ['IGHV1-12', 'IGHV4-4', 'IGHV1-17', 'IGHV1-14', 'IGHV3-15', 'IGHV1-18', 'IGHV3-11', 'IGHV3-13', 'IGHV(III)-16-1', \
'... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from rest_framework.parsers import JSONParser
from rest_framework.renderers import JSONRenderer
from apiREST.models import *
from ... |
import itertools
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.core.validato... |
# Generated by Django 2.0.6 on 2018-07-01 21:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('solution', '0022_auto_20180701_1709'),
]
operations = [
migrations.AlterField(
model_name='project',
name='authors',... |
from flask import Flask, json, Response, redirect
from flask_cors import CORS
import os
import random
import json
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# allows redirects
CORS(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:G8AR7Cseu5bTh9pPttcX@localhost/flowgames'
app.confi... |
""" Check domains, IPs, and hosts to ensure they are "external" """
import ipaddress
import publicsuffix2
__version__ = '1.0.1'
def is_external_address(addr):
""" Similar to the ``ipaddress`` ``is_global`` property, test if the
address (given any way ``ipaddress.ip_address`` allows) is an "external"
(... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
__author__ = 'huangbinghe@gmail.com'
import sublime
import sublime_plugin
from collections import Counter
class MaxCountCommand(sublime_plugin.TextCommand):
def run(self, edit, without_empty_line=1):
setting = sublime.load_settings("HBH-Rows.sublime-settings")
... |
from urllib import request
from bs4 import BeautifulSoup
import json
from pprint import pprint
from scipy import stats
from utils import truncate
#############
### Setup ###
#############
teams = ['SF', 'CHI', 'CIN', 'BUF', 'DEN', 'CLE', 'TB', 'ARI',
'SD', 'KC', 'IND', 'DAL', 'MIA', 'PHI', 'ATL', 'NYG',
... |
from collections import deque
from typing import Deque
class SetOfStacks:
def __init__(self, capacity):
self.set_of_stacks = []
self.capacity = capacity
def getLastStack(self):
return self.set_of_stacks[-1] if self.set_of_stacks != [] else Deque()
def push(self, data):
c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.