text stringlengths 38 1.54M |
|---|
'''
simple-calculator-v3.py
Allow the user to enter a full arithmetic expression and use eval to evaluate it.
'''
expression = input(
"Welcome to Simple Calculator v3. Please enter an arithmetic expression(i.e.: \"2 + 3\" or \"(9 * 7) / (88 - 9)\") and the calculator will evalue it: "
)
while True:
try:
... |
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.utils import timezone
from approver.models import Person
from approver.constants import SESSION_VARS
from . import user_crud
def add_shib_information_to_session(request):
"""
... |
import operator
class City:
edges = []
def __init__(self, name='', root=None, greedy=0, heuristic=0):
self.name = name
self.root = root
self.greedy = greedy
self.heuristic = heuristic
self.cost = greedy + heuristic
class Path:
map = {}
graph = None
path_possibilities = []
air_distance = {'Arad': ... |
import numpy as np
import random as rand
import matplotlib.pyplot as plt
def random_age():
age_val = rand.random()
if age_val < 0.2:
age = int(15*rand.random()) # 15-0=15
elif age_val < 0.85:
age = int(50*rand.random()) + 15 # 65-15=50
else:
age = int(30*rand.random()) + 65 # 95... |
class PowerConsumer():
"""Base class for power consuming objects."""
def __init__(self, power_input: int):
"""Initialize the `PowerConsumer` object.
Args:
power_input: Specifies the requirement of power for this consumer in watts per second.
"""
self._input = power... |
from config import URL_HOST, POSTGRES_PORT
import os
os.system('docker pull postgres')
os.system('docker run --name postgres_az -p '+POSTGRES_PORT+':5432 -e POSTGRES_PASSWORD=postgres -d postgres:latest')
|
import pandas as pd
import argparse
from tqdm import tqdm
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Build protocols from pregenerated oulu metadata.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('input_folder', type=str, h... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Local data_store interface."""
import json
import os
import pickle
from rudra.data_store.abstract_data_store import AbstractDataStore
from scipy.io import loadmat
from rudra import logger
from ruamel.yaml import YAML
class LocalDataStore(AbstractDataStore):
"""W... |
# -*- coding: utf-8 -*-
import sys
import argparse
from jconvertor.word2vec import functions as w2v_func
from ml.deeplearning.nwjc2gnews2vec_sigmoid_5_majority import NWJC2GNEWS2VECSigmoid5MAJORITY
from amazon_corpus.functions import read_amazon_corpus
import constants
def main(start_k, end_k, start_epoch, end_epoc... |
from history import history
from ls import ls
from pwd import pwd
from cd import cd
from exit import exit
from cp import cp
from cat import cat
from clear import clear
from grep import grep
from mv import mv
from mkdir import mkdir
from true import true
|
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1300811410.3089409
_template_filename='/home/home/oostendo/dev/cortex/cortex/cortex/templates/discover.mako'
_template_uri='/discover.mak... |
from svm import *
from svmutil import *
import sys
if __name__ == '__main__':
y, x = svm_read_problem('train_precompute_data')
ty, tx = svm_read_problem('test_precompute_data')
prob = svm_problem(y, x, isKernel = True)
param = svm_parameter('-t 4 -c 4 ')
param_poly = svm_parameter('-t 1')
pa... |
import os
import glob
import re
from sympy.parsing.sympy_parser import parse_expr
from sympy import simplify
global homogeneous
global path
#pathstring = str(os.path.dirname(os.path.realpath(__file__)) + "/input_files/comass[0-9][0-9].txt")
#pathstring = str(os.path.dirname(os.path.realpath(__file__)) + "/input_files... |
#!/usr/bin/env python
from helpers import *
import stubs #.message
import auth
import hashlib
sys.path.append("modules.d")
import regen_modules
regen_modules.rebuild_bModules()
import bModules
pw = "testpass"
pw_hash = hashlib.md5(pw).hexdigest()
START("auth")
at = auth.Authenticator(auth_hash=pw_hash)
auth_msg... |
import numpy as np
from scipy import signal, misc
import matplotlib.pyplot as plt
from scipy import ndimage
# Image Read
lena = misc.imread('./image_sample/lena_256.bmp')
col, row = lena.shape
# Apply Fourier TransForm
# 이미지 푸리에 변환 -> 주파수 영역 이미지 -> 복구
F = np.fft.fft2(lena) #fft2 : 2차원 이미지용
Mag = np.abs(F) #폭(크기... |
# Copyright 2018 Samuel Payne sam_payne@byu.edu
# 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 ... |
#!/usr/bin/python3
"""
Print a string on the stdout.
"""
def text_indentation(text):
"""
Split a text where is found the delimiters ., :, and ?
Args:
text (str): text to split.
Return:
print on the stdout.
"""
if not isinstance(text, str):
raise TypeError("text must b... |
import pytest
from ddf import G
from django.contrib.auth import get_user_model
from django.test.testcases import SimpleTestCase
from django_functest import FuncWebTestMixin
from general.models import Camp
from utils.urls import admin_url as _admin_url
User = get_user_model()
class FuncWebTest(FuncWebTestMixin, Simp... |
#------------------------------------------------------------------------------
# __init__.py - Parsers package root
#
# December 2015, Antony Wallace
#------------------------------------------------------------------------------
"""Parsers for Jam debug output."""
__all__ = (
"parse",
)
from ._dd import DDPar... |
'''
Query the User for a stock ticker (e.g., "IBM")
Verify that the ticker is valid by returning the full name of the company (e.g., "IBM Corp." or other appropriate regulatory name) or query the User again
Query the User for Pertinent Year-Ended Dates (Program should check whether fiscal years are calendar years or ot... |
from decorators import standard_error, standard_response
@standard_response
@standard_error
class dbaddWorker:
NAME = 'db-add'
NICENAME = 'Database Add'
REQUEST = {
'key': str,
'database': str,
'collection': str,
'data': dict,
}
@standard_response
@standard_error
clas... |
meno = "John"
naz = "Snow"
#CTRL + SPACE - podpowiada jakie mamy dostępne opcje
#FN lub ALT + Shift + F10
#by komentowacaych linii służy CTRL + /
print(f'Witoj, {meno} {naz}'[-1:-6:-1])
# dwa = meno + ' ' + naz
# # print('z spacji', dwa)
# # print('bez spacji', dwa.strip(' '))
# #
# # trzy = "_ucho_"
# # print(trzy)
... |
#Name: Juan Gonzalez
#ID: 1808943
num1 = int(input())
num2 = int(input())
num3 = int(input())
num4 = int(input())
num5 = int(input())
num6 = int(input())
works = False
x = 0
y = 0
for i in range(-10,11):
for j in range(-10, 11):
if ((((num1 * i) + (num2 * j)) == num3) and (((num4 * i) + (... |
#! /usr/bin/python3
# mclip.py - a multi clip board program.
TEXT = {'agree':'Yes, i agree thanks whatever.','busy':'so sorry cant come too busy.',
'upsell':'gis more money please'}
import sys,pyperclip
if len(sys.argv)<2:
print("Usage: python mclip.py [keyphrase] - copy paste text")
sys.exit()
keyph... |
from .utils import organization_manager
def organizations(request):
"""
Add some generally useful metadata to the template context
"""
# selected organization
orga = organization_manager.get_selected_organization(request)
# all user authorized organizations
if not request.user or not requ... |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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 limitation
# the rights to use, copy, modify,... |
def is_matched(expression):
dict_b = {
")": "(",
"]": "[",
"}": "{"
}
stack = []
for char in expression:
if char in dict_b.values():
stack.append(char)
elif char in dict_b.keys():
if stack:
most_recent = stack.pop()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Rico Sennrich <sennrich [AT] cl.uzh.ch>
# This program handles the combination of Moses phrase tables, either through
# linear interpolation of the phrase translation probabilities/lexical weights,
# or through a recomputation based on the (weighted) combined cou... |
N,K=map(int,input().split())
x=list(map(int,input().split()))
index = 0
ans = 10**9
while index + K - 1 < N:
start = x[index]
end = x[index + K - 1]
if start < 0:
ans = min(ans,abs(end-start)+abs(start))
ans = min(ans,abs(end-start)+abs(end))
else:
ans = min(ans,end)
index +=... |
import copy
import qcp
import qcprot
def getRefCA(ref_ca, s1_def, s2_def):
x, y, z = [], [], []
for res in s1_def:
x.append(ref_ca[int(res) - 1][0])
y.append(ref_ca[int(res) - 1][1])
z.append(ref_ca[int(res) - 1][2])
for res in s2_def:
x.append(ref_ca[int(res) - 1][0])
... |
#-------------------------------------------------------------------------------
# Name:
# Purpose:
#
# Author: Hannah Fritsch
#
# Created: 20/02/2020
# Copyright: (c) Hannah Fritsch 2020
# Licence: <your licence>
#-------------------------------------------------------------------------------
import sql... |
import requests
import time
import math
from tech_news.database import create_news
from parsel import Selector
# Requisito 1
def fetch(url):
try:
response = requests.get(url, timeout=3)
time.sleep(1)
except requests.ReadTimeout:
return None
if response.status_code == 200:
r... |
import pytest
import ray
from ray import train
from ray.train import ScalingConfig
from ray.train._internal.worker_group import WorkerGroup
from ray.train.backend import Backend, BackendConfig
from ray.train.data_parallel_trainer import DataParallelTrainer
from ray.train.tests.util import create_dict_checkpoint, load_... |
#看解题区才知道原来我写的这就算是动态规划了。。
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
pascal=[]
if numRows>=1:
pascal.append([1])
for i in range(1,numRows):
temp=[]
temp.append(1)
for j in range(1,i):
temp.append(pascal... |
''' Implementar la clase Rectangulo que contiene una base y una altura, y el método area.'''
class Rectangulo:
def __init__(self, base, altura):
self.base = base
self.altura = altura
def area(self):
a = self.base*self.altura
return a
algo = Rectangulo (5,6)
assert (algo.a... |
from .. utils import TranspileTestCase
class SetattrTests(TranspileTestCase):
def test_minimal(self):
self.assertCodeExecution("""
class MyClass(object):
class_value = 42
def __init__(self, val):
self.value = val
print("On class... |
"""baseball URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-base... |
def mpg(a, b):
mpg = a / b;
mpg = round(mpg, 3);
return mpg;
miles = float(input("Enter the number of miles driven: "));
gallons = float(input("Enter the number of gallons used: "));
mpg = mpg(miles, gallons);
print ("Your vehicle can go " + str(mpg) + " miles per gallon.");
|
from time import time
class FrameManager:
def __init__(self, flagPrintFPS:bool=False):
self.__frameCount_i = 0
self.__lastCountedTime_f = 0.0
self.__frameDelta_f = 0.0
self.__lastCountFPS_f = time()
self.__fpsCounter_i = 0
self.__lastFPS_i = 0
self.__flagPri... |
import math
import sqlite3
#based on analysis of data and court dimensions the x axis spans the length of the court
#while the y axis spans the width of the court
#method for determining if the shot taken was a FG, FT or 3PT
def check_shot_type(shot_x, shot_y, offense_basket):
#need to get the correct x and y di... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def g(x):
return np.exp((-1 / 2) * x) * np.cos((-2) * x)
def h(x):
return np.exp((-3 / 2) * x) * np.sin(4 * x)
def main():
x = np.linspace(0, 4, 501)
y_func = g(x)
h_func = h(x)
plt.plot(x, y_func, 'r-', label="Cos talas")
plt.plot(x, h... |
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
#img = cv2.imread('lines.jpg')
while(True):
ret, img = cap.read()
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
#print img.shape[1]
#print img.shape
minLineL... |
# Generated by Django 2.0.1 on 2018-02-15 18:11
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django_dag.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_US... |
# -*- coding: UTF-8 -*-
from __future__ import division
import ordereddict
import os
import pymongo
import simplejson as json
import time
import urllib2
import csv
def gen_frame_lines(fp, server, collection, month, day):
frame_25 = {}
frame_25_rate = {}
frame_39 = {}
frame_39_rate = {}
frame_100 = {}
frame_100_r... |
species(
label = 'C#C[CH]CC[CH]C=C(26564)',
structure = SMILES('C#C[CH]CCC=C[CH2]'),
E0 = (467.707,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,2995,3025,975,1000,1300,1375,400,500,1630,1680,2175,525,750,770,3400,2100,2750,2783.33,2816.67,2850,1425,1450,1225,1275,1... |
from user import User
class Admin(User):
def __init__(self):
super().__init__()
self.setDescription("Admin")
|
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import Session
class SessionContext:
def __init__(self, db_name: str):
self.db_name = db_name
self.session_maker = sessionmaker(bind=self.create_aurora_engine(), expire_on_commit=False)
... |
import re
import sys
import random
import time
import datetime
import copy
#import plotly.plotly as py
#import plotly.figure_factory as FF
import pdb
data=[]
colors=[]
text = []
n_colors=[]
n_text=[]
def gettime(strtime):
hours = strtime[11:13]
mins = strtime[14:16]
senconds = strtime[17:19]
msenconds... |
'''while True:
number = 1
while number%2==1:
number = int(input('Please enter a odd number: '))
if number % 2 == 0:
print('Sorry, please enter odd number')
break
for i in range(number,0,-2):
print((str(i)*i).center(number*len(str(number))))
'''
a = []
... |
def overlap_interval(arr):
if not arr:
return []
arr=sorted(arr, key=lambda x:x[0])
soln=[arr[0]]
for i in range(1, len(arr), 1):
if arr[i][0]<soln[-1][1]:
soln[-1][1]=arr[i][1]
else:
soln.append(arr[i])
return soln
print(overlap_interval([[1,3],[2,4],... |
import turtle
def draw_triangle(t,color):
t.fillcolor(color)
t.begin_fill()
t.forward(20)
t.left(120)
t.forward(20)
t.left(120)
t.forward(20)
t.end_fill()
def draw_cort():
window = turtle.Screen()
window.bgcolor('#ff0084')
t = turtle.Turtle()
t.color('#fff')
t.shape... |
#1723682
#David van Vliet
import csv
prijs = ''
naam = ''
artikelnummer = ''
voorraad = ''
totaal_producten = 0
with open ('pe9_4.csv', 'w')as pe9_4: # Maakt het bestand aan met de volgende regels en kolommen
schrijven_bestand = csv.writer(pe9_4, delimiter = ';')
schrijven_bestand.writerow (('Artikelnummer',... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torchtext import data, datasets
import numpy as np
import math
import copy
import time
from model import *
from utils import *
import spacy
spacy_de = spacy.load('de')
spacy_en = spacy.load('en')
def tokenize... |
#! /usr/bin/python2
#from getmac import get_mac_address
from uuid import getnode as get_mac
from urllib.parse import urlencode
#import urllib.parse
import pycurl
import time
import sys
from time import gmtime, strftime
EMULATE_HX711=False
import requests
import json
referenceUnit = 108
if not EMULATE... |
""" Script to calculate the theoretical neutrino spectrum and to simulate the expected spectrum from DM annihilation
with background in the JUNO detector in the energy range from few MeV to hundred MeV
-> old version of the simulation
-> do NOT use it
-> instead use gen_simu_spectrum_v1.py
"""
#... |
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# 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 ap... |
from _lib import exceptionUtils
from xmlrpc.client import Fault
def createNewProject(server, prj_code, template_code, title):
server.start("Create Project", "Project creation for {} of type {}".format(prj_code, template_code))
try:
args = {'project_code': prj_code,
'template_code': tem... |
__author__ = 'ovidiucs'
"""
Using the Python language, have the function FormattedDivision(num1,num2) take
both parameters being passed, divide num1 by num2, and return the result as a
string with properly formatted commas and 4 significant digits after the decimal
place. For example: if num1 is 123456789 and num2 is 1... |
import random as rand
# Open the file is input is not there create one
try:
in_text = open("in.txt", "r")
out_text = open("out.txt", "w")
except IOError:
print("File in.txt does not exist creating default one.")
in_file = open("in.txt", "w")
string = """\
We are a one of a... |
# Trouver le mot le plus court et le plus long dans une phrase
# le premier par ordre alphabetique
# ordre dans la phrase en premier
def get_min_and_max_words(sentense):
words = sentense.split(" ")
min_word = min(words, key=len)
max_word = max(words, key=len)
# print(words)
return min_word, max_wo... |
from nerds.features.base import FeatureExtractor, BOWFeatureExtractor, RelationFeatureExtractor, VectorFeatureExtractor
from nerds.features.char2vec import Char2VecFeatureExtractor
from nerds.features.doc2bow import BOWDocumentFeatureExtractor
from nerds.features.pos2vec import PoS2VecFeatureExtractor
from nerds.featur... |
import hexy as hx
import numpy as np
with open('input_day24') as f:
lines = [x.strip() for x in f.readlines()]
h = hx.HexMap()
for l in lines:
i = 0
dirs = []
while i < len(l):
if l[i] in ('s', 'n'):
dirs.append(l[i:i+2])
i += 2
else:
dirs.append(l[... |
# O(n*m)
# n = len(grid) | m = len(grid[0])
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
maxArea = 0
for y in range(len(grid)):
for x in range(len(grid[y])):
if grid[y][x] == 1:
maxArea = max(maxArea, self.explore(grid, y,... |
## USAGE: python /home/baldig/projects/genomics/crick/crick/scripts/create_job_script.py variables hidden layers dropout rate crickjob
import sys
import os
import math
from HebbianNetwork import monotone_generator
content = {}
variables = sys.argv[1]
count_vars = range(len(monotone_generator(variables)))
for i in r... |
from __future__ import annotations
import inspect
import os
import warnings
import param
from packaging.version import Version
__all__ = (
"deprecated",
"find_stack_level",
"PanelDeprecationWarning",
"PanelUserWarning",
"warn",
)
def warn(
message: str, category: type[Warning] | None = Non... |
from EMController import *
from Event import *
from EventMap import *
import generate
import kdtree
import random
from threading import Thread
print("**** TESTING EVENTMAP ****\n\n")
def get_input():
inp = input()
if inp == 'pass':
print("Test will be passed\n")
return 'pass'
else:
try:
n = int(inp)
re... |
from django.db import models
#from ckeditor.fields import RichTextField as HTMLField
from djangocms_text_ckeditor.fields import HTMLField
class Section(models.Model):
section = models.CharField(max_length=50)
section_slug = models.SlugField(unique=True)
display_count = models.IntegerField(default=3,help_te... |
# grid_world.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to Clemson University and the authors.
#
# Authors: Pei Xu (p... |
#Authors: Anna Godin & Kimberly Wolak
import Image
import numpy as geek
import PercentageTracker
def naive_bayes_face_training(face_image_data_training, face_image_data_testing, feature_size):
max = 0
total_num_faces = 0
total_num_not_face = 0
for image in face_image_data_training: # 5000
... |
import logging
from nwmaas.access import Authenticator, Authorizer
from nwmaas.communication import AbstractRequestHandler, FailedSessionInitInfo, Session, SessionInitFailureReason, \
SessionInitMessage, SessionInitResponse, SessionManager
from typing import Optional
logging.basicConfig(
level=logging.DEBUG,
... |
from flask_wtf import FlaskForm
from wtforms import FileField
from wtforms.validators import DataRequired, ValidationError
from flask_wtf.file import FileRequired, FileAllowed
ALLOWED_EXTENSIONS = {'jpeg', 'png', 'jpg'}
class ImageForm(FlaskForm):
image = FileField('image', validators=[DataRequired(
), FileR... |
from __future__ import print_function
import os
import shutil
import time
import pprint
import torch
import argparse
import numpy as np
import os
from torch.utils.tensorboard import SummaryWriter
import torch.nn.functional as F
from model.dataloader import dataset_dict
import torch
import torch.nn as nn
def rand_bbo... |
# Micropython implementation for the ESP8266:
# (Adapt as necessary for your chosen platform)
# This script uses the ssd1306 oled module.
# to switch off all display pixels:
# This file was created on 15/04/2017
# Author: George Kaimakis
import machine
import ssd1306
# define the display size:
width = 128 # pix... |
#!/usr/bin/env python
from lxml import etree
import argparse
import requests
import RPi.GPIO as GPIO
import time
class Servo:
def __init__(self, pin):
self.pin = pin
self.frequency = 100
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.pin, GPIO.OUT)
self.pwm = GPIO.PWM(self.pin, self.frequency)
self... |
import sys
from easydict import EasyDict as edict
sys.path.append("../..")
cfg = edict()
cfg.data = edict()
cfg.data.train_file = "/mnt/data/haomiao/4_Ass_09_train.csv"
cfg.data.test_file = "/mnt/data/haomiao/4_Ass_09_test.csv"
cfg.data.input_size = 104 * 2
cfg.solver = edict()
cfg.solver.batch_size = 32
cfg.solver... |
from requirements import *
class clean_data(object):
'''
CLASS clean_data()
It performs missing value detection for all the datasets, filling them with:
- mean for features with continuous variables;
- most frequent label for features with categorical variables.
Then it conver... |
import math
import datetime
import random
#物理用常数
N=20
kb=1.38e-23
J=1 #自旋耦合系数
Mu=1 #磁场耦合系数
#初始状态(随机状态)
stheta=[[[0.0 for k in range(N)] for j in range(N)] for i in range(N)]
for i in range(N):
for j in range(N):
for k in range(N):
stheta[i][j][k] =random.randint(0,180)/180.0*math.pi
sphi=[[[0.0 f... |
#coding=utf8
from django.db import models
class Address(models.Model):
name = models.CharField(max_length=20)
address = models.CharField(max_length=100)
pub_date = models.DateField()
|
import sys
import time
import argparse
import sqlite3
parser = argparse.ArgumentParser(description='Update the status of the '
'tasks specified by the supplied TaskIDs (over stdin/pipe).')
parser.add_argument('database')
parser.add_argument('newstatus')
args = parser.parse_args()
with sqlite3.Connection(args.... |
def pk_one_comp_model_parameters():
ka = 0.0867; Cl = 15.5; F = 1; Vc = 368
K = Cl / Vc
par = (ka, F, K)
return par
|
#!/usr/bin/python3
""" RESTful Api - use methods HTTP in amenities
"""
from api.v1.views import app_views
from models import storage
from models.base_model import BaseModel
from models.amenity import Amenity
from flask import jsonify, abort, Response, request
@app_views.route('/amenities', strict_slashes=False, metho... |
from __future__ import print_function
print("examplemodule2 being imported")
def example_function_2():
print("example_function_2 running")
if __name__ == '__main__':
print("examplemodule2 main running")
# this gets created by our setup script
try:
from .__version__ import __version__
exc... |
with open("opt.out", "r") as input_file:
freqs = []
for line in input_file:
if "incident light, reduced masses (AMU), force constants (mDyne/A)" in line:
break
for line in input_file:
if "Frequencies --" in line:
l = line.replace("\n","")
freqs.extend(l.sp... |
# pylint: disable=too-many-arguments
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
from hpdr.models import Spec
from hpdr import utils
from datetime import timedelta
standard_libra... |
import cv2
import dlib
import sys
from util import *
from Logger import Logger
import argparse
from pathlib import Path
from graph import save_ear_graph, save_microsleep_perclos_graph
import json
from multiprocessing import Process, Value, Pool, cpu_count
video_work_queue = []
detector = dlib.get_frontal_face_detect... |
import train
import csv
def getPredict(f):
predict_file = file(f)
p_reader = csv.reader(predict_file)
predict = []
for p in p_reader:
predict.append(int(p[1]))
return predict
def insertFeature(features,data,action):
if features.has_key(data[1]):
features[data[1]][31-data[-1]] = action[data[2]] + features[... |
# Generated by Django 3.0.3 on 2020-06-24 20:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clients_app', '0010_clientfile_clientfile'),
]
operations = [
migrations.RenameField(
model_name='client',
old_name=... |
import cv2
import random
import numpy as np
class Image():
def __init__(self, image_path, image_name='default'):
"""
image_path 为文件路径
image_name 为文件名称
"""
self.name = image_name
self.path = image_path
self.image = cv2.imread(image_path)
self.height = self.image.shape[0]
self.width = self.image.shap... |
import datetime
from ford_fulkerson import *
g = FlowNetwork()
for v in "sopqrt":
g.add_vertex(v)
g.add_edge('s','o',3)
g.add_edge('s','p',3)
g.add_edge('o','p',2)
g.add_edge('o','q',3)
g.add_edge('p','r',2)
g.add_edge('r','t',3)
g.add_edge('q','r',4)
g.add_edge('q','t',2)
a = datetime.datetime.now()
k = g.max_flo... |
import torch
import numpy as np
import pandas as pd
import os
from torch import nn
class Coin():
def __init__(self, Nx, Ny, x = None, y = None, vx = None, vy = None):
self.Nx = Nx
self.Ny = Ny
if x is None:
self.x = np.random.randint(Nx)
else:
self.x = x
if y is None:
self.... |
from django import forms
from django.forms import ModelForm
from .models import Account
class AccountForm(ModelForm):
class Meta:
model = Account
fields = '__all__'
exclude = []
labels = {}
help_texts = {}
form = AccountForm() |
import pytest
from django.forms.models import model_to_dict
from django.urls import reverse
from faker import Faker
fake = Faker("fi_FI")
@pytest.mark.django_db
def test_filter_form_is_template(django_db_setup, form_factory, admin_client):
form_factory(
name=fake.name(),
description=fake.sentence... |
# coding:utf-8
import sqlite3
conn = sqlite3.connect('database/test.db')
c = conn.cursor()
print('open database success')
sql = c.execute("SELECT id,name,salary FROM USER")
for row in sql:
print(row)
print('operation done successfully')
conn.close()
|
from mininet.topo import Topo
class Project2_Topo_0516045( Topo ):
def __init__( self ):
Topo.__init__( self )
# Add hosts
h1 = self.addHost( 'h1' )
h2 = self.addHost( 'h2' )
s1 = self.addSwitch( 's1' )
s2 = self.addSwitch( 's2' )
s3 = self.addSwitch( 's3' )
... |
from flask import Flask, request
from flask import render_template, jsonify
import json
from PItchContourSegmenter import extractPitch, segmentNotesFromPitch
from Song import Song
#import search
app = Flask("abzlabs", static_url_path="/static", static_folder="static")
app.debug = True
@app.route('/')
def index():
... |
from bs4 import BeautifulSoup
myHtml='''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>this is title from inty</title>
</head>
<body>
<h1>This is H1</h1>
<h1>这是另外一个H1</h1>
<h2>this is h2, 小一点的字体</h2>
<p> this is inty, i love you guys. yes!!!</p>
</body>
</html>'''
soup=BeautifulSoup(myH... |
from pyquery import PyQuery as pq
import requests
r = requests.get('http://www.cuiqingcai.com')
doc = pq(r.text)
print(doc('title')) |
#postprocessing for diffusion problem
from boutdata import collect
from boutdata import *
from boututils import *
import os
import subprocess
import matplotlib.pyplot as plt
from matplotlib import *
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
from numpy import *
from scipy import fft
Ni... |
import sys
sys.setrecursionlimit(1500)
# Recursive Fib
def fib(n):
if n < 2:
return 1
else:
return fib(n-1)+fib(n-2)
# print(fib(35))
# Memoization recursive call
fib_memo_dict = {}
def fib_memo(n):
if n in fib_memo_dict:
return fib_memo_dict[n]
if n < 2:
return_obj = 1
... |
import re
class Course(object):
DAYS = {'M': 0, 'T': 1, 'W': 2, 'TH': 3, 'F': 4, 'S': 5}
def __init__(self, unique, days, hours, room, instructor):
self.unique = unique
self.days = days
self.hours = hours
self.room = room
self.instructor = instructor
def __hash__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.