text stringlengths 38 1.54M |
|---|
import pytube
import sys
import time
import gc
def downloadall(url):
video_list = []
# 导入URL到pytube库解析
video = pytube.YouTube(url)
# 输出视频中可供下载的视频Itag
print('以下是视频选择区域:')
for stream in video.streams:
if "video" in str(stream) and "mp4" in str(stream):
print(stream)
... |
def rss_feed(symbol = 0, write_pickle = True, read_pickle = False):
'''
Provides latest news from Yahoo Finance for each selected symbol.
Parameters
----------
symbol : string or list
Company ticker(s) either displayed as a string for one company or as ... |
import numpy as np
import torch
import cv2
from PIL import Image
import torch.nn.functional as F
import torch.nn as nn
from torch.autograd.variable import Variable
INPUT_PATH = 'input/'
# img = cv2.imread('./input/train/0cdf5b5d0ce1_01.jpg')
img = np.array(Image.open(INPUT_PATH + 'train_masks/{}_mask.gif'.format('0cdf... |
# -*- coding: utf-8 -*-
import sys
import os
import random
import time
import xml.etree.ElementTree as et
import logging
from logging import Formatter, FileHandler
from logging.handlers import SysLogHandler
import urllib2
class Application(object):
app_name = 'app_name'
def __init__(self):
self._par... |
# coding=utf-8
import logging
from datetime import datetime
from time import mktime, strftime, localtime
from flask_login import current_user, current_app
from celery.utils.log import get_task_logger
from app import db, cache, celery
from app.models.user import StreamStatus
from app.http.rong_cloud import ApiClient, C... |
import sys
import ctypes
import struct
a = 5
x=y=a
b = 125.54
c = 'Hello World!'
print(id(a)) # адрес памяти по которому лежим объект целого типа 5
print(sys.getsizeof(a))
print(ctypes.string_at(id(a), sys.getsizeof(a)))
print(struct.unpack('LLLcc', ctypes.string_at(id(a), sys.getsizeof(a))))
print(id(int))
|
from django import forms
from .models import Question, Answer
from django.forms import DateInput
class AnswerCreateForm(forms.ModelForm):
class Meta:
model = Answer
fields = ['answer']
|
# Таблица имен
_table = []
def openScope():
_table.append({})
def closeScope():
_table.pop()
def add(item):
last = _table[-1]
last[item.key] = item
def new(item):
pass
|
from django.shortcuts import render
def search_upload(request):
return render(request, 'imagesearch/search_upload.html', {})
|
from argparse import ArgumentParser
############################## User Settings #############################################
class Settings():
def __init__(self):
self.use_classifier = True # Toggles skin classifier
self.use_flow = False # (Mixed_motion only) Toggles PPG detection
# wit... |
word = input('Enter a word: ')
print("\nHere's each letter in your word")
for letter in word:
print(letter, end='')
input("\n\nPress the enter key to exit")
|
# import random
box = list(map(int, input().split()))
# box = [random.randrange(100000) for i in range(1000000) ]
target = int(input())
box = sorted(box)
count = 0
while True:
count+=1
if box[int(len(box)/2)] == target:
print("Yes")
break
if box[int(len(box)/2)] > target:
... |
"""
Simple Python application to show CI/CD capabilities.
"""
from bottle import Bottle, run
import cx_Oracle
import os
app = Bottle()
@app.route('/addition/<salary>/<amount>')
def addition(salary, amount):
return str(int(salary) + int(amount))
@app.route('/increment/<salary>/<percentage>')
def increment(sala... |
import cv2
import numpy as np
def generateSingleNumber(pathOf123,pathofa):
img=cv2.imread(pathOf123) #'/Users/zhangyiming/Desktop/workshop/123.jpg'
GrayImage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #将BGR图转为灰度图
ret,thresh1=cv2.threshold(GrayImage,130,255,cv2.THRESH_BINARY) #将图片进行二值化(130,255)之间的点均变为255(背景)... |
# coding: utf-8
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
from random import randint, choice
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib import cm
get_ipython().magic('matplotlib inline')
# In[2]:
... |
import unittest
import common
from l0112_path_sum import Solution
class Test(unittest.TestCase):
def test_solution(self):
self.assertEqual(
True,
Solution().hasPathSum(
common.create_binary_tree([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1]),
... |
import pytest
from rest_framework.test import APIClient
from author.models import User
@pytest.fixture
def client():
return APIClient()
@pytest.fixture
def author():
author = User(username='author', password='123456', avatar='avtr', is_author=True)
author.save()
return author
@pytest.mark.django_... |
#!/usr/bin/env python3
from Crypto.Util.number import *
from hashlib import sha1
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from secrets import flag, n
class coord:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"coord({self.x}, {self.y... |
# Copyright (c) 2022, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import numpy as np
from coremltools.converters.mil.mil import Builder as mb
from coremltools.convert... |
list = [{"name": "推荐食谱", "1": "症状", "name1": "浑身忽冷忽热"}, {"name": "绿豆薏米饭"}, {"name": "芝麻"}]
# res = [item[key] for item in list for key in item]
res = [item[key] for item in list for key in item ]
#print(res)
data = {'Uid': '12600742b9046b92dd218378d85b63a5',
'Message': '成功',
'Token': 'd00cNs4dAhY9VwJJ... |
import csv
from statistics import mean
import matplotlib.pyplot as plt
def get_from_csv(file_path):
reader = csv.reader(open(file_path), delimiter=' ')
return [[float(element) for element in elements[0].split(",")] for elements in reader][0]
def get_average_from_csv(file_path):
return mean(get_from_csv... |
for casos in range(int(input())):
dic, custo = [{}, 0]
for produtos in range(int(input())):
a, b = input().split()
dic[a] = float(b)
for compras in range(int(input())):
prod, quant = input().split()
custo += dic[prod] * int(quant)
... |
import random
from pico2d import *
meat_count = 0
class Meat18:
PIXEL_PER_METER = (10.0 / 0.1) # 10 pixel 30 cm
RUN_SPEED_KMPH = 17.0 # Km/Hour
RUN_SPEED_MPM = (RUN_SPEED_KMPH * 1000.0 / 60.0)
RUN_SPEED_MPS = (RUN_SPEED_MPM / 60.0)
RUN_SPEED_PPS = (RUN_SPEED_MPS * PIXEL_PER_METER)
image = ... |
"""
Using unofficial GoPro API to detect changes between to images.
Comparison time is around one minute
"""
from PIL import Image
import requests
import sys
import time
def setup_cam():
global all_adjusted
try:
json_stat = requests.get('http://10.5.5.9/gp/gpControl/status').json()
... |
# -*- coding: utf-8 -*-
# @Time : 2020/12/13 20:08
# @Author : fcj11
# @Email : yangfit@126.com
# @File : run_test.py
# @Project : crm自动化测试
import unittest
import time
from BeautifulReport import BeautifulReport
from config.config import REPORT_PATH, CASES_PATH
suite = unittest.defaultTestLoader.discover(CASES_PATH, '... |
import datetime
import luigi
from luigi import date_interval as luigi_date_interval
class BaseDateMixin(luigi.Task):
"""조회 일자(base_date)를 Parameter로 받는 클래스"""
today = datetime.datetime.today()
yesterday = today - datetime.timedelta(days=1)
base_date = luigi.DateParameter(default=yesterday)
class Da... |
# -*- coding: utf-8 -*-
import pytest
from kartothek.io.eager import build_dataset_indices
from kartothek.io.testing.index import * # noqa: F4
@pytest.fixture()
def bound_build_dataset_indices():
return build_dataset_indices
|
import select
import socket
import uuid
import random
import string
from enum import Enum
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from aes_cipher import AESCipher
from connection.file import File, FileToReceive, FileToSend
from connection.header import Header, ContentType, FileState
from key_ma... |
'''
game involves a 1d board with numbers
you start on the left and end when you get past the last square
each time you roll a die
whatever it lands on
multiply that by the cotents of your current square
and move forward in the array by that amount
question:
what is the expected number of steps it will take to re... |
from django.db import models
from solo.models import SingletonModel
from django.core.validators import MaxValueValidator, MinValueValidator
class SiteUser(SingletonModel):
name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(max_length=50, null=True,... |
import pyupbit
import numpy as np
K = 0.5 # K값 (범위: 0~1)
# 코인 종목
# stock_symbol = "KRW-BTC"
stock_symbol = "KRW-ETH"
# stock_symbol = "KRW-DOGE"
# OHLCV(open, high, low, close, volume)로 당일 시가, 고가, 저가, 종가, 거래량에 대한 데이터
df = pyupbit.get_ohlcv(stock_symbol, count=7)
# 변동폭 * k 계산, (고가 - 저가) * k값
df['range'] = (df['h... |
USERNAME = "root"
PASSWORD = "baobao"
DBNAME = "QuestionnaireSystem"
HOST = "127.0.0.1"
PORT = "3306"
|
from tkinter import*
from tkinter import ttk,messagebox
from PIL import Image,ImageTk
import pymysql
class Register:
def __init__(self,root):
self.root=root
self.root.title("Registation Window")
self.root.geometry("1350x700+300+150")
self.root.config(bg="white")
#========Bg I... |
class Solution(object):
### inorder traversal
def isValidBST(self, root):
output = []
self.inorder(root, output)
for i in range(1, len(output)):
if output[i-1] >= output[i]:
return False
return True
def inorder(self, root, output):
if r... |
import json
topic_path = "../airs2017-collection/topic/"
def topic_stats():
av_sent_len = 0
av_para_len = 0
for topic in range(1, 101):
topic_case_id = 0
skip_write = False
topic_file_name = topic_path + str(topic) + ".json"
with open(topic_file_name) as topic_file:
topic_data = json.load(topic_file)
... |
import math
from collections import Counter
from random import random
import nltk
import pandas as pd
from nltk.corpus import stopwords, wordnet
from nltk.stem import WordNetLemmatizer
from prettytable import PrettyTable
lemmatizer = WordNetLemmatizer()
stop_words = set(stopwords.words('english'))
def clean_text(te... |
__author__ = 'Voronin Denis'
import sl4a
import time
import types
droid = sl4a.Android()
Marks = types.SimpleNamespace()
Marks.name = ''
Marks.shirota = 0.0
Marks.dolgota = 0.0
Marks.coordinate = ''
class Mark:
def get_coordinate(self):
self.droid.startLocating()
time.sleep(15)
loc = se... |
from . import db
from .abc import BaseModel
import datetime
class User(db.Model, BaseModel):
username = db.Column(db.String, primary_key=True, unique=True, nullable=False)
avatar_url = db.Column(db.String, nullable=True)
date_created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
password ... |
from airflow.models import DAG
from airflow.providers.apache.spark.operators.spark_sql import SparkSqlOperator
from airflow.providers.jdbc.operators.jdbc import JdbcOperator
from airflow.utils.dates import days_ago
from datetime import timedelta, datetime as dt
args = {
'owner': 'Seshu Edala',
}
with DAG(
dag... |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, logout, login
f... |
# Implement a URL shortener with the following methods:
# shorten(url), which shortens the url into a six-character alphanumeric string, such as zLg6wl.
# restore(short), which expands the shortened string into the original url.
# If no such shortened string exists, return null.
# Hint: What if we enter the same URL ... |
import re
import sys
from Bio import SeqIO
from Bio.Seq import Seq
##infile = open(sys.argv[1],"r")
##outfile = open(sys.argv[2],"w")
##inconv = open(sys.argv[3],"r")
outfile = open("/Users/mjohnpayne/Documents/Uni/phd/Asp_sequences/MEGA_analysis/500bp_5prime_alignment/1000bp_5prime_seq_asps_mod.fasta","w")
inconv ... |
import os
import cv2 as cv2
import numpy as np
from models.model_custom_densenet_segmentation_v1 import model_custom_densenet_segmentation_v1
from util.segmentation_dataloader_v1 import segmentation_dataloader_v1
sample_loader = segmentation_dataloader_v1('D://portrait-dataset//train_input256x256//', 'D://portrait-da... |
#this script extracts ensembl gene ID, gene length, and count from featureCounts output and converts Ensembl geneID to EntrezID usi ng myGene package. Discards any Ensembl entry without an EntrezID associated.
# changed to just extracting ensembl ID since mygene querying took so long
# instead using convert2entrez.R f... |
from sense_hat import SenseHat
from time import sleep
sense = SenseHat()
sense.clear()
black=(0,0,0)
x=0
y=0
while True:
sense.set_pixel(x,y,(0,0,255))
for event in sense.stick.get_events():
#print("Joystic was {} {}".format(event.action,event.direction))
if(event.action=="pressed" and event.dir... |
import tkinter
from tkinter import ttk
import os
# 点击左边的目录树展示到右边 右边的Frame
class InfoWindow(ttk.Frame):
def __init__(self, master):
frame = tkinter.Frame(master)
#放大右边
frame.grid(row=0, column=1)
#创建输入控件
#给entry绑定变量
self.ev = tkinter.Variable();
self.entry... |
from .action import Action
class BuiltInCmds:
cmds = { 'D': Action.DEBUG,
'd': Action.DEBUG,
'debug': Action.DEBUG,
'Debug': Action.DEBUG,
'DEBUG': Action.DEBUG,
'x': Action.EXIT,
'X': Action.EXIT,
'q': Action.EXIT,
... |
import numpy as np
from utils.algorithms import RLAlgorithm as Algorithm
from utils.policies import Policy
class Agent(object):
def __init__(self,
algorithm = 'qlearning',
policy = "eps_greedy",
nA = 10,
nS = 4**4,
lvfa = False,
feature_size = 13,
alpha = 0.01,
gamma = 0.99,
... |
# Generated by Django 2.1.5 on 2020-04-24 16:25
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('usuarios', '0028_elementosdiscapacidad_tiposrehabilitaciondiscapacidad'),
]
operations = [
migr... |
#-*- Coding:utf-8 -*-
# Author: D.Gray
'''
未使用Call方法,实例化对象后,这个实例对象后面就不能在加括号
'''
class Dog(object):
def __init__(self,name):
self.name = name
# def eat(self,food):
# print("%s 吃 %s"%(self.name,food))
def __call__(self, *args, **kwargs):
print("running call",args,kwargs)
def __s... |
# coding=utf-8
from . import upload
from flask import render_template, url_for, request
from .. import db, bootstrap, basedir
from ..models import Image
from ..forms import UploadForm
import os
from werkzeug.security import gen_salt
folder = os.path.join(basedir, 'static', 'images') # 图片保存的文件夹
# 验证上传文件类型是否为支持格式图片
de... |
# Generated by Django 2.0.1 on 2019-01-14 22:46
from django.db import migrations, models
import django.db.models.deletion
import freshsheet.models
class Migration(migrations.Migration):
dependencies = [
('freshsheet', '0042_auto_20190108_0000'),
]
operations = [
migrations.AlterModelMan... |
# -*- encoding: utf-8 -*-
'''
Current module: pyrunner.drivers.uiautomator.driver
Rough version history:
v1.0 Original version to use
********************************************************************
@AUTHOR: Administrator-Bruce Luo(罗科峰)
MAIL: lkf20031988@163.com
RCS: rock4.softte... |
# Implement the following functions
# Activation (sigmoid) function
def sigmoid(x):
return np.divide(1, 1 + np.exp(-x))
# Output (prediction) formula
def output_formula(features, weights, bias):
return sigmoid(( weights[0] * features[0] )+ ( weights[1] * features[1] ) + bias)
# Error (log-loss) formula
def e... |
#coding:utf-8
#################################
#Copyright(c) 2014 dtysky
#################################
import re
import sys
import os
from ctypes import *
import codecs
import hashlib
import locale
user32 = windll.LoadLibrary('user32.dll')
MessageBox = lambda x:user32.MessageBoxA(0, x, 'Error', 0)
class MyFS():
... |
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect
from .models import Produto, Pedido, Produto1
from .forms import pedidoForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.paginator... |
import struct
import datetime
class Logger:
def __init__(self, working_dir):
self.working_dir = working_dir
def log_base(self, level, s):
msg = '{}: {}'.format(datetime.datetime.now(), s)
if self.working_dir is not None:
with open(self.working_dir + 'log.txt', 'a') as f:
... |
def trans():
t = str.maketrans("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM")
x = str(input("What do you want to translate? "))
print(x.translate(t))
trans()
|
#!/usr/bin/env python3
#! -*- coding:utf-8 -*-
import uvicorn
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI(openapi_url="/help/openapi.js",docs_url="/help/docs",redoc_url="/help/redoc")# 设置api路径
@app.get("/ping/{key}",summary="crack hackbar plugin.",tags=["crack"])
async def cr... |
from plenum.test.bls.helper import check_bls_multi_sig_after_send
from plenum.test.pool_transactions.conftest import looper, clientAndWallet1, \
client1, wallet1, client1Connected
nodeCount = 7
nodes_wth_bls = 7
def test_each_node_has_bls(txnPoolNodeSet):
for node in txnPoolNodeSet:
assert node.bls_bf... |
test_case = input().split()
for i in range(1, int(test_case[2]) + 1):
x = int(test_case[0])
y = int(test_case[1])
if i % x == 0 and i % y ==0:
print("FizzBuzz")
elif i % x == 0:
print("Fizz")
elif i % y == 0:
print("Buzz")
else:
print(i)
|
# -*- coding: utf-8 -*-
# @author: franky
# @email: runping@shanshu.ai
# @date: 2018/08/02
import configparser
import os
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) + '/..'
def preprocess_param(param):
dict_param = {}
for key, value in param:
if value.isdigit():
dict_param[... |
import os
import torch
from torch.utils.data import DataLoader
import wandb
from dataset import AlbumentationDataset
from model import MyModel
from tqdm import tqdm
import numpy as np
from GPUtil import showUtilization as gpu_usage
from datetime import datetime, timedelta, timezone
import albumentations as A
class T... |
# coding=utf-8
"""
Girdiğimiz sayıların yapacağımız işleme göre
bize sonucunu gösterecek bir uygulama
"""
# Toplama
print "toplam = ", 3 + 4 # 3 + 4 = 7
# Çıkarma
print "Fark = ", 12 - 5 # 12 - 5 = 7
# Çarpma
print "Çarpım = ", 3 * 9 # 3 * 9 = 27
# Bölme
print "Bölüm = ", 34 / ... |
import sys
import csv
import unicodedata
from django.core.management.base import BaseCommand
from authlog.models import Access
import six
CSV_HEADERS = [
'login_time', 'ip_address', 'ip_forward', 'user', 'path_info', 'user_agent',
'get_data', 'post_data', 'http_accept', ]
class Command(BaseCommand):
args... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @author: junfeng
# @contact: junfeng_pan96@qq.com
# @file: interval_tree.py
# @time: 2018/4/9 10:39
# @desc:
from data_structure.red_black_tree.red_black_tree import RBTreeNode, RBTreeColor, RBTree
class IntervalData:
def __init__(self, low, high):
self.low = ... |
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def create_bst(arr, start_index, end_index):
if start_index > end_index:
return None
elif start_index == end_index:
mid = start_index
else:
mi... |
# Copyright (c) 2019 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from typing import Set
from PyQt5.QtCore import QObject, pyqtSignal
class SettingVisibilityHandler(QObject):
def __init__(self, parent = None, *args, **kwargs) -> None:
super().__init__(parent = parent, *arg... |
import boto3
#aws ses create-template --cli-input-json file://mytemplate.json
#SES Sandbox
source_email = ''
template_name = 'MyTemplate'
def send_email(email, name, html_msg, text_msg):
client = boto3.client('ses',
region_name="us-east-1")
data = '{{ "name":"{}", "htmlreport": "{}", "te... |
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User
from django.db import models
class Watched(models.Model):
"""Watched model"""
STATUS_CHOICES = (
(1, 'Active'),
(2, 'Inactive'),
)
... |
from curtsies.input import *
def main():
"""
Reads and returns user input; after 2 seconds, 1 second, .5 second
and .2 second, respectively, an event -- user input -- is printed,
or "None" is printed if no user input is received.
"""
with Input() as input_generator:
print(repr(input_g... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 26 22:02:07 2018
@author: KushDani
"""
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd #library for data manipulation and analysis
#in particular, it of... |
# Copyright (c) 2019 The Erizo Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
#
# This code is part of the Fatiando a Terra project (https://www.fatiando.org)
#
"""
Gridding 2-component GPS coupled by elasticity
============================================... |
# -*- encoding: utf-8 -*-
'''
@file game.py
@brief Implementa la clase Game
@author José Jesús Marente Florín
@date Octubre 2010.
'''
import pygame
import data
import resource
import keyboard
import mouse
import intro
import xml.dom.minidom
import os
import config
import modes
class Game:
'''
@brief Clase en... |
import sys
def isJolly(lista):
tamanho = int (lista[0])
listaDiferencaAbsoluta = []
i = 1
while (i < tamanho):
# print(lista[i], lista[i+1])
listaDiferencaAbsoluta.append(abs(lista[i] - lista[i+1]))
i += 1
# print(listaDiferencaAbsoluta)
listaDiferencaAbsoluta.sort(reverse = True)
# print(listaDife... |
class News(object):
def __init__(self, url, typeName, timeStamp, source, content, title):
self.__url = url
self.__typeName = typeName
self.__timeStamp = timeStamp
self.__source = source
self.__content = content
self.__title = title
def display(self):
print... |
# -*- coding: utf-8 -*-
import sqlite3
from .items import Link
class SQLitePipeline:
create_rqst = """
CREATE TABLE IF NOT EXISTS {}
(
text TEXT NOT NULL,
url TEXT NOT NULL,
referer_url TEXT NOT NULL,
status_code INT NOT NULL
)
"""
clear_rqst = """
DELETE FROM {}
"""
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, redirect
from forms import RegistrarOwner, LoginOwner
from django.core.urlresolvers import reverse
from django.contrib import messages
from usuarios.models import Usuario, Ciudad
from django.utils import timezone
from d... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from xiachufang.items import XiachufangCategoryItem,XiachufangCaiPuItem
import re
from scrapy_redis.spiders import RedisCrawlSpider
"""
1.获取所有的菜单分类列表存储到数据库(url, 名称,分类的id)
2.获取菜单分类下所有的菜品详情信息... |
# 生成器----多任务(多任务三种模式:协程、进程、线程,本例协程)
def test1():
while True:
print("------1-------")
yield None
def test2():
while True:
print("------2-------")
yield None
t1=test1()
t2=test2()
while True:
print(t1.__next__())
print(t2.__next__()) |
import habitat
import numpy as np
from perceptionDataGen import ClassifierDataGenerator
import matplotlib.pyplot as plt
import random
from math import sqrt, floor
object_to_classify = {1: 'wall',
4: 'door',
17: 'ceiling',
2: 'floor',
... |
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2010, 2012-2013 Rocky Bernstein <rocky@gnu.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at... |
DEBUG = True
SECRET_KEY = 'test'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'tests.database.db',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
ROOT_URLCONF = 'urls'
MIDDLEWARE_CLASSES = ()
TEMPLATE_CONTEXT_PROCESSORS =... |
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('xmlserver',
# Examples:
# url(r'^$', 'xmlserver.views.home', name='home'),
# url(r... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-22 11:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('topics', '0002_subtopic_is_quiz'),
]
operations = [
migrations.AddField(
... |
"""Script to post csv into database"""
import pandas as pd
from sqlalchemy import create_engine
#File to read
FILE_TO_PUT_IN_DB = pd.read_csv('/location/of/file.csv')
#Converting column names to lower case
FILE_TO_PUT_IN_DB.columns = [c.lower() for c in FILE_TO_PUT_IN_DB.columns]
#Postgres connection (make sure the... |
import wx
import sqlite3 as db
import Graph
from IDs import *
from math import *
class interface(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, frame_id, 'flight tool', size=(1000,500))
self.graph = Graph.Graph()
'''
panels
'''
self.panel1 = wx.Panel(se... |
#This program counts the number of occurences of each letter in a string
#Will also import pretty print to ensure output is more readable
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[char... |
from appconf import AppConf
from django.conf import settings # noqa
class MyAppConf(AppConf):
# Size of chunks what will be used to select data from table.
SELECT_BATCH_SIZE = 20000
# Size of chunks what will be used to update data in table.
UPDATE_BATCH_SIZE = 500
# Default folder with model d... |
from utilities.statusoftesst import status
import unittest
import pytest
from pages.courses.register_courses_page import RegisterCoursesPage
from pages.Home.login_page import LoginPage
@pytest.mark.usefixtures("oneTimeSetUp", "setUp")
class RegisterCoursesTests(unittest.TestCase):
@pytest.fixture(autouse=True)
... |
from threading import Thread
import pywebserver.config
import os, sys
import importlib
importlib.reload(pywebserver.config)
Configuration = pywebserver.config.Configuration
def getfile(fname, parser):
if Configuration.parsing["Python"] and fname.endswith(".py"):
spec = importlib.util.spec_from_file_locati... |
from io import StringIO
from Bio import Phylo
import plotly.plotly as py
from plotly.graph_objs import *
import igraph
from igraph import *
treedata = "(ta:0.145313, (pa:0.142047, (ml:0.165216, (hi:0.210634, (mr:0.146529, (ne:0.102035, (sa:0.105757, (gu:0.110000, bn:0.117400):0.013043):0.025140):0.016884):0.016691):... |
# A. Create a program displaying the below output:
# Enter value for x : 8
x = int(input("Enter value for x: "))
# Enter value for y : 10
y = int(input("Enter value for y: "))
# The expression (2x 5y) will return the value 66
print((2 * x) + (5 * y)) |
import cv2
image = cv2.imread('005.jpg',0)
cv2.imshow("Original", image)
kernelSizes = [(3, 3), (9, 9), (15, 15)]
# 对使用不同大小的内核对原图像进行平均模糊
for (kX, kY) in kernelSizes:
blurred = cv2.blur(image, (kX, kY))
cv2.imshow("Average ({}, {})".format(kX, kY), blurred)
cv2.waitKey(0)
|
#Autor: Lalykin Oleg
#installation commands:
#pip install py_expression_eval
#pip install tabulate
#pip install matplotlib
import math
from tabulate import tabulate
from py_expression_eval import Parser
import matplotlib.pyplot as plt
parser = Parser()
expr = parser.parse("x^2")
A = -10
B = 10
EP... |
from ...biotools import score_to_formatted_string
from ...Location import Location
from ...reports import colors_cycle
class SpecEvaluations:
"""Base class for handling lists of SpecEvaluations.
See ProblemObjectivesEvaluations and ProblemConstraintsEvaluations for
the useful subclasses.
Parameters
... |
lyrics = "Ah, Ba Ba Ba Ba Barbara Ann Ba Ba Ba Ba Barbara Ann Oh Barbara Ann Take My Hand Barbara Ann You Got Me Rockin' And A-Rollin' Rockin' And A-Reelin' Barbara Ann Ba Ba Ba Barbara Ann ...More Lyrics... Ba Ba Ba Ba Barbara Ann Ba Ba Ba Ba Barbara Ann"
# print(lyrics) #set up to check output
#separte string into... |
from django.urls import path
from . import views
urlpatterns = [
path('data/<int:year_number>/', views.dataframe_view, name="dataframe view"),
path('dataall/<int:year_number>/', views.dataframe_all_view, name="dataframe_all view"),
path('pca/<int:year_number>/', views.pca_view, name="pca view")
]
|
import serial
import time
import subprocess
ser = serial.Serial('/dev/ttyACM0',9600)
line = 0
def main():
while 1:
listen()
def show_image1():
print 'show image 1'
subprocess.call('bash display_image.sh haveanawesomeday.jpg', shell=True)
def show_image2():
print 'show image 2'
subprocess.call('bash ... |
"""
WSGI config for cocus_project project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
import os
from dj_static import Cling
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cocus_project.settings')
application = Cling(get_ws... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.