text stringlengths 38 1.54M |
|---|
from django.urls import path
from listings import views as listings
from enquiries import views as enquiries
urlpatterns = [
path('', listings.houses, name="houses"),
path('house/addhouse/<int:user_id>', listings.addhouse, name="addhouse"),
path('house/preview_house/<int:user_id>/<int:house_id>', listings.... |
"""
Author: Franklin Floresca
Date: July 1, 2017
About: A simple game of hangman where a user has a maximum of 6 failed attempts to guess the correct letters for a word.
Note: The following code was written following the directions as laid out by Albert Sweigart in one of his Invent With Python books.
"""
import r... |
def CheckIfInteger(num):
if (num**(.5))%1 == 0:
print "True (",num,"is equal to an integer to the second power)\n"
else:
print "False (",num,"is equal to a float to the second power)\n"
flag="y"
while flag!="n":
num = input("Give a number...\n")
CheckIfInteger(num)
flag=raw_input("... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.SignMerchantParams import SignMerchantParams
class AgreementSignParams(object):
def __init__(self):
self._buckle_app_id = None
self._buckle_merchant_id = None... |
class AB:
def createString(self, N, K):
num_a = N//2
num_b = N-num_a
if K > N//2*(N-N//2):
return ""
# Num of b's after a's
counter = K//num_a
leftover = K%num_a
prefix = (num_b-counter-1)*"B"+leftover*"A"+"B" if counter < num_b else ""
# p... |
"""CNN - LSTM config system
This file specifies deafoult congig options for the model used.
You should not change this file: is recommended copy and paste in other config.py file the own configuration and replace it in this folder.
"""
from utils.collections import AttrDict
__C = AttrDict()
#Users can get the confi... |
import pygame
import random
import os
bus_texture = pygame.image.load(os.path.join("images/bus.png"))
class Player:
def __init__(self, surf):
self.surf = surf
self.image = bus_texture
self.rect = self.image.get_rect()
self.jump_speed = 3
self.jump_height = s... |
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from products.models import Products, ProductImage, ProductCategories, ProductReview, ProductRating, SearchHistory
from cart.models import ShoppingCart, CartItem
from django.db.models import Sum, F
class DataContainer():
de... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 26 09:04:13 2020
@author: luol2
"""
import time
import sys
import numpy as np
from nn_represent import CNN_RepresentationLayer,BERT_RepresentationLayer
from keras.layers import *
from keras.models import Model
from keras_bert import load_trained_model_from... |
##DRILL:
##Drill Description:
##For this drill, you will need to write a script that creates a database and adds new data
##into that database.
##
##Requirements:
##Your script will need to use Python 3 and the sqlite3 module.
##
##Your database will require 2 fields, an auto-increment primary integer field and a field... |
"""
This file screen scraps the yahoo website and gathers
all stock ticker symbols for a given industry. You specify
which industry you're interested in in the INDUSTRIES list
The output will be a file in the data directory, 1 file
per industry with company name along with it's ticker symbol
"""
import urllib2
... |
#!/usr/bin/python3.8
import json, os
import time, datetime
from datetime import datetime
import tarfile as tf
cdir = os.path.dirname(os.path.abspath(__file__))
nowt = datetime.now()
logtime = nowt.strftime("%Y-%m-%d [%H:%M]")
print(logtime + ' backup started...')
# set the filename of the archive file...
tgzfile =... |
accepted = "✅"
pending = "⏳"
disputed = "❌"
trophy = "🏆"
first_place = "🥇"
second_place = "🥈"
third_place = "🥉"
thumbs_up = "👍"
thumbs_down = "👎" |
# *****************************************************************************
# © Copyright IBM Corp. 2018. All Rights Reserved.
#
# This program and the accompanying materials
# are made available under the terms of the Apache V2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/l... |
"""
First pass at a stimulus model for abstracting the qualities and functionality of a stimulus
into an abstract class. For now, we'll assume the stimulus model only pertains to visual
stimuli on a visual display over time (i.e., 3D). Hopefully this can be extended to other stimuli
with an arbitrary number of dime... |
#set: order in which items appear can be inconsistent
# mutable (can be changed)
# add items with .add
#dictionaries: add items with .append
# |
#!/usr/bin/env python
# encoding: utf-8
"""
ugly-number.py
Created by Shuailong on 2016-02-03.
https://leetcode.com/problems/ugly-number/.
"""
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
# if num == 1:
# return True
... |
'''
Your plane lands with plenty of time to spare. The final leg of your journey is a ferry that goes directly to the tropical island where you can finally start your vacation. As you reach the waiting area to board the ferry, you realize you're so early, nobody else has even arrived yet!
By modeling the process peopl... |
from threading import Thread
from time import time
import cv2
import numpy as np
from PIL import Image
from tqdm import tqdm
from yolov4 import Detector, MultiGPU
c = 0
def target(g, desc):
global c
for _ in range(1000):
# print(desc)
g.perform_detect(show_image=False)
if c % 100 ==... |
"""
Django settings for vulfocus project.
Generated by 'django-admin startproject' using Django 2.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
i... |
from wasted.models import activity
from rest_framework import viewsets
from wasted.serializers.activity import ActivitySerializer
from django.core.exceptions import SuspiciousOperation
from django.forms.models import model_to_dict
from rest_framework.response import Response
from rest_framework.decorators import list_r... |
from vpython import *
p = vector(0.6, 0, 0)
b = sphere(pos=vector(5,0,0),color=color.blue,redius=.25,make_trail=True)
w = sphere(pos=b.pos+p,redius=0.1)
r = sphere(color=color.red,redius=0.9)
while True:
rate(50)
b.pos = rotate(b.pos, angle=0.001,axis=vector(0,2,1))
p = rotate(p, angle=0.013,axis=vector(0,... |
from django.urls import path
from . import views
from .views import WorkflowViewSet
urlpatterns = [
path('workflow/', WorkflowViewSet.as_view({
'get': 'list',
'post': 'create',
})),
path('workflow/<str:pk>', WorkflowViewSet.as_view({
'patch': 'partial_update',
})),
path('w... |
n = int(input())
s = [input() for s in range(n)]
dic = {}
for i in range(n):
if not s[i] in dic:
dic[s[i]] = 1
else:
dic[s[i]] += 1
cnt_max = max(dic.values())
ans = []
for j in dic.keys():
if dic[j] == cnt_max:
ans.append(j)
ans.sort()
for h in range(len(ans)):
print(ans[h])
|
#Sean McGlincy
# Machine Learning
# HW 2
# Requires
# Running Python 3.6
# Linux: sudo yum install tkinter python36u-tkinter
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
#################################################################################################... |
from GPUtil import showUtilization as gpu_usage
import pdb
import os
import time
import random
from itertools import permutations
import argparse
import pickle
import numpy as np
import pandas as pd
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from perm_df import PermDF, WreathDF
from... |
from tkinter import *
from tkinter.filedialog import askopenfile
from tkinter import messagebox
master=Tk()
def cmd1():
lb1.configure(text="acadview")
def cmd2():
a=askopenfile()
def calculate():
a=w1.get()
b=w2.get()
messagebox.showerror(('info',str(a)+""+str(b)))
menu= Menu(master)
master.con... |
import os, sys
file_path = os.path.dirname(os.path.abspath(__file__))
if not (file_path in sys.path):
sys.path.append(file_path)
from get_caller import get_caller
from authorized import authorized_functions
def check_caller_authorization():
caller = get_caller(3)
if caller in authorized_functions:
... |
import requests as req
def get_spell(spell_name, level):
spell = req.get("https://www.dnd5eapi.co/api/spells/" + spell_name)
spell_json = spell.json()
print(spell_json['damage'])
try:
return '' + spell_json['damage']['damage_at_slot_level'][f"{level}"] + ':' + \
spell_json['dam... |
#!/usr/bin/env python
import random
# Variables (Pyright reportUnboundVariable [E] "..." is possibly unbound)
restartGame = ''
restartMessage = '''
=================== Restart ===================
'''
rangeStart = 1
rangeEnd = 20
print('Hello. What is your name?')
userName = input()
def guessANumber():
'''Game. Ask... |
from django import forms
from .models import User
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = {'first_name','last_name','email','password','username'}
labels = {'first_name':'First Name','last_name':'Last Name','email':'Email','password':'Password','username':'Username'}
widgets = {
'... |
# Copyright 2020 (author: Meng Wu)
import io
import pynini
from .utils import DataIO, make_context_fst, update_wd_table
from .tokenizer import Tokenizer
from .common import list2fst
class UserTableReader(DataIO):
def __init__(self, encode="utf-8", split_space=" ", wd_table_path="test_data/words.txt", \
... |
print("pyDEBUG: importing select")
import select
print("pyDEBUG: select imported")
print("pyDEBUG: creating poller object")
poller = select.poll()
print("pyDEBUG: polling with timeout of 2")
poller.poll(2000)
print("pyDEBUG: polling finished")
print("pyDEBUG: polling with timeout of 1")
poller.poll(1)
print("pyDEBUG... |
"""
this file tests the creation of a new scene
"""
def test_new_scene(setup, init_root, default_scene_name, scene_root, history_db):
"""
tests creating a new scene. depends on setup.
"""
from src.praxxis.scene import new_scene
from src.praxxis.scene import delete_scene
import os
scene_... |
import docplex.mp.model as cpx
import pandas as pd
import numpy as np
import sys, os
import json
###################################################################################################
options = pd.read_csv("data/filtered_tsla_options_w_greeks.csv")
options = options[options.date_current == "2020-07-13"]
... |
import glob
import multiprocessing
import numpy as np
import os
import PIL as pil
import re
import sys
sys.path.append('./../transformer')
import transformer.transform_policy as transform_policy
from functools import partial
from multiprocessing import Pool
from random import shuffle
def _convert_label_to_integer(t... |
from inspect import isfunction
class Node(object):
"""
node
"""
def __init__(self, value, next=None):
self.value = value
self.next = next
def initNode(value, next):
"""
:param value:
:param next:
:return: LinkList
"""
return Node(value, nex... |
while True:
try:
a = input().split(':')
calc = ((int(a[0]) * 60) + int(a[1])) + 60
if calc <= 480:
print('Atraso maximo: 0')
else:
print('Atraso maximo: {}'.format(calc-480))
except:
break
|
class sample:
x = 10
@classmethod
def modify(cls):
cls.x = cls.x + 1
s1 = sample()
s2 = sample()
print 'x in s1 = ', s1.x
print 'x in s2 = ', s2.x
s1.modify()
print 'x in s1 = ',s1.x
print 'x in s2 = ',s2.x
|
import sys
import os
import couchdb
from Bio import SeqIO
def main(argv):
# Put stuff in JSON config file
couchServer = 'http://localhost:5984/'
couchDB = 'testseq'
couch = couchdb.Server(couchServer)
# In case admin permissions
# couch.delete(couchDB)
# couch.create(couchDB)
db = couch[couchDB]
... |
import os
import subprocess
class StringToCombinations:
def __init__(self):
self.combinations = []
self._raw_str = '''
aix ppc64
android 386
android amd64
android arm
android arm64
darwin 386
darwin amd64
darwin arm
darwin arm64
dragonfly amd64
freebsd 386
freebsd amd64
freebsd arm
illumos amd64
j... |
import time
import requests
import json
# fin = time.strftime("%Y%m%d%H%M%S", time.localtime())
# fund = fin + str(1)
loanAmount = [4000,60000]
loanTerm = [12,18]
repayMode = [3,4,5,6,9,10]
livingCity = [110100,120100]
# print (loanAmount)
# print (loanTerm)
# print (repayMode)
# print (livingCity)
# print(fin,fund)... |
primes = range(2, 2501)
for i in range(2, 8):
primes = list(filter(lambda x: x == i or x % i, primes))
print(primes)
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
class Block(nn.Module):
def __init__(self, insize, outsize):
super(Block, self).__init__()
self.layers = nn.Sequential(
nn.Conv2d(insize, outsize, kernel_size=3, padding=1, bias=... |
# -*- coding: utf-8 -*-
from django.test import TestCase
from .. import factories
from .. import models
from .. import utils
class CreateLogEntryTests(TestCase):
def setUp(self):
self.game = factories.GameFactory(cash=0)
self.alice, self.bob = factories.PlayerFactory.create_batch(size=2,
... |
### area.py
## Calcular área de um terreno
# Funções
def area(larg, prof): # recebe largura e profundidade
return larg*prof
largura = float(input("Largura (m): "))
profundidade = float(input("Profundidade (m): "))
print(f"A área do terreno {largura}x{profundidade} é de {area(largura, profund... |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
# generate some data
x = np.arange(0, 100, 0.01)
# indices = range(0,10000, 101)
# x1 = np.take(x, indices)
# x1 = x[::10].copy
x1 = x[:1000]
y = np.sin(x)
cll = np.random.randn(len(x))
plt.style.use(['dark_background'])
# plot it
fig = plt.fig... |
def digits(N):
digs = []
if N == 0:
return [0]
while N > 0:
digs += [N%10]
N = N//10
return digs
def lastNum(N):
if N == 0:
return "INSOMNIA"
else:
i = 2
digs = digits(N)
while len(digs) < 10:
digs += digits(N*i)
d... |
from django import forms
from protwo.models import User
class NewUserForm(forms.ModelForm):
class Meta:
model = User
fields = ['first_name','last_name']
|
import matplotlib.pyplot as plt
import json
# 此方法主要进行有效行数的可视化分析,target_dim为目标题型
# 要检查的题型,树图题目
plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文
target_dim = 'dim1'
lines = []
src_path = r'E:\0000ProfessionalClass\2_2nd\SMSE\OnGitHub\BigJob\indicators_of_four_dim_filtered.json'
with open(src_path, "r") as fp:
... |
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from PhoneBook import PhoneBook
if __name__ == '__main__':
phoneBook = PhoneBook()
phoneBook.setAllData()
phoneBook.getAllDataInJson()
phoneBook.exportDataInJson()
del phoneBook
|
import os
import json
import argparse
from agent import Agent
def main():
args = parse_command_line_args()
config = load_config(args.experiment)
A = Agent(config)
A.run()
def load_config(experiment):
with open("./config/" + str(experiment) + ".json") as json_file:
config = json.load(json... |
from django.conf.urls.defaults import *
urlpatterns = patterns('ts.traders.views',
(r'^logout.html$', 'logout_view'),
(r'^transactions.html$', 'transactions'),
(r'^editdetails.html$', 'editdetails'),
(r'^$', 'account')
)
|
def payingOffInAyear(balance, annualInterestRate):
monthlyInterestRate = annualInterestRate / 12
payment = 10
while balance > 0:
bal = balance
for i in range(12):
unpaidBalance = bal - payment
bal = unpaidBalance + unpaidBalance*monthlyInterestRate
if bal <= 0... |
import time
link = "http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/"
def test_find_a_button(browser):
browser.get(link)
button_count = len(browser.find_elements_by_css_selector("#add_to_basket_form > button"))
time.sleep(5)
assert button_count == 1
|
import math as _math
import numpy as _np
def my_function(a, b):
'''Here is a Google style Sphinx docstring
Args:
a (float): Description of variable a
b (:obj:`numpy.ndarray`): Description of variable b
Returns:
c (:obj:`numpy.ndarray`): Here's the first argument that this returns.... |
#!/usr/bin/env conda run -n jpandas python
# -*- coding: utf-8 -*-
import params
import pandas as pd
from . import prd_funcs as func
def main(input_folder, output_folder):
# read csv file
file_emp = input_folder + 'post_emp.csv'
file_GDP = input_folder + 'post_GDP.csv'
df_emp = pd.read_csv(file_emp)
... |
"""
tagplay.py
refactored based on Jukebox Activity
Copyright (C) 2007 Andy Wingo <wingo@pobox.com>
Copyright (C) 2007 Red Hat, Inc.
Copyright (C) 2008-2010 Kushal Das <kushal@fedoraproject.org>
Copyright (C) 2010 Walter Bender
"""
# This program is free software; you can redistribute it and/or
# modify it under... |
#/usr/bin/env python3
import click
import logging
import pandas as pd
# locals
from arxiv_connections import (graphing, arxiv_util)
# TODO - save the authors and things optionally
# TODO - save the plot optionally
# TODO - consider different ways of sorting received articles
stream_handler = logging.StreamHandler()
... |
# Copyright 2019- d3p Developers and their Assignees
# 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 a... |
# Author : Sheena Elveus
# Date: May 17 2017
# Description : Main Python file to generate blog site
import os
import jinja2
import webapp2
import datetime
from utils import *
from models.user import *
from models.blogpost import *
from models.comment import *
from models.likes import *
from models.unlikes import *
fr... |
import torch
class MDSEmbeddingReader():
def __init__(self):
self.document_set_ids = []
self.document_ids = []
self.sentence_ids = []
self.texts = []
self.labels = []
self.lengths = []
self.embeddings = []
def read(self, json_data):
docset_ids = ... |
import dataclasses
import json
import typing
from typing import List, Optional, Tuple, Union
KEY = 'key'
@dataclasses.dataclass
class Base:
def __post_init__(self):
self.__dataclass_fields__ = {
field_name: self.__dataclass_fields__[field_name]
for field_name in self.__dataclass_... |
import random
class town:
def __init__(self, loc, map, controller):
self.name = 'DeathTown 2K11'
self.loc = loc
self.map = map
self.size = (map[len(map)-1][0]-map[0][0]+1,map[len(map)-1][1]-map[0][1]+1)
self.controller = controller
self.houses=[]
def get_population(self):
for pos in self.map:
... |
"""This module includes methods for training and predicting using naive Bayes."""
import numpy as np
import math as math
def naive_bayes_train(train_data, train_labels, params):
"""Train naive Bayes parameters from data.
:param train_data: d x n numpy matrix (ndarray) of d binary features for n examples
... |
from launch import LaunchDescription
from launch.substitutions import PathJoinSubstitution
from launch_ros.actions import Node
from launch_ros.substitutions import FindPackageShare
def generate_launch_description():
joystick_driver_node = Node(
package='joystick_package',
executable='joys... |
"""Heatmap and dendograms"""
import warnings
import scipy.cluster.hierarchy as hierarchy
import scipy.spatial.distance as distance
import easydev
__all__ = ['Linkage']
class Linkage(object):
"""Linkage used in other tools such as Heatmap"""
def __init__(self):
""".. rubric:: constructor
:p... |
from django.http import HttpResponse
from django.shortcuts import redirect
def admin_only(view_func):
def wrapper_function(request, *args, **kwargs):
user = request.user
if user.is_authenticated and user.is_superuser:
return view_func(request, *args, **kwargs)
else:
return HttpResponse('You are not author... |
import collections
from typing import List
from django.contrib.auth.models import User
from . import models
def get_solutions(contest: models.Contest, user: User) -> List[models.Solution]:
return list(models.Solution.objects.filter(user=user, problem__contests=contest).prefetch_related("problem"))
def get_cor... |
import os
include('../../../ropdb/DB.py')
add_word(HEAP_STAHED_DEST+0x4)
add_word(0)
add_word(0)
add_word(PIVOT_2)
add_word(PIVOT_4)
add_word(MEMCPY)
add_word(PIVOT_3)
add_word(os.path.getsize('../../../rop/build/rop_loader.bin')+0x24) #memcpy size
add_word(PIVOT_1)
org(0x8C)
add_word(HEAP_STAHED_DEST)
|
# Different endpoints for server, functions, and definitions for logic
import datetime
from flask import request, jsonify
from fitness_tracker import app
# Imports User model from database
from fitness_tracker.models import User, LoggedWorkout
from fitness_tracker.manage import db
# This points the app towards the ng... |
from __future__ import print_function
import os
import glob
import subprocess
import fnmatch
def combine_cards(model_dir):
base_dir = os.path.dirname(os.path.dirname(model_dir))
datacards = []
for root,dirs,files in os.walk(os.path.join(model_dir,"datacards")):
for f in files:
if fnmat... |
import frida, sys
def on_message(message, data):
if message['type'] == 'send':
print("[*] {0}".format(message['payload']))
else:
print(message)
def main():
js_code = """
function showStacks() {
Java.perform(function () {
send(Java.use("android.util.Log").getStackT... |
from django.db import models
class CommunityPerson(models.Model):
ROLE_CHOICES = (
('leader', 'ผู้นำชุมชน'),
('wise_man', 'ปราชญ์ชุมชน'),
)
name = models.CharField(null=False, blank=False, max_length=150)
role = models.CharField(
null=False,
blank=False,
choice... |
from pymongo import MongoClient, errors
from pprint import pprint
import zlib
client = MongoClient('localhost', 27017)
db = client['mails_db']
mails_db = db.mails
db2 = client['goods_db']
goods_db = db2.goods
def make_hash(item):
return zlib.adler32(bytes(repr(item), 'utf-8'))
def save_mails_to_db(mails_list)... |
from datetime import datetime
from sqlalchemy import Column, Boolean, DateTime, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_property
from cause.api.management.core.multilang import MultiLang
from cause.api.management.models.language_content import ... |
from datetime import datetime
file_path = 'C:/Users/John/PycharmProjects/corey_schafer_oops/data/'
class WriteFile(object):
def __init__(self, file_name, writer):
self.fh = open(file_path+file_name, 'a+')
self.formatter = writer()
def write(self, input):
self.fh.write(self.formatter.f... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os, sys
from PIL import Image
accepted_formats = [
".gif",
".jpg", ".jpeg", ".jfif", ".jfi", ".jp2", ".j2c",
".png",
".tiff", ".tif",
".webp",
".bmp"
]
class ImageFactory():
def __init__(self, file):
super().__init__()
pri... |
#
# Definicao de metodos utilitarios
#
import sys
import AgentU
import ConfigU
import ConstantsU
import GlobalsU
import FieldU
import PriorityQueueU
from math import sqrt
from time import sleep
from optparse import OptionParser
from random import randrange
def ParseOption():
err = False
parser = OptionParse... |
from selenium import webdriver
from selenium.webdriver.common.by import By
browser = webdriver.Chrome()
button = browser.find_element(By.ID, "submit_button") |
"""Class containing the gpu execution function.
Use: Initialize with no argument to let pycuda compile the kernel, then call exec() with the array of inputs, the
size of all outputs, and the NEAT network to use. Be sure to look at the function definition for the specific
type for the input.
"""
... |
# -*- coding: utf-8 -*-
import frst_zverzeichnis
import frst_zgruppedetail
import frst_personemailgruppe
import frst_persongruppe
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : print_.py
# @Author: ly
# @Date : 2018/12/15
def func_():
def func1():
print(456)
return func1
print(func_())
|
from expertai.nlapi.cloud.client import ExpertAiClient
client = ExpertAiClient()
def get_normalized_terms(text):
output = client.specific_resource_analysis(
body={"document": {"text": text}},
params={'language': 'en', 'resource': 'relevants'
})
term_magnitude = sum([x.score**2 for x in o... |
import sys
sys.stdin = open('7465_무리의개수.txt','r')
def go(person):
for next_person in range(1,N+1):
if relation[person][next_person] == 1 and connected[next_person] != True:
connected[next_person] = True
go(next_person)
tc = int(input())
for case in range(1,tc+1):
N,M = map(i... |
from flask import Flask, Response, request
from twilio.twiml.messaging_response import Message, MessagingResponse
app = Flask(__name__)
@app.route("/twilio")
def check_app():
# returns a simple string stating the app is working
return Response("It works!"), 200
@app.route("/twilio", methods=[... |
from django.db import models
import uuid
from django.contrib.auth.models import User
import os
from django.core.validators import MaxValueValidator, MinValueValidator
from django.utils import timezone
from datetime import datetime
import accounts.models
def make_uuid():
return str(uuid.uuid1().int >> 64)
class... |
n=int(input())
ar=[int(i) for i in input().split()]
s=ss=10000000
for item in ar:
if item<=s:
ss=s
s=item
elif s<item<ss:
ss=item
print(ss) |
#from SBaaS_LIMS.lims_quantitationMethod_postgresql_models import *
#from .lims_msMethod_query import lims_msMethod_query
from SBaaS_LIMS.lims_calibratorsAndMixes_query import lims_calibratorsAndMixes_query
class lims_quantitationMethod_query(lims_calibratorsAndMixes_query,
#lims_ms... |
# coding=utf-8
'''
Author: ripples
Email: ripplesaround@sina.com
date: 2020/3/25 15:01
desc:
'''
# 发送端
import socket
import sys
# 调用实验1 中的CRC
sys.path.append('../实验1/python')
from CRC import *
import time
import _thread
import threading
UDPPort=8888
FilterError=10
FilterLost=10
client = socket.socket(socket.AF_INET... |
# Copyright (C) 2012 Yahoo! Inc.
#
# Author: Joshua Harlow <harlowja@yahoo-inc.com>
#
# This file is part of cloud-init. See LICENSE file for license information.
"""Write Files: write arbitrary files"""
import base64
import os
from textwrap import dedent
from cloudinit.config.schema import (
get_schema_doc, val... |
# Library imports
import dateutil.parser
from datetime import timedelta, datetime
from flask import Flask, render_template, jsonify, request
from flask_restful import Api, Resource
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.hybrid import hybrid_method
from sqlalchemy_serializer import SerializerMixin
f... |
# coding: utf-8
"""
Defect Dojo API
To use the API you need be authorized. # noqa: E501
The version of the OpenAPI document: v2
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import openapi_client
from openapi_client.api.tool_product_setti... |
# coding: utf-8
import traceback
import signal
from powermeter import qt
from powermeter.monitor import Monitor
from powermeter.calibrate import Calibrate
from powermeter.visualize import Visualize
from powermeter.signature import Signature
from powermeter.disaggregate import Disaggregate
__all__ = ("PowerMeter", "q... |
import tensorflow as tf
import numpy as np
import os
import random
import time
from utils import *
from networks import multi_column_cnn
from configs import *
import cv2 as cv
np.set_printoptions(threshold=np.inf)
def train():
set_gpu(1)
dataset = 'A'
# training dataset训练数据集
img_root_dir = r'D:/peop... |
"""
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
1 <= n <= 20
"""
class Solution:
def generateMatrix(self, n: int) -> List[List[i... |
#!/bin/python3
import os
print("Welcome to installation script")
to=input("Set instalation directory (default /usr/bin):")
if to=="":
to="/usr/bin"
file = open("FILES.TXT")
m={}
if not os.path.isdir(to):
print(f"Make directory {to}")
os.makedirs(to)
for i in file.readlines():
i=i[0:-1]
print(f"Copy ... |
from collections import defaultdict
import numpy as np
import math
LEFT = 0
DOWN = 1
RIGHT = 2
UP = 3
class FA:
def __init__(self, alpha, epsilon, discount, env):
"""
FA Agent
Instance variables
- self.epsilon (exploration prob)
- self.alpha (learning rate)
- s... |
"""empty message
Revision ID: f13a99943e85
Revises: dc93e5f99ead
Create Date: 2017-01-31 17:25:37.060549
"""
# revision identifiers, used by Alembic.
revision = 'f13a99943e85'
down_revision = 'dc93e5f99ead'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic ... |
#!/usr/bin/env python
# __Author__:cmustard
import importlib.util
import re
import os
import sys
from multiprocessing import Pool
from util.comm import getLogger, printInfo
from util.config import CLASSNAMEREGX, PLUGIN_CLASSNAME_REGEX
LOGGER = getLogger()
PLUGIN_ROOT = "../fingerprint/"
class CmsDector():
def ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.