text stringlengths 38 1.54M |
|---|
from MidiEvents import MetaEvent
from MidiEvents import ContinuationEvent
from MidiEvents import MidiEvent
def readFourBytes(f):
dat = f.read(4)
return (ord(dat[0])<<24) | (ord(dat[1])<<16) | (ord(dat[2])<<8) | ord(dat[3])
def readTwoBytes(f):
dat = f.read(2)
return (ord(dat[0])<<8) | ord(da... |
from pathlib import Path
import tensorflow as tf
from unsupervised_dna import (
LoadImageEncoder,
LoadImageVAE,
)
AUTOTUNE = tf.data.AUTOTUNE
class DatasetVAE:
def __init__(self, data_dir: Path, batch_size: int, kmer: int, shuffle: bool = True):
self.data_dir = Path(data_dir)
self.b... |
from os import path
WTF_CSRF_ENABLED = True
SECRET_KEY = 'princesse123'
db_filename = path.join(path.dirname(__file__), 'templog.db')
|
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, SimpleRNN, Dropout
#1. 데이터
x = np.array([[1,2,3], [2,3,4], [3,4,5], [4,5,6]]) # (4, 3)
y = np.array([4,5,6,7]) # (4,)
print(x.shape, y.shape)
x = x.reshape(4, 3, 1) # (batch_size, timesteps, feature)
print(x)... |
from lxml import etree
import os
import sqlite3
import db_tools
def populate_questions_answers_tables(elem, c):
is_question = elem.attrib['PostTypeId'] is "1"
has_accepted_answer = 'AcceptedAnswerId' in elem.attrib
if is_question and has_accepted_answer:
q_id = int(elem.attrib['Id'])
title... |
from datetime import date
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from dateutil.rrule import rrule, WEEKLY, WE
START_DATE = date(2018, 11, 1)
MIN_DAYS_TO_COUNT_AS_MONTH = 10
MONTHS_PER_YEAR = 12
def calc_months_passed(year, month, day):
"""Construct a date objec... |
# -*- coding: utf-8 -*-
#use:
#python opencv_labeling.py img/520f8a8d.jpg
import cv2
import numpy as np
import sys
args = sys.argv
image_path = ""
if len(args) < 2:
image_path = "img/520f8a8d.jpg"
else:
image_path = str(args[1])
img = cv2.imread(image_path)
def main():
# 入力画像の取得
im = cv2.imread(ima... |
""" Script "output_analysis_v5.py" from 12.05.2020.
It was used for simulation and analysis of "S90_DSNB_CCatmo_reactor_NCatmo".
output_analysis_v5.py:
The Script is a function to display and analyze the results of the MCMC analysis.
The MCMC analysis is done either with analyze_spectra_v7_local.py o... |
# DIFFERENCE BETWEEN COROUTINES AND GENERATORS
# it is possible to add arguments to coroutines during execution
# not possible for generators
from asyncio import coroutine
def coroutine(func):
def start(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return start
# d... |
from data_conversion import *
buids = []
def init():
get_buids()
def get_buids():
for entry in db["profiles"].find():
if "buids" in entry:
if len(entry["buids"]) > 0:
for buid in entry["buids"]:
buids.append((buid, str(entry["_id"])))
buids.sort()... |
# Generated by Django 3.2.7 on 2021-10-06 08:47
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("details", "0016_alter_ex... |
import os
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
# app.config['SECRET_KEY'] = 'mysecretkey'
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__, static_url_path='/static')
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://tinyfee4_Team:k-k)6ih8URbs... |
from django.db import models
from django.contrib.auth.models import User
from address.models import AddressField
from star_ratings.models import Rating
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=100)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from lxml import etree
import requests
import xlwt
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36',
}
info_base_url = 'https://hr.tencent.com/'
# 1. 创建 列表页链接 https://hr.tenc... |
import numpy as np
x, y = np.loadtxt('coordinate pixel.txt', unpack = True)
az, pol = np.loadtxt('coordinate_celesti.txt', unpack = True)
az = (az*np.pi)/180
pol= (pol*np.pi)/180
A = np.cos(pol[0])*np.cos(pol[1])+ np.sin(pol[0])*np.sin(pol[1])*np.cos(az[0]-az[1])
alfa1 = np.arccos(A)
A = np.cos(pol[1])... |
""" Query catsim """
def catsim_query(stack_version, **kwargs):
""" Pass arguments to a function which handles
specifics of the stack version """
if stack_version < 10:
return catsim_query_stack8(**kwargs)
else:
return catsim_query_stack10(**kwargs)
def catsim_query_stack8(objid, c... |
#!/usr/bin/env python
import os
from munin import MuninPlugin
from sense_hat import SenseHat
ADJUSTMENT=9
class TempPlugin(MuninPlugin):
title = "Adjusted Temperature"
# args = "--base 1000 -l 0"
vlabel = "adjusted temp (-{0})".format(ADJUSTMENT)
scale = False
category = "sense"
@property
... |
import csv
import pandas as pd
import io
headers = ["name", "mass", "radius", "distance"]
df = pd.read_csv("./brown-dwarfs.csv")
df = df[df['mass'].notna()]
df = df[df['radius'].notna()]
df['radius'] = df['radius'] * 0.102763 # Convert to Solar Radius
df['mass'] = df['mass'] * 0.000954588 # Convert to Solar Mass
p... |
import unittest
import mock
import os
from cumulus.queue import get_queue_adapter
from cumulus.queue.abstract import AbstractQueueAdapter
from cumulus.constants import QueueType
from cumulus.tasks import job
class PbsQueueAdapterTestCase(unittest.TestCase):
def setUp(self):
self._cluster_connection = moc... |
from Instrucciones.Return import Return
from Expresiones.Arreglos import Arreglos
from Abstractas.NodoArbol import NodoArbol
from Expresiones.Rango import Rango
from Instrucciones.Continue import Continue
from TablaSimbolos.Errores import Errores
from Abstractas.Objeto import TipoObjeto
from Objetos.Primitivos import P... |
from classproperty import classproperty, classproperty_support
from collections import OrderedDict
@classproperty_support
class LMPtrj(object):
"""
A class that parses lammps trajectories and stores the data in the
trj attribute as a dictionary
attributes:
clear() : clear the trj, called by the cl... |
import sys
import cloudinary
#---------------------------------------------------------------------------#
# Generic #
#---------------------------------------------------------------------------#
SECRET_DEBUG = True
SECRET_KEY = 'xd#vc@mec1c0+wz^y&_i^-o... |
import os
import yara
import time
import lief
import json
import pefile
import zipfile
import hashlib
import pythoncom
import win32com.client
from utils import db_comm
from utils import peparser
from utils import get_malicious
from utils.config import Config
from utils.yarascan import YaraScan
from utils.MSMQCustom imp... |
from jetbotSim import Robot, Camera
import numpy as np
import cv2,math
frames = 0
objpoints = []
Matrix = np.array([[568.67291932, 0.00000000e+00, 518.70213251],
[0.00000000e+00, 567.49287398, 245.11856484],
[0.00000000e+00, 0.00000000e+00, 1.00000000e+00]])
k = np.array([[ -0.30992158, 0.10084567, 0.0... |
import logging
from os.path import exists
import unittest
from db import Db
from generic_dao import GenericDao
class TestGenericDao(unittest.TestCase):
class TestDao(GenericDao):
@property
def table_name(self):
return "test_table"
@property
def columns(self):
... |
# Python implementation of post at
# https://www.topcoder.com/community/data-science/data-science-tutorials/assignment-problem-and-hungarian-algorithm/
import numpy as np
import pdb
__all__ = ['Hungarian']
class Hungarian:
def __init__(self):
self.max_match = 0
self.cost = None
self.n = 0... |
#!/usr/bin/env python
#
# Set the GPIO state of a specified pin. Return the pin with its new value.
# Package: gpio_msgs. Support for setting a single Raspberry Pi GPIO output.
#
import sys
import rospy
import RPi.GPIO as GPIO
from std_msgs.msg import String
from gpio_msgs.srv import GPIOSet
def set_GPIO(request):
... |
import re
hand = open('mbox-short.txt')
for line in hand:
line = line.rstrip()
if re.search('From:', line):
print line
###############################################
#achieve above not using regular expression
hand = open('mbox-short.txt')
for line in hand:
line = line.rstrip()
if line.find('... |
from riotwatcher import RiotWatcher
import json
from time import sleep
w = RiotWatcher('21e6bb30-08e1-47ed-946f-cee514b740d8')
challenger = w.get_challenger()
# returns list of player id's in league
def getPlayerIds(league):
entries = league['entries']
l = []
breakPoint = 0;
for ent in entries:
... |
import os
anaFiles = ["start_lunchinator.py"]
anaFiles.extend(aFile for aFile in os.listdir("plugins") if os.path.isfile(aFile) and aFile.endswith(".py"))
for aFile in os.listdir("plugins"):
aFile = os.path.join("plugins", aFile)
if aFile.endswith(".py"):
anaFiles.append(aFile)
if os.path.isdir(aFil... |
from CRABClient.UserUtilities import config
config = config()
config.General.requestName = 'PRv4_monoX-SingleEl_resubmit'
config.JobType.pluginName = 'Analysis'
config.JobType.psetName = 'tree.py'
config.Data.inputDataset = '/SingleElectron/Run2015D-PromptReco-v4/MINIAOD'
#'/DoubleEG/Run2015D-05Oct2015-v1/MINIAOD'
#... |
password = [0x0, 0x0, 0x0, 0xd2]
temp = 0xf9
temp2 = 0xd4
for i,byte in enumerate(password):
byte = temp ^ temp2 ^ byte
temp = temp2
temp2 = byte
password[i] = byte
checksum = ((((0x3b + password[0]) ^ password[1]) - password[2]) ^ password[3]) & 0xff
result = [password[0], password[1], password[2], password[3],... |
# coding: utf-8
# In[1]:
""" Process flood risk data and store on BigQuery.
-------------------------------------------------------------------------------
Author: Rutger Hofste
Date: 20181204
Kernel: python35
Docker: rutgerhofste/gisdocker:ubuntu16.04
"""
SCRIPT_NAME = "Y2018M12D04_RH_RFR_CFR_BQ_V01"
OUTPUT_VER... |
from flask import request
from flask_restful import Resource
from sqlalchemy.orm import joinedload
from sqlalchemy import exists
from werkzeug.exceptions import NotFound, Conflict, Forbidden
from model import db, Group, User
from core.capabilities import Capabilities
from core.schema import GroupSchema, MultiGroupShow... |
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So, you're %r old, %r tall and %r heavy." % (
age, height, weight)
print "Who is your daddy?",
daddy = raw_input()
print "What does he do?",
do = raw_input()
print... |
import geocoder
from django.db import models
from django.contrib.auth.models import (AbstractUser, User)
mapbox_token = 'pk.eyJ1Ijoid2F6b3dza2lkZXZlbG9wIiwiYSI6ImNrcTdneXZ4ejA2M2Uyd3VoY29hZTVjYXYifQ.wUjItHT_F5ZCMXUcwx5_xA'
class Place(models.Model):
address = models.CharField(max_length=100)
lat = models.Fl... |
################################################################################
# -*- coding: utf-8 -*-
# author : Jinwon Oh
# file name : cxFile.py
# date : 2012-09-06 14:27:08
# ver :
# desc. :
# tab size : set sw=4, ts=4
# python ver. : 2.7.1 Stackless 3.1b3 060516 (release27-main... |
"""
1. Have accumulator to check largest
2. Iterator should reduce by 1 every iteration
3. once end of iterator reached, swap index of number with last index
"""
def selection_sort(lst):
largest_index = 0
for i in range(len(lst)-1, 0, -1):
for j in range(i):
if lst[j+1] > lst[j]:
... |
import unittest
from parse import parse
def input_file():
# return the input_test file in a text
file = open('input', 'r')
text = file.read()
file.close()
return text
def output_file():
# read line of output_1 file
file = open('output', 'r')
res = [line.rstrip('\n') for line in file]... |
from dsa_util import *
from subprocess import Popen
before_path = r'Y:\TIM_3.1\TIM31_HigherTransitCoefficients\scenario\Output'
after_path = r'Y:\TIM_3.1\DVRPC_ABM_Github\scenario\Output'
outfile = r'D:\TIM3\BeforeAfterSPEmp.csv'
names = ['before', 'after']
fps = [os.path.join(before_path, '_person_2.dat'), os.path.... |
"""
Django settings for mail_server project.
Generated by 'django-admin startproject' using Django 2.0.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
... |
"""
统计生成所有不同的二叉树
题目: 给定一个整数N,如果N<1,代表空树结构,否则代表中序遍历的结果为{1,2,3.。。N}
请返回可能的二叉树结构由多少。
例如,N = -1时,代表空树结构,返回1;N=2时,满足中序遍历为{1,2}的二叉树结构只有图3-49所示的两种
所以返回结果为2.
进阶:N的含义不变,假设可能的二叉树结构由M种,请返回M个二叉树的头节点,每一颗二叉树代表一种可能的结构
"""
from question.chapter1_stack_queue_question.question9 import Node
def num_tree(n):
if n < 2:
return 1
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 23 14:40:03 2017
@author: jason
"""
import shapefile
import numpy as np
from sklearn.cluster import DBSCAN
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.io.img_tiles import OSM
osm_tiles = OSM()
proj = osm_tile... |
class DisjointSet(object):
def __init__(self, value):
self.rank = 0
self.representedBy = value
self.parent = None
class DisjoinSets(object):
def __init__(self):
# Hash table that stores the mappings of value -> node for fast access
self.dictionarySets = {}
# Creat... |
height1, width1, deepth1 = sorted(map(int, input().split()))
height2, width2, deepth2 = sorted(map(int, input().split()))
if height1 == height2 and width1 == width2 and deepth1 == deepth2:
print('Boxes are equal')
elif height1 <= height2 and width1 <= width2 and deepth1 <= deepth2:
print('The first box is sma... |
import rasa.utils.io as io_utils
from rasa.cli import x
def test_x_help(run):
output = run("x", "--help")
help_text = """usage: rasa x [-h] [-v] [-vv] [--quiet] [-m MODEL] [--no-prompt]
[--production] [--data DATA] [--log-file LOG_FILE]
[--endpoints ENDPOINTS] [-p PORT] [-t AUTH_T... |
def buildMethodTree(classesList, classesQueryDic):
for c in classesList:
for inherited in c.inheritedList:
if not inherited in classesQueryDic:
print "inherited classes not found"
raise Exception("inherited classes not found")
c.addParentClass(classesQueryDic[inherited])
classesQueryDic[inherited]... |
from models.expense import Expense
class PercentExpense(Expense):
def __init__(self, paid_by, amount, splits, expense_metadata):
super().__init__(paid_by, amount, splits, expense_metadata)
self.validate()
def validate(self):
split_percent = 0
for split in self.splits:
... |
import pymysql
from pandas import DataFrame
def connect_db():
sharenote_db = pymysql.connect(
user='root',
passwd='sharenotedev1!',
host='52.79.246.196',
port=3306,
db='share_note',
charset='utf8'
)
# data read -> 오늘 기준으로 전날 데이터 조회하는 쿼리 필요
cursor = ... |
#Reverse Cipher
message = "Three can keep a secret ,if thwo of them are dead."
translated =''
i = len(message) - 1
while i>=0:
translated = translated + message[i]
i = i-1
print(translated)
|
from django.shortcuts import render
from django.views.generic import(
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView,)
from .models import Post, Reply
from .forms import PostForm, ReplyForm
from django.urls import reverse_lazy
# Create your views here.
# def home(request):
# return ren... |
n = int(input())
c = 0
for i in range (0, n):
number = int(input())
if number == 0:
c = c+1
print(c) |
from django.apps import AppConfig
class mdbConfig(AppConfig):
name = 'mdb'
verbose_name = 'Django Movie Database'
def ready(self):
import mdb.signals
|
def f1(arg):
return arg + 2
def f2:
return 3
@f1(arg)
@f2
def func(): pass
#is equivalent to:
def func(): pass
func = f1(arg)(f2(func))
|
import torch
from torch.utils.data import Dataset
from torchvision import transforms
import numpy as np
import os
import random
import cv2
class CLSDataPrepare(Dataset):
def __init__(self, txt_path, img_transform = None):
self.img_list = []
self.label_list = []
with open... |
#!/usr/bin/env python3
import os
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import load_model
from keras.utils import CustomObjectScope
from keras.initializers import glorot_uniform
from model import eng_tokenizer,encode,rus_tokenizer,eng_max_sentence_length
def mapping(number,tokenizer):... |
from flask import Flask, request, jsonify, abort
import socket
import json
from flask_cors import CORS, cross_origin
#챗봇 엔진 서버 접속 정보
host = "127.0.0.1"
port = 5050
app = Flask(__name__)
#챗봇 엔진 서버와 통신
def get_answer_from_engine(bottype, query):
#챗봇 엔진 서버 연결
myApiSocket = socket.socket()
myApiSocket.connec... |
from flask import Blueprint, jsonify, request, send_file, render_template
import imageio
# imageio.plugins.ffmpeg.download()
from moviepy.editor import VideoFileClip
import os
import random
import json
import cv2
from ml_prod.image2text import model
from ml_prod.match import nli_predict
recommend_controller = Blueprint... |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pl
import matplotlib.cm as cm
import matplotlib.colors as colors
from matplotlib import rc, rcParams
rcParams.update({'font.size': 12})
import numpy as np
import os
import sys
import time
import yaml
import h5py
import argparse
from pathlib import Pat... |
import numpy as np
import preprocessing
import random_transformer
def test_filegen():
fs = preprocessing.get_wavs_from_dir("Data/Speaker_A/WAV")
wav = fs.__next__()
rg = preprocessing.MonoRawGenerator().gen(wav)
fg = preprocessing.FFTGenerator().gen(rg)
data = fg.__next__()
data = np.concatenate([data, fg.__n... |
'''
Stepik001132ITclassPyсh01p03st03TASK02__20200610.py
Даны три переменные, напиши такую программу, которая используя эти
переменные выведет текст: "Дважды два = четыре" без кавычек.
'''
b = 'два'
a = 'Дважды'
c = 'четыре'
print("{} {} = {}".format(a, b, c)) |
from django.db import models
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
class Post(models.Model):
Titulo = models.CharField(max_length=200)
Contenido = models.TextField()
Fecha_Creacion = models.DateTimeField('Fecha de creacion')
PUBLICO = 'pub'
P... |
from skbio import DNA, RNA, Sequence
rna_seq = RNA(open('raw.txt').read().replace('T','U'))
with open('moderna.gb', 'w+') as fh:
print(rna_seq.write(fh, format='genbank'))
|
import os
import csv
from datetime import datetime
import cv2
import face_recognition
import numpy as np
from datetime import date
#read chinese path name
def cv_imread(filePath):
cv_img=cv2.imdecode(np.fromfile(filePath,dtype=np.uint8),-1)
return cv_img
def encodeFaces(images):
encodelist = []
for i... |
"""Consensus Representation
@author: Soufiane Mourragui
This module computes the consensus representation between two datasets, by:
- Computing the domain-specific factors.
- Computing the principal vectors from source and target.
- Interpolating between the sets of principal vectors.
- Using KS statistics, finds th... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from app.models import Destination, UserProfile, Rating, Trip, BlogPost, Comment, PostImage
# Register your models here.
admin.site.register(Destination)
admin.site.register(UserProfile)
admin.site.register(Rating)
admin.... |
import logging
from django.shortcuts import render
from django.views import View
from django.http.response import JsonResponse
from .models import Meiju, MeijuTag, TagMeiju
from .models import model
class MeijuView(View):
def get(self, request, meiju_id):
meiju = model.get_meiju(meiju_id)
retur... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
p = head
while p:
if p.next:
q = p.next
if p.val == q.val:
# 重复, 进行删除
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 22 17:19:08 2018
@author: yiyuezhuo
"""
import json
import numpy as np
import os
def json2points(fname, verbose = True, detect=False):
with open(fname) as f:
obj = json.load(f)
arr = np.array(obj, dtype=np.int)
_fname, _ = os.path.splitext(fname... |
#!/usr/bin/env python
# encoding: utf-8
"""
This script is called by a bash completion function to help complete
the options for the diskutil os x command
Created by Preston Holmes on 2010-03-11.
preston@ptone.com
Copyright (c) 2010
Permission is hereby granted, free of charge, to any person obtaining
a copy of this... |
from email.message import EmailMessage
from smtplib import SMTP
from abc import ABCMeta, abstractmethod
import os
class EmailSender(metaclass=ABCMeta):
@abstractmethod
def send(self,msg: EmailMessage):
pass
class SimpleEmailSender(EmailSender):
SMTP_SERVER_PORT:str="SMTP_SERVER_PORT"
@classm... |
import socket
socket_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#Nos conectamos a la dirección y puerto del server
host = "127.0.0.1"
port = 8001
socket_client.connect((host,port))
var=True
while var==True:
mensaje = input("Cliente: ")
socket_client.send(mensaje.encode())
respuesta = s... |
#!/usr/bin/python
import threading
import time
class MyThread(threading.Thread):
def __init__(self,name,param):
threading.Thread.__init__(self)
self.setName(name)
self.thread_stop=False
self.param = param
def run(self):
for i in range(0,self.param):
if not s... |
# coding=utf-8
import pandas as pd
import numpy as np
import os
import math
import pickle
# 作图相关
import matplotlib.pyplot as pplt
# 分词
import jieba.posseg as pseg
# 文本特征提取:计数向量 / tf-idf向量
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
# 随机森林分类器
from sklearn.ensemble ... |
"""
This file is part of Linspector (https://linspector.org/)
Copyright (c) 2013-2023 Johannes Findeisen <you@hanez.org>. All Rights Reserved.
See LICENSE.
"""
class Database:
def __init__(self, configuration, environment, log):
self._configuration = configuration
self._environment = environment
... |
# Generated by Django 2.0.13 on 2020-09-25 15:19
from django.db import migrations, models
import django.db.models.deletion
import jsonfield.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('user_profile', '0001_initial'),
]
operations = [
migrations.Cr... |
def f(x,y,l,a):
p=a[x][y];t=0
for i in range(l):
for j in range(l):
if a[x+i][y+j]!=p:t=1;break
if t:break
if t:l//=2;return f(x,y,l,a)+f(x,y+l,l,a)+f(x+l,y,l,a)+f(x+l,y+l,l,a)
else:return str(p)
def solution(arr):k=f(0,0,len(arr),arr);return [k.count('0'),k.count('1')] |
from config import *
import time # 导入计时time函数
if os_platform == 'linux' or os_platform == 'Linux':
import RPi.GPIO as GPIO # 导入Rpi.GPIO库函数命名为GPIO
GPIO.setmode(GPIO.BOARD) # 将GPIO编程方式设置为BOARD模式
GPIO.setup(11, GPIO.OUT) # 设置物理引脚11负责输出电压
def LightBreath(light_code):
while True:
... |
from django.test import TestCase
from django.contrib.auth.models import User
from django.urls import reverse
from store.models import Group, Category, \
Product, Article, Customer, Order, Parameter
class TestView(TestCase):
def setUp(self):
user = User.objects.create_superuser(
username='t... |
from flask import Flask
app = Flask(__name__)
print(__name__)
#1)localhost:5000 - have it say "Hello World!" - Hint: If you have only one route that your server is listening for, it must be your root route ("/")
@app.route('/')
def hello_world():
return 'Hello Worl... |
import datetime
import re
log_line = '''183.60.212.153 - - [19/Feb/2013:10:23:29 +0800] "GET /o2o/media.html?menu=3 HTTP/1.1" 200 16691 "-" "Mozilla/5.0 (compatible; EasouSpider; +http://www.easou.com/search/spider.html)"'''
lst = []
tmp = ''
flag = False #用来判断 块语句
for word in log_line.split():
#print(word)
... |
# Generated by Django 2.2 on 2020-12-05 11:07
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
opera... |
from mongoengine import Document, fields
from mongoengine import connect
def init_db():
connect('madelyn-db')
class Product(Document):
price = fields.DecimalField(precision=2, required=True)
name = fields.StringField(required=True)
meta = {'allow_inheritance': True}
class Painting(Product):
material = fiel... |
import os
import json
import requests
import py7zr
url = 'https://arxiv.org/src/1911.12237v2/anc/corpus.7z'
corpus_dir = './data/samsum_corpus'
zip_fn = './data/corpus.7z'
def main():
if not os.path.isdir(corpus_dir):
os.makedirs(corpus_dir)
r = requests.get(url, allow_redirects=True)
open(... |
# scope
# what variables do we have access to
a = 1
def my_func():
a = 5
return a
print(a) # -> 1
print(my_func()) # -> 5 scope of a = 5 is limited to my_func
print(a) # -> 1 scope is still limited
# order of scope:
# 1 - local scope
# 2 - parent scope
# 3 - global scope
# 4 - built in python function
... |
from django.shortcuts import render
from .models import Comunidad,Evento,Solicitud,AgentesPatorales,Login
# Create your views here.
def Home(request):
return render(request,'core/index.html')
def ListadoComunidad(request):
listaComunidad = Comunidad.objects.all()
return render(request,'core/listarComunida... |
from keras.models import load_model
import paths
#Modelimizi loadlıyoruz
model = load_model(paths.modelpath)
import json
import numpy
import random
import yorumlayici
import pickle
import dusukprobability
import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
#Jsondaki her sentence
inte... |
"""
Architectures for sequence tagging task
"""
from keras_contrib.layers import CRF
from keras_contrib.losses import crf_loss
from keras_contrib.metrics import crf_accuracy
from keras.models import Model, load_model
from keras.layers import Input, Bidirectional, LSTM, TimeDistributed, Dense
from keras.utils import Se... |
import os
import shutil
import unittest
import tempfile
from bento._config \
import \
IPKG_PATH
from bento.core.node \
import \
create_root_with_source_tree
from bento.core.package \
import \
PackageDescription
from bento.core \
import \
PackageMetadata
from bento.core.p... |
import math as mp
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
import scipy.interpolate as sp
import time
class Computations(object):
def __init__(self):
self.weights = []
self.thita = [[1, 1, 1]]
self.flag = True
def read_fl(self, filename):
"""
Functi... |
import tweepy
import json
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.probability import FreqDist
from nltk.twitter import Twitter
consumer_key = "zkQZ4djk5UP7wVXseob8jJ6Vm"
consumer_secret = "umeeVPom6lC32sCthGcu8k1lsbAdEVKxUaHp2KtDUxb5VZAcnb"
access_token = "225... |
from django.conf.urls.defaults import *
urlpatterns = patterns('notificaciones.views',
# url(r'^name/$', 'name', name='name'),
) |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.views.generic import ListView
# Create your views here.
from players.models import Player
class PlayerList(ListView):
model = Player
def index(request):
num_players = Player.objects.all().count()
ret... |
# -*- coding: utf-8 -*-
import MySQLdb
from eod_aps.model.server_constans import ServerConstant
from eod_aps.model.instrument import Instrument
from decimal import Decimal
from eod_aps.tools.getConfig import getConfig
def test():
# host_server_model = ServerConstant().get_server_model('host')
# session = hos... |
from Start_up import *
from Bullet import Bullet
from Upgrades import*
class HealthBar:
def __init__(self, player):
self.x = 100
self.y = 10
self.player = player
self.bar = pygame.Surface((20 * self.player.health, 10))
self.bar.fill((0, 255, 0))
self.bar_back = pyga... |
from django.db import models
from datetime import datetime
# Create your models here.
class Storage(models.Model):
degree = models.CharField(verbose_name="分类", choices=(("wz", "网站"), ("rj", "软件"), ("qt", "其他")), max_length=4)
add_time = models.DateTimeField(verbose_name="存储时间", default=datetime.now())
ur... |
from pyb import UART
from lepton import flirLepton
uart = UART(1, 9600)
## initialize a lepton object on micropy boards SPI1 bus at 10500000 baud, I2C2 at 100000 baud
lepton = flirLepton()
##enable automatic histogram equalization on the Lepton module
lepton.AGC_enable()
## read a frames-worth of data into frame_... |
import sqlite3
def conexion():
conn = sqlite3.connect('Base_de_Datos.db')
return conn
def data_base_Asistencias(conn):
cursor = conn.cursor()
cursor.executescript("""
CREATE TABLE "Asistencias" (
"ID_Alumno" INTEGER NOT NULL,
"Nombre" TEXT,
"Apellido" TEXT,
"Fechas" TEXT,
"Materias"... |
from collections import deque
text = deque(input().split())
main_colors = ["red", "yellow", "blue"]
secondary_colors = ["orange", "purple", "green"]
secondary_colors_conditions = {
"orange": ["red", "yellow"],
"purple": ["red", "blue"],
"green": ["yellow", "blue"]
}
collected_colors = []
while text:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from math import log10
class Mapper:
def run(self):
data = self.readInput()
for cur_id, follow1 in data:
follow = int(follow1)
if follow == 1:
group = 0
else:
group = int(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.