text stringlengths 38 1.54M |
|---|
# Contains read time suggestion algorithms
from util.pewma import Pewma
import math
import numpy as np
class ReadTimeSuggestionAlgorithm:
""" Read time suggestion dummy class. """
def next(self, t, v): raise NotImplementedError("next(...) not implemented.")
class Periodic(ReadTimeSuggestionAlgorithm):
... |
# remove particular elements from list
list1=[1,4,6,5,9,7,4]
num=int(input("which itom idex do you want to remove"))
list1.pop(num)
print(list1)
|
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more informatio... |
from django.shortcuts import render
from django.http import HttpRequest
from .models import Game
# Create your views here.
def index(request: HttpRequest):
return render(request, "regency_app/index.html", context={})
def join_game(request: HttpRequest):
games = Game.objects.order_by("-start_date")[:5]
return r... |
import math
def stdDevOfLengths(L=None):
"""Return the standard deviation on the length of strings.
Expects L to be a list.
Returns standard deviation
Returns 'NaN' if the list is empty
"""
if not L or len(L) < 1:
return float('NaN')
# Get the mean of the length of t... |
# Misc. Helper Functions
from functools import wraps #for login_required
from flask import session
"""If user isn't logged in, they will be redirected away from
certain pages back to home"""
def login_required(f):
@wraps(f)
def is_logged_in(*args, **kwargs):
if 'logged_in' not in session:
return redirect(url_f... |
# -*- coding: utf-8 -*-
# __author__ = 'Gz'
from basics_function.golable_function import MD5
import time
import copy
import requests
import json
import threading
class FiveNut:
def __init__(self, fail_list):
self.salt = "3*y4f569#tunt$le!i5o"
self.fail_list = fail_list
self.time_stamp = i... |
# coding: utf8
from urbvan_framework.schemas import (BaseResponseSchema, BaseBodySchema)
from urbvan import permissions
def render_response_error(errors={}):
list_errors = []
for key, value in errors.items():
if type(value) is list:
value = {"message": value[0]}
value.update({"fie... |
from Grid import *
from Inputs import *
from NeuronKohonen import *
if __name__ == '__main__':
#ustawienia i parametry sieci neuronowej
learningRate = 0.1
epoch = 100
noOfInputs = 4
width = 20
height = 20
inputs = Inputs() #utworzenie danych wejściowych
"""Przypisanie danych róz... |
from django.contrib import admin
from modeltranslation.admin import TranslationAdmin
from dictionaries import models
from dictionaries.forms import DefaultElementAdminForm
from grappelli_orderable.admin import GrappelliOrderableAdmin
class SizeAdmin(GrappelliOrderableAdmin):
list_display = ('size',)
class Def... |
from django.db import models
class contect(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
phone = models.CharField(max_length=13)
text = models.TextField(max_length=500)
timestamp = models.DateTimeField(auto_now_add=True, blank=True)
def __str... |
#!/usr/bin/env python3
import argparse
import json
# This is the location of the IaaS swagger
old_filename = "swagger/vra-iaas.json"
new_filename = "swagger/vra-iaas-fixed.json"
def replace_value(d, k, v, new):
if k in d and d[k] == v:
print(d[k])
print("found one")
d[k] = new
for c... |
#!/usr/bin/python
from django.core.management import setup_environ
import settings
setup_environ(settings)
import time
import logging
import statgrab
from status.models import *
kb = 1024
mb = kb * kb
while True:
### Host data ###
cpu = statgrab.sg_get_cpu_percents()
load = statgrab.sg_get_load_stats()... |
# -*- coding: utf-8 -*-
import multiprocessing
import glob
from eod import rewrite_data
import ipdb
import os
import xarray as xr
import numpy as np
import pandas as pd
from utils import constants as cnst, u_met
from scipy.interpolate import griddata
def saveDaily():
files = glob.glob('/prj/AMMA2050/CP4/histor... |
from django.shortcuts import render,redirect
from .models import Log
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.decorators import permission_required
from django.shortcuts import get_object_or_404
from djang... |
from typing import Union
from numpy import asarray
from itertools import zip_longest
def nonelen(l):
return 0 if l is None else len(l)
def noneratio(x,y):
return None if x is None or y is None else x/y
def nonecast(x,fill_value=0.0):
if x is not None:
return [xj if xj is not None else fill_val... |
''' programa 0
un programa que nos pida el nombre
y que te responda
encantado de conocerte'''
nombre = input('¿Cómo te llamas?')
print('encantado de conocerte,',nombre)
cont = 0
while cont <= 9:
print('hola', nombre, cont)
cont = cont + 1
|
#!/usr/bin/python3
'''
@author: Edgar D. Arenas-Díaz
'''
from optparse import OptionParser
import subprocess
import os
def main():
parser = OptionParser()
parser.add_option("-s", "--source-path", dest="srcpath", metavar="SRCPATH",
help="Path to source files")
parser.add_option("-f",... |
# import basic packages
import cv2, torch, types
import numpy as np
from numpy import random
# import pytorch packages
from torchvision import transforms
import torchvision.transforms.functional as FT
# for normalize / resize / to_tensor
class ToTensor(object) :
def __call__(self, image, boxes=None, labels=None, di... |
#coding=utf-8
def produce_entity_index(entity2idPath,DB_id_index_Path,allDBIdexPath):
idMap=dict()
with open(entity2idPath,encoding='utf-8') as f:
line=f.readline().strip('\n')
while line:
id=line.split(' ')[0][3:]
index=int(line.split(' ')[1])
... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import psycopg2
class Pipeline1(object):
def __init__(self):
# db_path = os.path.dirname(os.path.dirname(os.path.... |
from jenkspy import jenks_breaks
from Tools.Encoders.Encoder import Encoder
from numpy.random import RandomState
from typing import List
import numpy as np
class NaturalSplineEncoding(Encoder):
""" Natural Spline Encoding encodes every feature individually as piecewise cubic spline with the following
requireme... |
import numpy as np
import json
import os
from keyvalue import STORE
from util import quickhash
from run import run_deeprole
def proposal_to_bitstring(proposal):
result = 0
for p in proposal:
result |= (1 << p)
assert result < 32
return result
def bitstring_to_proposal(bitstring):
result ... |
from bigml.api import BigML
api = BigML()
source1 = api.create_source("iris.csv")
api.ok(source1)
dataset1 = api.create_dataset(source1, \
{'name': u'iris'})
api.ok(dataset1)
cluster1 = api.create_cluster(dataset1, \
{'name': u'iris'})
api.ok(cluster1)
centroid1 = api.create_centroid(cluster1, \
{u'peta... |
first = 'Ben'
last = 'Wollen'
message = first + ' [' + last + '] is a coder'
print(message)
msg = f'{first} [{last}] is a coder'
print(msg)
|
"""
cnet.py (see network)
Check to see if you are connected to the internet and make sure your ip address
is in the set ip_whitelist.
(Originally designed for Linux Mint MATE v19.1.)
"""
import socket
import subprocess
import time
import logging
ip_whitelist = set()
#ip_whitelist.add('')
def internet(host = '8.8.8... |
#
# [794] Swim in Rising Water
#
# https://leetcode.com/problems/swim-in-rising-water/description/
#
# algorithms
# Hard (44.29%)
# Total Accepted: 3.1K
# Total Submissions: 6.9K
# Testcase Example: '[[0,2],[1,3]]'
#
# On an N x N grid, each square grid[i][j] represents the elevation at that
# point (i,j).
#
# Now... |
# coding:utf-8
import html_downloader, position_outputer, positionInfo_parser
position = positionInfo_parser.PositionInfo_Parser().parse("http://campus.chinahr.com/job/120396.html",
"company_test_uuid")
# 职位所属公司uuid
print "company_uuid:" + position.company_uui... |
from abc import abstractmethod
class CoinHandlerBase:
def __init__(self):
_successor = CoinHandlerBase()
self._successor = _successor
@abstractmethod
def handle_coin(self, coin):
pass
def set_successor(self, successor):
self._successor = successor
|
import random
deck_of_cards = [i for i in range(2,11) for num in range(4)]
loser_deck = []
#random.seed(42)
random.shuffle(deck_of_cards)
player1_cards = [card for index, card in enumerate(deck_of_cards) if index % 2 == 0]
player2_cards = [card for index, card in enumerate(deck_of_cards) if index % 2 == 1]
p... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... |
# Import libraries
import numpy as np
from flask import Flask, request, jsonify
from deeppavlov import build_model, configs
app = Flask(__name__)
# Load the model
model = build_model(configs.squad.squad, download=False)
@app.route('/ques',methods=['POST'])
def predict():
# Get the data from the POST requ... |
# This file is a part of pyctr.
#
# Copyright (c) 2017-2021 Ian Burgwin
# This file is licensed under The MIT License (MIT).
# You can find the full license text in LICENSE in the root of this project.
from functools import wraps
from typing import TYPE_CHECKING, NamedTuple
from ....common import PyCTRError
from ....... |
import requests
import sys
import shutil, os
from django.shortcuts import render
from subprocess import run,PIPE
from django.core.files.storage import FileSystemStorage
from cv2 import cv2
def button(request):
return render(request,'index.html')
def external(request):
image = request.FILES['image']
... |
from django.contrib import admin
from cars.models import Car, SoldCar
class CarAdmin(admin.ModelAdmin):
date_hierarchy='end_time'
search_fields=['plate','brand']
list_display = ['id', 'plate', 'brand','end_time' ]
admin.site.register(Car, CarAdmin)
admin.site.register(SoldCar ,CarAdmin)
|
class foo():
'''填写描述'''
def set(self):
pass
print(foo().__doc__)
a = iter([1,2,3,4,5,6,7])
for i in range(5):
print(next(a)) |
import hashlib
import json
import scrapy
from kingfisher_scrapy.base_spider import ZipSpider
class Portugal(ZipSpider):
name = 'portugal'
download_warnsize = 0
download_timeout = 9999
def start_requests(self):
url = 'https://dados.gov.pt/api/1/datasets/?q=ocds&organization={}&page_size={}'
... |
#Implement integer exponentiation. That is, implement the pow(x, y) function,
#where x and y are integers and returns x^y.
#Do this faster than the naive method of repeated multiplication.
#For example, pow(2, 10) should return 1024.
import sys
sys.setrecursionlimit(1500)
def power(base, exp):
if exp == 0:
re... |
#!/usr/bin/python2
'''Run all the tests'''
import sys
import os
if len(sys.argv) > 1:
sys.path.insert(0, sys.argv[1])
else:
BASE = os.path.abspath(__file__)
DIR = os.path.dirname(BASE)
TARGET = os.path.join(DIR, '..', 'src')
CLEAN = os.path.abspath(TARGET)
assert(os.path.isdir(CLEAN))
sys... |
lista = ['a','b','c','d','e','f']
lista_n = [1,2,3,4,5,6]
lista_cap = [1,2,3,2,1]
lista_lista = [[1,2,3],[4,5],[6,7,8,9]]
#e1
def comprimento(lst):
if lst == []:
return 0
return 1 + comprimento(lst[1:])
print(f"O comprimento da lista é {comprimento(lista)}")
#e2
def soma(lst):
if lst == []:
... |
from utils import *
import os
import tensorflow as tf
import tensorflow_addons as tfa
os.environ['TF_XLA_FLAGS'] = '--tf_xla_enable_xla_devices'
BUFFER_SIZE = 1000
BATCH_SIZE = 100
VOCAB_SIZE = 10000
def run(df, epochs, N_CLASS, metric, fold):
# separate train and test
train_dataset = df[df["kfold"] != fo... |
'''
Header
Name:
mm_sh_toolset.py
Created by: Matt Malley
E-mail: contact@radiant-entertainment.com
How to Run in Maya: Copy/Paste this into Maya (or create as a button):
import maya.cmds as cmds
cmds.unloadPlugin("mm_sh_toolset.py")
cmds.loadPlugin("mm_sh_toolset.py")
cmds.mm_sh_toolset()
Project Description:
Th... |
"""PyTorch implementation of ResNet
ResNet modifications written by Bichen Wu and Alvin Wan, based
off of ResNet implementation by Kuang Liu.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
"""
import functools
import torch.nn as nn
f... |
def range_chars(char_1, char_2):
range_start = ord(char_1)
range_end = ord(char_2)
for i in range(range_start+ 1, range_end):
print(chr(i), end=" ")
character_1 = input()
character_2 = input()
range_chars(character_1, character_2)
|
def perform(codes):
cur = codes[0]
idx = 1
res = 0
cnt = base_cnt = 1
def calc_res(base_cnt, cnt, res):
if base_cnt >= cnt:
if 0 >= cnt:
res += base_cnt
else:
res += base_cnt - cnt
return res
while idx < l... |
import pygame
BLACK = (0,0,0)
class Brick(pygame.sprite.Sprite):
#This class represents a brick. It derives from the "Sprite" class in Pygame.
lives=0
def __init__(self, color, width, height, lives):
# Call the parent class (Sprite) constructor
super().__init__()
self.li... |
from typing import Any
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def printc(*args: Any, color: str = 'green') -> None:
string =... |
DBENGINE = 'mysql' # ENGINE OPTIONS: mysql, sqlite3, postgresql
DBNAME = 'lianjia2'
DBUSER = 'lianjia'
DBPASSWORD = 'lianjia'
DBHOST = '192.168.50.113'
DBPORT = 3306
CITY = 'gz' # only one, shanghai=sh shenzhen=sh......
REGIONLIST = [u'huangpu'] # only pinyin support
|
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
@api_view(['GET'])
def api_root(request, format=None):
return Response({
'apis': reverse('apis:checkbox-list', request=request, format=format),
}) |
import sys
i1 = 10
i2 = 10
print(hex(id(i1)),hex(id(i2)))
i1 = 11
i2 = 10 + 1
print(hex(id(i1)),hex(id(i2)))
# list는 mutable이므로 서로 다른 객체가 된다
l1 = [1,2]
l2 = [1,2]
print(hex(id(l1)),hex(id(l2)))
s1 = 'hello'
s2 = 'hello'
print(hex(id(s1)),hex(id(s2)))
# is 동일성 레퍼런스 비교
print(i1 is i2)
print(l1 is l2)
print(s1 is s2)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
import argparse
import json
import logging
import os
import subprocess
import sys
import time
from distutils.spawn import find_executable
import requests
requests.packages.urllib3.disable_warnings()
logger = logging.getLogger(__name__... |
from typing import Callable
import cv2
import numpy as np
from torch.utils.data import Dataset
from torchvision import transforms as transforms
class TransformDataset(Dataset):
def __init__(self, dataset: Dataset, transform: Callable):
self.dataset = dataset
self.transform = transform
def _... |
def lightNeeded(x):
if x==0:
return 6
if x==1:
return 2
if x==2:
return 5
if x==3:
return 5
if x==4:
return 4
if x==5:
return 5
if x==6:
return 6
if x==7:
return 4
if x==8:
return 7
if x==9:
return 6
... |
import FWCore.ParameterSet.Config as cms
highPurityGeneralTracks = cms.EDFilter(
'TrackSelector',
src = cms.InputTag('generalTracks'),
cut = cms.string('quality("highPurity")'),
)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 25 20:21:56 2020
@author: AYUSHI GUPTA
"""
def progC():
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from guizero import App... |
#Assistive Tech Group 2019
# __init__(self, id, lat, lon)
# updateLocation(self,latitude, longitude)
class Guide:
def __init__(self, GUIDEID, name, latitude, longitude):# Guide(GUIDEID, latitude, longitude)
self.GUIDEID = GUIDEID
self.latitude = latitude
self.longitude = longitude
... |
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from QuoteeApp import views
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django... |
class Tweet:
def __init__(self, tweet, who, score):
self.tweet = tweet
self.who = who
self.score = score
def __str__(self):
return self.tweet + " - " + self.who + " - " + str(self.score)
def __iter__(self):
return iter([self.tweet, self.who, str(self.score)])
|
class BallotTreeNode:
def __init__(self, candidateString, candidateDictionary):
self.votesThatPassHere = 0
self.candidateString=candidateString
self.candidateDictionary=candidateDictionary
self.children={}
def addBallot(self, remainingBallot):
self.votesThatPassHere+=1
... |
'''
############################### PYSKELWAYS #####################################
A software for hypergraph extraction from a binarised image
TODOLIST :
* Put small functions in miscfunc, or create two func files
* Put CORRECTION IN A NEW MODULE
* REPAIR SPLIT (Connexion unbreakable, wrong connection broke... |
import os.path
# create link in windows
# run cmd as administrator
# mklink broken_link C:\\not-exist
FILENAMES = [
__file__,
os.path.dirname(__file__),
os.sep,
'broken_link',
]
for file in FILENAMES:
print(f'File : {file}')
print(f'Absolute : {os.path.isabs(file)}')
print(f'Is File? : {os.path.is... |
# -*- coding:utf-8 -*-
# __author__ = 'gupan'
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, BASE_DIR)
from common.iniParser import IniParser
import json
conf_path = BASE_DIR + '\\conf\\testInfo.ini'
# print(BASE_DIR, conf_path)
# 获取测试链接主页
cf = IniPars... |
import sys
sys.path.append('./lib')
sys.path.append('./utils')
from productos import findByCodigo
# Cantidad de stock de un producto
def stock():
print('Introduzca el codigo del producto que desea ver el stock: ')
producto = findByCodigo(input('~~>'))
print()
print(producto["nombre"])
pri... |
"""
This module deals with processing the verb conjugation forms.
"""
from wiktionary_parser.sections import FTSection
from wiktionary_parser.formating_type import RegexFT
class NormalVerbConjugation(object):
def __init__(self, plain, third, third_past, past_part, pres_part):
self.plain = plain
... |
def get_min_coin_change(arr , target):
min_coin = target
if target in arr:
return 1
else:
for coin in [ _ for _ in arr if _ < target ]:
res = 1 + get_min_coin_change( arr , target - coin)
if res < min_coin:
min_coin = res
return res
print g... |
import pygame
class Janela:
def __init__(self, x, y, title):
self.size = (x,y)
self.title = title
def main():
game = Janela(800,600,"Oi, sou o Pygame.")
pygame.display.set_caption(game.title)
pygame.display.set_mode(game.size)
running = True
while running:
... |
"""
Created on Sat Aug 29 11:13:10 2020
@author: sds
"""
# how to use e.g. in spyder
# import modules
import numpy as np
import hiddensmmodel
# load data: nparray without timestamp
T = 10000
data = np.loadtxt('example-data.txt')[:T]
# train model
model = hiddensmmodel.Hsmm(data)
# estimated state sequenece to ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('dancers', '0014_tour_is_published'),
]
operations = [
migrations.RemoveField(
model_name='atl',
name... |
import screen
screen.clear()
def print_models(unprinted_designs, completed_models):
# Simulate printing each design, until none are left.
print("\nUnprinted Designs:")
while unprinted_designs:
current_design = unprinted_designs.pop()
#Simulate creating 3D print from the design
... |
# -*- coding: utf-8 -*-
import json
import urllib
import urllib2
import sys
sys.path.insert(1, '../genuzot')
import helperFunctions as Helper
from sefaria.model import *
apikey = Helper.apikey
server = Helper.server
structs = {}
structs = { "nodes" : [] }
def intro_basic_record():
return {
"title": "Haamek ... |
def isLeap(year: int):
if year % 400 == 0:
return True
if year % 100 == 0:
return False
if year % 4 == 0:
return True
return False
year = int(input())
print('YES' if isLeap(year) else 'NO')
|
import socket
import threading
import SocketServer
import time
import random
import sys
import os
list_ip = []
def init_list_ip():
list_ip = []
return None
def remove_client_ip(ip_client):
list_ip.remove(ip_client)
if len(list_ip) == 0:
return 1
else:
return None
def add_clie... |
import heapq
import sys
input = sys.stdin.readline
heap = []
tot = int(input())
for i in range(tot):
num = int(input())
if num == 0:
if len(heap) == 0:
print(0)
else:
print(heapq.heappop(heap))
else:
heapq.heappush(heap, num) |
#coding: UTF-8
import sys
sys.path.append('../')
import jieba
jieba.load_userdict("slackbot/plugins/extra_dict/custom_dict.txt")
jieba.load_userdict("slackbot/plugins/extra_dict/dict.txt")
import jieba.analyse
import re
from slackbot.bot import respond_to
from slackbot.bot import listen_to
ANSWER_LIST = []
@respon... |
import matplotlib.pyplot as plt
import numpy as np
import cPickle as pickle
from matplotlib.backends.backend_pdf import PdfPages
import scipy.stats
pdf = PdfPages('SamplingRate' + '.pdf')
a = pickle.load(open("Age_matched_w_inner_and_outer.p","r"))
regions = ['left_frontal','right_frontal','left_parietal','right_pari... |
from django.db import models
class Category(models.Model):
title = models.CharField(max_length=255) |
import torch
import torch.nn as nn
import logging
logger = logging.getLogger(__name__)
def get_concat(concat: str, embedding_dim: int):
"""
:param concat: Concatenation style
:param embedding_dim: Size of inputs that are subject to concatenation
:return: Function that performs concatenation, Size ... |
import os
import subprocess
import sys
def main():
cmd = sys.argv[1:]
h_file = None
try:
index = cmd.index('-o')
h_file = cmd[index+1]
cmd[index+1] = os.path.dirname(h_file)
except (ValueError, IndexError):
pass
p = subprocess.run(cmd, capture_output=True, text=True... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 14 21:04:47 2019
@author: Henri_2
"""
from __future__ import print_function
from keras.utils import np_utils
import numpy
""" This function cuts the notes list into "sequence_length" long sequences
and their respective outputs: X notes from the list and the X+1:th ... |
from django.urls import path
from django.urls.resolvers import URLPattern
from .views import dotaciones, insertar_dotacion, asignar_dotacion
urlpatterns = {
path('dotacion/', dotaciones, name='dotaciones_list' ),
path('insertar_dotacion/', insertar_dotacion, name='insertar_dotacion' ),
path('asignar_dotacio... |
import random
import hashlib
def create_salt():
salt = ''
seq = '0123456789abcdefghijklmnopqrstuvwxyz'
rng = random.randint(5, 10)
i = 0
while i < rng:
i += 1
salt += random.choice(seq)
return salt
def hashed_password(password, salt):
hashed_password = hashlib.sha256((salt + password).encode('utf8')).hexdi... |
from flask_restful import Resource
from app.auth import authenticate
class BasicProtectedResource(Resource):
method_decorators = [authenticate]
|
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium_api import *
from utils import *
class TreeholePage:
__post_locator = (By.XPATH, '//ol[@class="commentlist"]/li[contains(@id, "comment")]')
__open_comment_locator = (By.XPATH, '//div[@class="jand... |
from django.contrib import admin
from goods.tasks import generate_static_index_html
from django.core.cache import cache
from .models import GoodsType, IndexPromotionBanner, IndexTypeGoodsBanner, IndexGoodsBanner, GoodsSKU, GoodsImage, Goods
class BaseModelAdmin(admin.ModelAdmin):
""" 抽象父管理类"""
def save_model... |
class QuitException(Exception):
def __init__(self, message: str = 'User exited current menu'):
super().__init__(message)
self.message = message
def __repr__(self):
return f'<QuitException: {self.message}>'
|
# Generated by Django 3.1.7 on 2021-06-17 23:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('frontend', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='zinfo',
name='percent',
fi... |
import numpy as np
import pandas as pd
import dlib
import cv2
import os
from scipy import interpolate
class DlibVTExtractor(object):
def __init__(self):
pass
def get_equi_dist(self, contour, M):
contour = np.array(contour)
d = np.diff(contour, axis=0)
dist_from_vertex_to_vertex = np.hypot(d[:,... |
# -*- coding: utf-8 -*-
"""
This is part of WebScout software
Docs EN: http://hack4sec.pro/wiki/index.php/WebScout_en
Docs RU: http://hack4sec.pro/wiki/index.php/WebScout
License: MIT
Copyright (c) Anton Kuzmin <http://anton-kuzmin.ru> (ru) <http://anton-kuzmin.pro> (en)
Thread class for FuzzerHeaders module
"""
from ... |
# import library
import time
import matplotlib
import matplotlib.pylab as plt
import serial
# inisialisasi port serial
s=serial.Serial('com6', 2400)
def readlineCR(port): # Fungsi khusus buat baca feed data serial (string) dari vCOM
rv = "" # dengan terminator carriage return (CR) / '\r' atau ''
... |
from os import path
from numpy import dtype, fromfile
__author__ = "Yuri E. Corilo"
__date__ = "Jun 19, 2019"
class ReadMidasDatFile():
'''
Reads Midas data files, works for both Predator Analysis data and Thermo DataStation
'''
def __init__(self, filename_path):
'''
Constructor
... |
import Queue
#Global
ALPHABET = {1:'A',2:'B',3:'C',4:'D',5:'E',6:'F',7:'G',8:'H',9:'I',10:'J',
11:'K',12:'L',13:'M',14:'N',15:'O',16:'P',17:'Q',18:'R',19:'S',
20:'T',21:'U',22:'V',23:'W',24:'X',25:'Y',26:'Z'}
def senate(num, listSenators):
q = Queue.PriorityQueue()
order = list()
... |
#这基本是一个标准的inorder traversal
#对于BST而言,inorder traversal return的结果就是从小到大的
#这个code其实就是在94题标准的inorder traversal的基础上加了
def kthSmallest(self, root, k):
stack = []
while True:
while root:
stack.append(root)
root = root.left
if not stack:
return
# the order of... |
from setuptools import setup, find_packages
version = '1.0b0'
setup(name='fbimn.verteidigung',
version=version,
description="Verteidigungstermin Inhaltstyp",
long_description="""Verteidigungstermin Archetype, basierend auf ATEvent.
""",
# Get more strings from http://www.python.org/pypi?%3Aact... |
def print_list(alist):
for i in alist:
if type(i) is list:
print_list(i)
else:
print(i,end=' ')
a=[3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
import random
ta=[]
for i in range(20):
ta.append(random.randint(1,10000))
print(ta)
tb=ta[:10]
tb.sort()
ta[:10]=tb
tb=ta[10:]
tb.sort(re... |
"""A note on keeping code DRY: here I would optimally create one function that can dynamically
check different DB tables depending on which parameters are passed. For the sake of speed I'm not
doing that here since I won't always need to check if the record is in the DB before returning the
related object, e.g. in t... |
from flask import Flask, request, session, g, redirect, url_for, abort, render_template
from flask.ext.sqlalchemy import SQLAlchemy
import csv
import os
# creating the application
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
# databases init
db = SQLAlchemy(app)
# acode model
'''class ... |
from flask import (Flask, g, render_template, flash, redirect, url_for,
abort)
from flask.ext.bcrypt import check_password_hash
from flask.ext.login import (LoginManager, login_user, logout_user,
login_required, current_user)
from app import *
import forms
import models
l... |
from flask import Flask
from flask_session import Session
from flask_restful import Api
from flask_cors import CORS
from flask_socketio import SocketIO
from routes import ResourceManager
from models.User import User
from .sockets import sockets
from .redis import RedisSessionInterface
from utils.database impor... |
import sqlite3
from flask import json, g
def get_db():
db = getattr(g, '_database', None)
if db is None:
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
db = g._database = sq... |
import random as r
import time as t
def GenerateRandomIntArray(lenght):
n = []
n = r.sample(range(0,20000),lenght)
return n
def bubbleSort(vetor):
n = len(vetor)
jCounter = 0
for i in range(n):
for j in range(0, n - i - 1):
jCounter += 1
if vetor[j] > vetor[... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.