text stringlengths 8 6.05M |
|---|
# pylint: disable = C0103, C0111, C0301, R0913, R0903
import tensorflow as tf
import numpy as np
# from tensorflow.python.framework import ops
from scipy.ndimage.interpolation import rotate
def py_func(func, inp, Tout, stateful=True, name=None, grad=None):
# Need to generate a unique name to avoid duplicates:
... |
#!/usr/bin/env python
from PIL import Image
from pilkit.processors import ResizeToFit
from flask import Flask, request, send_from_directory, send_file
import os
from tempfile import TemporaryFile, NamedTemporaryFile
from zipfile import ZipFile
import random, string
from pprint import pprint
from werkzeug import secure_... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import time
import json
import logging
import homie
from modules.homiedevice import HomieDevice
from modules.mysql import db
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
class SetMixin:
def _set(self, param, type, msg, node=None):... |
from wtforms import Form
from wtforms import StringField, TextAreaField
from wtforms.fields.html5 import EmailField
from wtforms import PasswordField
from wtforms import HiddenField
from wtforms import BooleanField
from wtforms import SelectField
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from wtforms i... |
#!/usr/bin/env python
import os
from datetime import datetime
from flask import Blueprint, request, render_template, flash, redirect, url_for
from flask_login import login_user, logout_user, current_user, login_required
from app.helpers.getuser import get_user
from app.helpers.generaterandom import generate_random_... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
# ## This is a test notebook.
# In[ ]:
|
from abc import abstractmethod, ABC
class Bank(ABC):
@abstractmethod
def getROI(self):
pass
def getName(self):
return "Bank Name: PARENT BANK"
class SBI(Bank):
# pass
# @abstractmethod
def getROI(self):
return 8
# pass
# def getROI(self):
# return ... |
import json
from pycocotools.coco import COCO
from utils.data import save_coco_anns
from utils.data import get_category_based_anns
def filter_coco_by_cats(coco):
category_based_anns = get_category_based_anns(coco)
ann_ids_to_keep = []
img_ids_to_keep = set()
cat_ids_to_keep = set()
for sample in... |
# Parameter estimation by optimization
# When doing statistical inference, we speak the language of probability. A probability distribution that describes your data has parameters. So, a major goal of statistical inference is to estimate the values of these parameters, which allows us to concisely and unambiguously des... |
from adapters.adapter_with_battery import AdapterWithBattery
from devices.sensor.door_contact import DoorContactSensor
class SensorMagnet(AdapterWithBattery):
def __init__(self, devices):
super().__init__(devices)
self.devices.append(DoorContactSensor(devices, 'sensor', 'contact'))
|
#!/usr/bin/python
from __future__ import print_function
import logging
from fabric.api import task,run,local,put,get,execute,settings
from fabric.decorators import *
from fabric.context_managers import shell_env,quiet
from fabric.exceptions import *
from fabric.utils import puts,fastprint
from time import sleep
from c... |
#!/usr/bin/python
if __name__=='__main__':
factorial= lambda n:1 if n==1 else n*factorial(n-1)
print '3!=',factorial(3)
print '9!=',factorial(9)
print '15!=',factorial(15)
|
import heapq
def merge_boxs(prime_box_heap, version_map, regular_box):
output = [] # final output result will be stored here
while prime_box_heap:
version = heapq.heappop(prime_box_heap)
box_ids = version_map[version]
box_id = box_ids.pop()
output.append(box_id + ' ' + version)
... |
# List supports Modifications(insert,update) and duplicates and no order
List = list(("a", "bcd", 1, 2, 20, 1.5, 2, 10.0)) # ["a","bcd",1,2,20,1.5,2,10.0]
# Set supports Modifications(insert,update) but not duplicates and stores in an order
Set = set(("a", "bcd", 1, 2, 20, 1.5, 2, 10.0)) # {"a","bcd",1,2,20,1.5,2,... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
sess=tf.Session()
# seed
tf.set_random_seed(5)
np.random.seed(42)
batch_size = 50
a1 = tf.Variable( tf.random_normal(shape=[1,1]))
b1 = tf.Variable( tf.random_normal(shape=[1,1]))
a2 = tf.Variable( tf.random_normal(shape=[1,1]))
b2 = tf.Varia... |
import sys, os, re
file_list = []
with open('./log') as f:
for line in f:
m = 'Processing'
L = len(m)
if line[0:L] == m:
filename = line[L+1:-1]
print( filename )
file_list.append(filename)
print('Number of files: ',len(file_list))
|
#creating your own object/datatype
# Class - Definition of a abstract data type in a program
# Object - Particular instance of class definition
# aName = name('john','Doe')
# HEre name is class and aName is object
class Name:
#constuctor methods-- declaration/instantiation
#This first part talks ab... |
from django.apps import AppConfig
class AutoriConfig(AppConfig):
name = 'autori'
|
# -*- coding: utf-8
"""
Created on 17:07 27/07/2018
Snakemake de novo transcriptomics and transcript abundance estimation
- Find the the fastq files used by DCC read alignments workflow
- compute de novo tx with StringTie [doi:10.1038/nprot.2016.095]
- use de novo annotation to compute transcript abundance with salmon ... |
# 딕셔너리에서 아예 값을 뺌으로써 딕셔너리의 길이로 보석을 다 모았는지의 여부를 확인할 수 있도록
# 딕셔너리를 사용함으로써 시간 복잡도를 줄일 수 있도록
def solution(gems):
include = {gems[0]: 1}
g_len = len(gems)
i_len = len(list(set(gems))) # 보석 종류의 개수
answer = [0, g_len-1]
start, end = 0, 0 # 투 포인터
while end < g_len and start < g_len: # 두개의 포... |
import os
import psutil
for process in psutil.process_iter():
if "spotify" in process.name().lower():
try:
os.system(f"taskkill /F /PID {process.pid}")
except:
print(f"couldnt kill Process {process.name()} with PID {process.pid}")
os.system("start C:/Users/Dom/AppDa... |
from __init__ import print_msg_box
import time
def maxSubArraySum(a,size):
max_so_far =a[0]
curr_max = a[0]
for i in range(1,size):
curr_max = max(a[i], curr_max + a[i])
max_so_far = max(max_so_far,curr_max)
return max_so_far
def kadanes_algorithm(arr,hint=False):
start = time.time()
if... |
def powTwo38():
return 2 ** 38;
if __name__ == '__main__':
print(powTwo38()); # print the suffix of the next html doc
|
import wrcX.core
import wrcX.core.data as d
import wrcX.charts.overall as c
from pandas import merge
from wrcX.core.enrichers import addGroupClassFromCarNo
from wrcX.core.filters import groupClassFilter
def table_stageResult(stagenum,groupClass='',lower=0,upper=10):
pretxt = d.df_stage[d.df_stage['stage']==stagen... |
#coding:utf-8
import pymysql
from text9.dbcon import *
import sys
import pandas
bookzhekou=[]
bookcomment=[]
def getData():
conn = pymysql.connect("localhost","root","root","school_db")
cursor = conn.cursor()
sql = "select * from booktest1"
cursor.execute(sql)
books = cursor.fetchall()
for v in ... |
# Generated by Django 2.2.3 on 2019-11-12 15:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('log_in', '0003_auto_20191112_0232'),
]
operations = [
migrations.AlterField(
model_name='useraddition',
name='custom... |
'''
File defining base types
'''
from state import State
from ode import *
import pdb
import numpy as np
def matchParen(s,i):
l=s[i]
if l=='(':
r=")"
elif l=="{":
r="}"
elif l=="[":
r="]"
elif l=="<":
r=">"
else:
raise Exception()
cnt=0
for j in range(i,len(s)):
if s[j]==l:
cnt+=1
elif s[j]==r... |
import socket
def createSocket(port,host):
try:
s = socket.socket()
s.connect((host,port))
return s
except:
print('Socket created.')
def receiveFile(s,filename):
try:
with open(filename, 'wb') as f:
print ('file opened')
while True:
... |
###############################################################################
#
# cspace.py
#
# test ideas with OpenCV color spaces
#
###############################################################################
import cv2
import opencvconst as cv
import numpy as np
x0,y0 = -1,-1
clicked = False
def main():
... |
#!/usr/bin/python3
import sys
import heapq
def dijkstra(s, g):
v = {k: 0 for k in g}
e = {k: sys.maxint for k in g}
e[s] = 0
q = [(0, s)]
while (q != []):
_, a = heapq.heappop(q)
if v[a]: continue
v[a] = 1
for (n, w) in g[a]:
if (e[a] + w < e[n]):
e[n] = e[a] + w
heapq.heappush(q, (e[... |
import tensorflow as tf
import numpy
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
#加载数据
digits=load_digits()
x=digits.data
y=digits.target
y=LabelBinarizer().fit_transform(y)
x_train,x_test,y_train,y_test=train... |
import logging
from typing import Callable
backup_logger = logging.getLogger(__name__)
logger_callbacks = []
class ErrorLogger:
@staticmethod
def add_logging_callback(callback: Callable):
"""
Adds a callback for logging purposes.
:param callback: A function that takes in an excepti... |
from django.contrib import admin
from file_keeper.models import File
class FileAdmin(admin.ModelAdmin):
fields = ('hash', 'mime', 'base64')
list_display = fields
admin.site.register(File, FileAdmin)
|
from django.db import models
# Create your models here.
class Articles(models.Model):
title = models.CharField(max_length=256)
created_at = models.DateTimeField()
author = models.CharField(max_length=128, default='piroyoung')
body = models.TextField()
class Categories(models.Model):
name = mode... |
from flask import Flask,render_template,request,redirect,flash,Response
import pandas as pd
from io import BytesIO
import base64
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
from numpy import exp, cos, linspace
from matplotlib.figure import Figure
import os, re
import nu... |
#!env python3
# -*- coding: utf-8 -*-
var1 = 'variable one'
if var1 == 'variable one':
print('var1 is variable one')
|
# -*- coding: utf-8 -*-
import functools, types
import util
def login_check(check_func, failed_func=None):
"""Utility decorator to wrapped a method with login process"""
if not check_func or not util.is_callable(check_func):
raise Exception('Developer Error: check_func parameter must point to an exis... |
import socket
ip = '127.0.0.1' #Machine IP - Carbon Coder Software
porta = 1120 #Default Carbon Coder port
sck = socket.socket()
sck.connect((ip,porta))
message = "CarbonAPIXML1 68 <?xml version =\"1.0\" encoding=\"UTF-8\"?><cnpsXML TaskType=\"JobList\"/>"
sck.send(message.encode("utf-8"))
data = sck.recv(4096).... |
# Given an array and a value, remove all instances of that value in-place and return the new length.
#
# Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
#
# The order of elements can be changed. It doesn't matter what you leave beyond the new... |
import numpy as np
import sys
n, m, k, t = list(map(int, input().strip().split()))
data = np.array(list(map(lambda line: list(map(float, line.strip().split())), sys.stdin.readlines())))
points = data[:, :data.shape[1] - 1]
clusters = np.array(list(map(int, data[:, data.shape[1] - 1])))
for step in range(t):
# p... |
# -*- coding: utf-8 -*-
"""
ZigBee constants.
"""
# ========== MAC constants: ======================
#frame types:
TYPE_BCN = 'Beacon'
TYPE_DATA = 'Data'
TYPE_ACK = 'Ack.'
TYPE_CMD = 'Command'
FRAME_TYPE = {'000': TYPE_BCN,
'001': TYPE_DATA,
'010': TYPE_ACK,
'011': TYPE_CMD}
#addressing modes:
MODE_NONE =... |
import fresh_tomatoes
import media
# set up my six movie objects
secret_of_my_success = media.Movie(
"The Secret of My Success",
("https://upload.wikimedia.org/wikipedia/en/1/18/"
"The_Secret_Of_My_Success.jpg"),
"https://www.youtube.com/watch?v=rGHDATIJIX8")
john_wick = media.Movie(
... |
from interfaces.prediction_network import PredictionNetwork
from connect4.connect_four_state import ConnectFourState
import torch
class ConnectFourPredictionNetwork(PredictionNetwork):
def __init__(self, network, cols):
self._network = network
self._cols = cols
def predict(self, state):
... |
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import math
import socket
import os
class SimpleNetworkClient :
def __init__(self, port1, port2) :
self.fig, self.ax = plt.subplots()
now = time.time()
self.lastTime = now
self.times = [time.strftim... |
import sys
sys.path.append("..")
import requests
from bs4 import BeautifulSoup
import time
from backend.common.connect import Database
from SpotifySongInfo import spotify_info
#if year divisible by 4, it's a leap year -> feb + 1
DAYS_IN_MONTH =[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
WEEK = 7
year = 2019
mon... |
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib.auth import authenticate
from django import forms
from .interface import interface
from product_mgr_app.models import Product, Rating
def index_view(request):
user = request.user
products = Product.objects.all(... |
#https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
class Solution(object):
reflect_table = dict()
reflect_table["2"] = ['a','b','c']
reflect_table["3"] = ['d', 'e', 'f']
reflect_table["4"] = ['g', 'h', 'i']
reflect_table["5"] = ['j', 'k', 'l']
reflect_table["6"] = ['m', 'n... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 6 17:59:56 2019
@author: e1077783
"""
import sklearn.datasets
import numpy
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler
from sklearn.impute import SimpleImputer
from sklear... |
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
(x_train, _), (x_test, _) = mnist.load_data()
x = np.append(x_train, x_test, axis=0)
print(x.shape)
# 실습
# pca 를 통해 0.95 이상인 것 몇개?... |
overlap_studies = {
"BBANDS":"Bollinger Bands",
"DEMA":"Double Exponential Moving Average",
"EMA":"Exponential Moving Average",
"HT_TRENDLINE":"Hilbert Transform - Instantaneous Trendline",
"KAMA":"Kaufman Adaptive Moving Average",
"MA":"Moving average",
"MAMA":"MESA Adaptive Moving Average"... |
#coverage.py
#encoding:utf8
from user_cf import user_cf
from operator import itemgetter
from settings import K
def coverage(train,test,W, N):
recommend_items=set()
all_items=set()
for user in train.keys():
for item in train[user]:
all_items.add(item[1])
rank=user_cf(user,train,... |
from loaders import load_IAM, load_MNIST, load_split_MNIST
def get_loader(name, label=0):
if name == "IAM":
return load_IAM.batch_generator()
if name == "MNIST":
return load_MNIST.batch_generator()
if name == "split_MNIST":
return load_split_MNIST.batch_generator(label) |
class Vehicle:
def modelname1(self,modelname):
self.modelname=modelname
def Regnumber(self,Regno):
self.Regno=Regno
class Bus(Vehicle):
def colourname(self,colour):
self.colour=colour
def printval(self):
print(self.Regno,self.modelname,self.colour)
B=Bus()
B.modelname1('K... |
'''The MIT License (MIT)
Copyright (c) 2021, Demetrius Almada
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, me... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^$', 'apps.sharefile.views.friendFiles', name='friendFiles'),
url(r'sendMsg2cscServer/$', 'apps.sharefile.views.sendMyInfoToServer', name='sendMsg2cscServer'),
url(r'^peerPort/$', 'apps.sharefile.views.peerPort', name='pee... |
#!/usr/kai/anaconda3/python
# -*- coding: utf-8 -*-
# Hilfs-Funktionen:
# zum Spielen von Go9x9 (Brettdrehung, Print)
# zur Konvertierung des NN Input Formats (B7)
# zur Speicherung des MCTS Trees
# V1: setzt auf auf V4: gameT3
# V2: b7 convert functions
# V3: testing
# V4: drehung
# V5: Performance: b, b1 und n... |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class LoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'username'}),label='')
password = forms.CharField(widget = forms.PasswordInput(attrs=... |
#-----Statement of Authorship----------------------------------------#
#
# This is an individual assessment item. By submitting this
# code I agree that it represents my own work. I am aware of
# the University rule that a student must not act in a manner
# which constitutes academic dishonesty as stated and exp... |
from typing import Tuple, List
import numpy, os, gzip
def glove_reader(file_path: str) -> Tuple[List[str], List[List[float]]]:
if os.path.isfile(file_path):
word = []
vector = []
if '.gz' != file_path[-3:]:
with open(file_path, 'r') as fp:
for w in fp:
... |
import numpy as np
# One dimensional array
arr1 = ['Anuj', 'Ashish', 'Ayush', 'Bhavya']
print("The array of 1 dimension is: ", np.array(arr1))
narr = np.array(arr1)
print("The array of 1 dimension is: ", narr)
# Two dimensional array
arr2 = np.array([['Anuj', 'Ashish', 'Ayush', 'Bhavya'],
['Adarsh', '... |
#!/usr/bin/env python3
import cgi
import html
form = cgi.FieldStorage()
text_form = form.getfirst("ticket_number","none")
ticket_number = html.escape(text_form)
def lucky(num):
""" Checks if the ticket is lucky.
The ticket is lucky if the sum of the first three digits equals the last \
three digits.
... |
# class AboutDict:
# def __init__(self):
# pass
# def var_to_dict(self,*args):
import sys
def ss(a,b):
len(sys.argv)
print(sys.getframe().f_code.co_name )
a ='s'
c ='dd'
ss(a,c)
|
#!/usr/bin/python
import cma
import numpy as np
def fobj1(x):
assert len(x)==1
return 3.0*(x[0]-1.2)**2+2.0
def frange(xmin,xmax,num_div):
return [xmin+(xmax-xmin)*x/float(num_div) for x in range(num_div+1)]
#fobj= cma.fcts.rosen
fobj= fobj1
using_bounds= False
if not using_bounds:
#options = {'CMA_diagonal... |
class Triangulo:
def __init__(self, a,b,c):
self.a = a
self.b = b
self.c = c
def perimetro(self):
perimetro = self.a + self.b + self.c
return perimetro
def tipo_lado(self):
if self.a != self.b and self.b != self.c and self.a != self.c:
... |
from game.items.item import Tool
from game.skills import SkillTypes
class TinderBox(Tool):
name = 'Tinderbox'
value = 1
skill_requirement = {SkillTypes.firemaking: 1}
weight = 0.035 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from random import random
names = ["small", "medium", "large", "xlarge"]
Ns = [12, 16, 20, 24]
cc = 20
for no, n, name in zip(range(len(Ns)), Ns, names):
fp = open("input%.2d%s.txt" % (n, name), "w")
fp.write("%d\n" % cc)
for case in xrange(cc):
fp.write("... |
from django.shortcuts import render
from folder_tree.models import FolderTree
# Create your views here.
def index(request):
data = {'FolderTree': FolderTree.objects.all()}
return render(request, 'index.html',data) |
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from transformers import BertModel
class RNNSequenceModel(nn.Module):
def __init__(self, model_params):
super(RNNSequenceModel, self).__init__()
self.hidden_size = model_params['hidden_size']
self... |
def separateDigits(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
lst = []
sum = 0
# iterate through the provided list
for idx in nums:
# if the value is > 10 (aka more than one digit)
if idx >= 10:
vals = []
# break up the number and ... |
#/bin/python
#
#
#script takes recipe in *_* format and desired number of iterations
import subprocess, func
import subprocess, sys, logging, optparse
logging.basicConfig(filename='./out/log.out',level=logging.DEBUG)
parser = optparse.OptionParser('usage: python run_drift.py [fs-drift options]')
parser.add_option('... |
class Create_file(object):
def __init__(self, url, file_name):
self.url = url
self.file_name = file_name
def open_file(self):
with open(self.file_name, 'a') as file: #opens the ammendable('a') file with name "file_name"
file.write("\nfor " + self.url + " :... |
import os
import celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
from django.conf import settings # noqa
app = celery.Celery('project')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 24 11:23:48 2019
@author: nanokoper
"""
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor
import... |
class PartySizePicker:
select_toggle_selector = 'div.select-toggle[aria-owns="partySize-dropdown-list"]' |
from flask import *
from flask_menu import register_menu
from wtforms import *
auth = Blueprint('auth', __name__, url_prefix='/auth', template_folder='auth_templates')
class FormLogin(Form):
"""Clase para soporte de credenciales de usuarios"""
# empresa = StringField('Empresa', validators=[validators.optiona... |
"""MetFilab URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/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-ba... |
#coding:utf-8
import bobo, webob
from controller import Controller
from service.top.display import TopDisplayService
from view.view import View
@bobo.subroute('', scan=True)
class TopController(Controller):
def __init__(self, request):
self.request = request
@bobo.query('')
@bobo.query('/... |
#%%
from models import CNNBiLSTMATTN, CNNs, LSTMs, CNNLSTM
from models import root_mean_squared_error, weighted_root_mean_squared_error, last_time_step_rmse
from utils import WindowGenerator
from utils import draw_plot, draw_plot_all, save_results
import tensorflow as tf
from sklearn.preprocessing import Standard... |
def do_add_activities(uid, uactivities, boto):
status=200
ujson = {'type': "person", 'id': uid, 'added': uactivities}
try:
if((str(uid)!="")):
item = boto.get_item(id=uid)
added_list = [] + uactivities.split(",")
acti_list = item['activities']
for i in added_list:
acti_list.append(i)
ujson['... |
import datetime
import discord
import random
import sys
import os
token = sys.argv[1]
class CoronaBot(discord.Client):
def __init__(self):
super().__init__()
self.permission_denied_warned_servers = []
self.corona_emoji = "<:corona:684132221077946401>"
self.protected_message_conte... |
import ssl
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
DADOS_EMAIL = {
"port": 587,
"smtp_server": "smtp.gmail.com",
"sender_email": "thiagomandouemail@gmail.com",
"receiver_email": "diego.capassi.moreira@gmail.com",
"password": 'H0m3w0rk@2020'... |
def anagrams(words):
anagrams = {}
for i in words:
if str(sorted(i)) in anagrams:
anagrams[str(sorted(i))].append(i)
else:
anagrams[str(sorted(i))] = [i]
anagrams_list = list(anagrams.values())
return [x for x in anagrams_list if len(x) >1] #remove lists with one ... |
# Native Modules
# Downloaded Modules
# Custom modules
from .dbconnection import DBConnection
# Constants
class DBIp():
def __init__(self, p_dict):
self.id = p_dict["id"]
self.link = p_dict["link"]
self.asn = p_dict["asn"]
self.asowner = p_dict["asowner"]
self.network = p_dict["network"]
self.contine... |
import time,datetime,json,uuid,requests
from sqlalchemy import and_,extract
from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from django.core import serializers
import BJTU_RBAC.models as models
from BJTU_RBAC.orm import sqlConn
localtime = time.localtime(time.time())
'''
获取用户列表(分页)... |
# 开启debug模式
debug = True
# 数据库连接操作
# 数据库链接方法:dialect+driver://username:password@host:port/database
DIALECT = 'mysql'
DRIVER = 'mysqlconnector'
USERNAME = 'root'
PASSWORD = 'root'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'flask'
# SQLALCHEMY_DATABASE_URI--连接数据库制指定变量
SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{... |
import numpy as np
import random as random
import math
import re
import sys
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import beta
def beta_func(theta,a,b):
# beta prior
numSteps = 1000
theta_vector = np.linspace(0,1,numSteps)
vector_int = [x**(a-1)*(1-x)**(b-1) for x in the... |
from .apps import OsfOauth2AdapterConfig
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class OSFAccount(ProviderAccount):
def to_str(self):
# default ... reserved word?
dflt = super(OSFAccount, self).to_s... |
# coding: utf-8
import re, requests, xlwt
headers = {
'Accept':'*/*',
'Accept-Encoding':'gzip, deflate',
'Accept-Language':'zh-CN,zh;q=0.8',
'Connection':'keep-alive',
'Content-Length':'141',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
'Cookie':'JSESSIONID=ACCB528F0EE4... |
import logic
class RaftGUI:
'''
The RaftGUI is the interface between the main GUI and the logic module.
All properties of the raft, such as the location and velocity of the
raft is set here. Any key press event is being evaluated here.
The interface to the GUI module is:
1. updating of coordin... |
import threading
from typing import Callable
from threading import Semaphore
def printFirst():
print("first", end="")
def printSecond():
print("second", end="")
def printThird():
print("third", end="")
class Foo:
def __init__(self):
self.semaphore_second = Semaphore(0)
self.semapho... |
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the G... |
import sys
import pickle
from collections import defaultdict
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.stats as stats
colors = sns.hls_palette(8, l=.3, s=.8)
sns.set_palette(sns.hls_palette(8, l=.3, s=.8))
mpl.style.use('presentation')
mpl.rcParams... |
class Logger(object):
def __init__(self):
self.log = {}
def shouldPrintMessage(self, timestamp, message):
if timestamp < self.log.get(message, 0): # get the next printable timestamp
return False
self.log[message] = timestamp + 10 # set the next printable timestamp
... |
from clase_Pokemon import Pokemon
class Squirtle(Pokemon):
pokemon = 'Squirtle'
tipo = ("agua")
tipo_experiencia = "Parabolico"
atributos = {
"ps": 104,
"ataque": 78.5,
"defensa": 95.5,
"atq_esp": 80.5,
"def_esp": 94.5,
"velocidad": 73.5
}
# 'Movi... |
# class AdminTest(SeleniumTest):
#
# def test_admin_login(self):
# # a admin account is already registered
# # the admin is on the home page
#
# # the admin click the log in button
#
# # a form appears (dynamic)
#
# # the admin fill up the informations
# # - email
#... |
from pyarrow.hdfs import connect as hdfs_connector
from neomodel import db
from models import *
from factories import *
def eternity():
return "9999-01-01T00:00:00"
class HdfsToNeo4j:
def __init__(self, import_name, directory, version):
self._hdfs = hdfs_connector()
self._import_name = impo... |
#%% why numpy
array = []
for i in range(0, 10):
array.append(i**2)
array = [i**2 for i in range(0, 10)]
#%% array
import numpy as np # np->convention
np_zero = np.zeros(4)
np_array = np.array([0, 1, 2, 3, 10])
np_arange = np.arange(10) ** 2 #-> operator overloading
#%% math lib
min = np_array.min()
max = np_arr... |
import itertools
count = 0
str = input()
list = str.split()
str1 = input()
list1 = str1.split()
for v in itertools.combinations(list1, 3):
if(int(v[0])+int(v[1])+int(v[2]) == int(list[1])):
count = count + 1
print(count)
|
"""
Constraint Module
"""
from typing import List
import predicates
class Constraint:
"""
Constraint Class
Contains predicates.
Predicates are stored in a 2D list and interpreted as follows:
Equals(0) or (MoreThan(4) and LessThan(7))
_predicates = [[Eqals(0)],[MoreThan(4), LessThan(7)]]
""... |
# Wathaned Ean
import random
def namey():
global name
name = raw_input("What is your name? ")
randomnumber()
def randomnumber():
global ranum
ranum = random.randrange(10)+1
def printname():
for printy in range(ranum, 0, -1):
print name
def goodbye():
print "Bye", name
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.