text stringlengths 8 6.05M |
|---|
import time
import unittest
from appium import webdriver
class AndroidTests(unittest.TestCase):
def setUp(self):
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '10'
desired_caps['deviceName'] = 'Mi A2'
desired_caps['appPackage'... |
import math
import asyncio
from pythonosc.osc_server import AsyncIOOSCUDPServer
from pythonosc.dispatcher import Dispatcher
from pythonosc.udp_client import SimpleUDPClient
import obspython
from collections import OrderedDict
# GLOBALS
AUDIO_SOURCES = {}
# CONSTANTS
IP = "0.0.0.0"
PORT = 8000
# Close any eventu... |
#returns the result of the club conquest command
import commands.advancedhelp as ah
import discord
import math
CQ_COMMAND = '!cq-time'
def getResponseMessage(msg):
#first check if the user wants advanced help, if not return other message
msg = msg.content
adv_help = ah.getIfAdvancedHelp(msg)
if adv_help:
... |
#!/usr/bin/python
# When you create a 2D array in Python as a list of nxm filled
# by zeros. This is wrong, as each list [0]*3 is a reference to
# a list of m zeros. This is why modifying a[0][0]=5 also changes
# a[1][0]=5.
a = [[0]*3]*4
a[0][0] = 2
print("We only set a[0][0]=5, the rest should be 0's but...")
print... |
#!usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:yaoli
@file: 1.1.py 基本数据结构
@time: 2018/03/18
"""
#Python3 中共有六个标准的数据类型:
# Number (数字) String(字符串) List(列表)Tuple(元组)Sets(集合)Dictionary(字典)
counter = 100 # int
miles = 1000.0 # float
name = "liyao" # string
print (counter)
print (miles)
print (name)
... |
import random
import sys
name = input("Please enter your name: ")
# MAIN MENU
def main_menu():
print("\nHello, " + name + """
--- Main Menu ---
Press 1 to play
Press 2 to quit
""")
menu_selection_word = input("please select your option: \n")
try:
menu_selection_int = int(me... |
a=int(input())
b=0
for i in str(a):
b=b+int(i)
print(b)
|
import argparse
import sys
sys.path = sys.path[1:]
sys.path.append("/home/machen/face_expr")
import chainer
from graph_learning.dataset.graph_dataset_reader import GlobalDataSet
from dataset_toolkit.adaptive_AU_config import adaptive_AU_database
from graph_learning.dataset.graph_dataset import GraphDataset
from graph_l... |
a=int(input())
b=1
d=1
while (b<=a):
c=int(input())
if (c<=d):
min=c
else:
min=d
e=min
d=e
b=b+1
print(min)
|
import pandas as pd
import numpy as np
import torch
from torch.utils.data import DataLoader
from torch import nn
import torch.nn.functional as F
import torch.optim
torch.cuda.manual_seed_all(123456)
torch.manual_seed(123456)
import click
import logging
from ilovemhc.wrappers import *
from ilovemhc import dataset
f... |
import os
from face_tracker import _crop_video
from pytube import YouTube
yt_baseurl = 'https://www.youtube.com/watch?v='
import argparse
import shutil
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-b', "--batch_id",
type=int,
default=1)
... |
#!/usr/bin/python3
"""
model city class
"""
from models.base_model import BaseModel
class City(BaseModel):
"""
public class attribute contains empty strings with state_id and name
"""
state_id = ""
name = ""
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os,sys,Gnuplot,time
from file_managers import defectFrames
nom_fitxer_defectes = "historia_defectes_n"
def wait(for_this=0.01):
time.sleep(for_this)
def main(directori, fitxer=None):
if fitxer is None:
fitxer = nom_fitxer_defectes
fitxer =... |
"""
This file defines class RoutingSequential.
@author: Clemens Rosenbaum :: cgbr@cs.umass.edu
@created: 6/13/18
"""
from collections import OrderedDict
import torch.nn as nn
from PytorchRouting.CoreLayers.Initialization import Initialization
from PytorchRouting.CoreLayers.Selection import Selection
from PytorchRouti... |
# python 2.7.3
import sys
import math
n = input()
password = {}
userInSys = set()
for i in range(n):
line = sys.stdin.readline()
words = line.split()
user = words[1]
if words[0] == 'register':
passwd = words[2]
if user in password:
print 'fail: user already exists'... |
from flask_restplus import Namespace, Resource
from flask import request
from bookapp import schemas, models
ns = Namespace('admin', description='Admin operators')
_user_req = ns.model(
'user_request', schemas.AdminSchema.schema_user_req)
_user_res = ns.model(
'user_response', schemas.AdminSchema.schema_user_re... |
global level,path,path2
start=self.ghosts[0]
end=self.pacman
start2=self.ghosts[1]
# end2=(random.choice(self.food))
end2=(self.pacman[0],self.pacman[1]-4)
cost=1
prev_path=path
prev_path2=path2
#try excepting to quick code boundary conditions and end of game scenes
try:
path=searc... |
from conversion.ena.base import BaseEnaConverter
from datetime import date
from typing import Dict, List, Tuple
from xml.etree.ElementTree import Element
from lxml import etree
from submission.entity import Entity
from submission.submission import Submission
from .project import EnaProjectConverter
from .study import... |
from sqlite_engine import db_session
from sql_config_model import Config
from sqlalchemy import exc
try:
cfg = Config('config1', './Path/to/config1')
db_session.add(cfg)
db_session.commit()
except exc.SQLAlchemyError as ex:
print("Na")
try:
db_session.rollback()
res = Config.query.all()
pr... |
print ("Questao 3")
print ("Consumo do veiculo / KM/L")
m = input ("Distancia ")
m = float(m) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import os
import stat
import platform
from conans import tools
from conans.test.utils.test_files import temp_folder
class WhichTest(unittest.TestCase):
@staticmethod
def _touch(filename):
with open(filename, 'a'):
os.utime(file... |
# -*- coding: utf-8 -*-
from django.conf.urls import url
from press import views
urlpatterns = (
url(
r'^(?P<lang>\w{2})/press/$',
views.PressIndexView.as_view(), name='press_index'
),
url(
r'^(?P<lang>\w{2})/press/page/(?P<page>[0-9]{1,4})/$',
views.PressIndexView.as_view... |
# encoding: utf-8
# pylint: disable=invalid-name,unused-argument,too-many-arguments
"""
单元测试相关的Invoke模块
"""
import logging
from invoke import task
log = logging.getLogger(__name__) # pylint: disable=invalid-name
@task(
default=True, help={"directory": "单元测试目录", "with-pdb": "开启pdb支持 (默认:否)",},
)
def tests(conte... |
import django.contrib.auth.models as auth_models
import django.contrib.contenttypes.models as contenttypes_models
from django.core.management import call_command
import pytest
from daf import actions
import daf.models as daf_models
@pytest.mark.django_db
def test_install(mocker):
"""
Test permissions.install... |
import csv
import matplotlib.pyplot as plt
from statistics import mean
import numpy as np
def run():
x, y = read_fix()
plot(x, y)
def plot(x, y):
plt.plot(x, y ,'ro')
plt.axis([0, 100, 0, 100])
plt.show()
def read_fix():
point = []
with open('dead point dmn '+str(0.1)+'.csv', 'r') as ... |
# Generated by Django 2.1.11 on 2020-01-20 09:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('procedure', '0006_auto_20200120_0908'),
]
operations = [
migrations.AddField(
model_name='proc... |
"""
created by ldolin
"""
"""
爬虫回顾:
1.请求模块 urllib.request
1.构建请求对象:
Request(headers=headers)
2.发请求获响应
urlopen(请求对象)
2.请求对象的方法request:
1.get_header('User-agent')
3.响应对象的方法 response
1.read() 读取响应的内容
2.decode()将bytes转str
3.getcode()获取响应... |
from nose.tools import with_setup, ok_, eq_, assert_almost_equal, nottest, assert_not_equal
import torch
from gtnlplib.constants import *
import numpy as np
#8.1a
def test_model_en_dev_accuracy1():
confusion = scorer.get_confusion(DEV_FILE,'bakeoff-dev-en.preds')
acc = scorer.accuracy(confusion)
ok_(acc >... |
class Solution:
def numberToWords(self, num):
to19 = 'One Two Three Four Five Six Seven Eight Nine Ten Eleven '\
'Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen '\
'Nineteen'.split()
tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split()
... |
from flask import Blueprint
# 创建主页蓝图
index_blue = Blueprint('index', __name__)
# 导入views
from . import views
|
import numpy as np
from time import time
import random, string
random.seed(9001)
from Model.model import Model
m = Model(print_obj={
'timing': True
})
def get_keys(obj):
keys = []
for ing in obj:
keys.append(ing)
return keys
def get_by_key(obj,key, key_list=False):
arr = []
if key_li... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 什么是面向对象
#需求
# - 老妈的交通工具有两个,电动车和自行车
# - 家里离菜场共 20 公里
# - 周一的时候骑电动车去买菜,骑了 0.5 小时
# - 周二的时候骑自行车去卖菜,骑了 2 小时
# - 周三的时候骑电动车去卖菜,骑了 0.6 小时
# - 分别输出三天骑行的平均速度
class Vehicle():
def __init__(self, kind):
self.kind=kind
def grocery_v(self, time, date):
v=20/time
print '%s骑%s平均... |
from . import statistics
from django import forms
class PredictionForm(forms.Form):
category_choices,content_choices,genre_choices=statistics.get_choices()
appName = forms.CharField(label='App Name',widget=forms.TextInput(attrs={'placeholder':'Enter App Name'}))
size = forms.IntegerField(label='Size',min_... |
import math
print(math.ceil(4.4)) # ceiling id going to round up the value
print(math.floor(4.4)) # floor is going to round down the file
print(math.fabs(-4.4)) # fabs is going to knock of the aboslute value
print(math.factorial(6)) # going to give factorial of a number
print(math.fmod(4,2)) # is going to five bac... |
import sys
import os
if os.path.exists("tests/../src/"):
sys.path.append("tests/../src/") # when calling pytest from root
if os.path.exists("../src/"):
sys.path.append("../src/") # when calling pytest from tests
|
''' contact db creation '''
import sqlite3
DB = sqlite3.connect("createDB/contacts.sqlite")
NEW_EMAIL = "anotherupdate@update.com"
PHONE = "1234"
#UPDATE_SQL = "UPDATE contacts SET email = 'anotherupdate@update.com' WHERE phone = 1234"
UPDATE_SQL = "UPDATE contacts SET email = ? WHERE phone = ?"
UPDATE_CURSOR = DB.cu... |
from django.db import models
class Shelf(models.Model):
name = models.CharField(max_length=128,unique=True)
@property
def dict(self):
books = []
for shelved in self.shelved_set.all():
books.append((shelved.book.title,shelved.shelved_times))
print books[0]
books.... |
import u12
from time import sleep
from time import time
from scipy.integrate import simps
import datetime
import csv
import numpy as np
import sys
sys.path.insert(0, '/home/egs/UHV-chamber-controls/funcs')
from funcs import PID
d2=u12.U12(serialNumber=100035035)
#d1=u12.U12(serialNumber=100054654)
d1=d2
time_iter=0.3... |
n = int(input())
odd_sum = 0
odd_min = "No"
odd_max = "No"
even_sum = 0
even_min = "No"
even_max = "No"
for i in range(1, n + 1):
currentNum = float(input())
if i == 1:
odd_min = currentNum
odd_max = currentNum
elif i == 2:
even_min = currentNum
even_max = currentNum
... |
#!/usr/bin/env python3
"""Modifies a sites logging level
site_id -- numerical site id to retrive
log level -- log level to set
api_id -- API ID to use (Default: enviroment variable)
api_key -- API KEY to use (Default: enviroment variable)
"""
from .com_error import errorProcess
from .sendRequest import ApiCreden... |
fruit ='banana'
count = 0
sum = 0
for letter in fruit:
if letter == 'a':
count = count+1
print('Total no of a letters in the fruit is',count)
print('Total no of letters in the fruit is',len(fruit))
|
"""
Package for RestTutorial.
"""
|
from game.items.item import Ore
class IronOre(Ore):
type = 'Iron'
name = 'Iron Ore'
value = 17 |
#Python Richter Scale Calculation
#Brandon Garsson
#s1293728
gameOver=False
print("Enter the Richter scale value or -99 to end: ")
while gameOver==False:
r=float(input("Enter the Richter value: "))
if r >= 8.0:
print("Most structures will fall\n")
elif r >= 7.0:
print("Many buildings des... |
from Instruction import *
class InstCPU(Instruction):
"""Instrucción de CPU"""
def __init__(self,textCPU,time):
Instruction.__init__(self,textCPU,time)
def execute(self,cpu,pcb):
"""Simula su ejecución"""
Instruction.execute(self,cpu,pcb)
print("@CPU: Se ha ejecut... |
import numpy as np
GAMMA = np.exp(-5)
NSUBSETSIZE = 100
BOUND = 100
NN = 1000
BIN0 = 10
BIN1 = 30
P = 1.06900842285
L = 0.089076761067
|
from django.shortcuts import render, redirect
from .models import Board, Photo, Profile, Reservation
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .forms import SignUpForm, UserForm, ProfileForm, AdjustFundForm, ReservationForm
from .time import Calendar_week
from django.views.generic im... |
#! /usr/bin/python
from __future__ import division
import math
class Data:
''' Data class '''
def __init__(self,data):
self.data = data
def mode(self):
''' Returns mode as a float when data has only one mode
returns a list of modes when there are multiple modes '''
... |
#!/usr/bin/python3
"""
Generate procon graphs.
This script makes use of NetworkX to generate
procon graphs (nodes are paired up; one outputs
to another).
This tool creates adjacency list files (.adj)
whose filename represent the characteristics
of the graph created.
"""
from keyname import keyname as kn
import netwo... |
# -*- coding: utf-8 -*-
# @Author : 赵永健
# @Time : 2020/2/18 10:35
import unittest
from process.commonProc import commonProc
from process.initializationProc import initializationProc
from process.riskzoneProc import riskzoneProc
from public.openWeb import openWeb
'''
二、企业风险分区
1、评估单元划分
2、区域固有风险评估(校验值),L... |
# ==================================================================================================
# Copyright 2011 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
import numpy as np
from pylab import *
import sys
"""
SCRIPT NAME:
radxfer.py
AUTHOR:
Greg Blumberg
wblumberg@ou.edu
DESCRIPTION:
The primary argument for this code is the opd, which are the optical depths
set at the wave number grid (it's a 2D array of dimensions (layers, wnums)).
... |
#!/usr/bin/env python3
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
import urllib
import ev3dev.ev3 as ev3
import time
motorHand = ev3.Motor('outA')
motorLeft = ev3.LargeMotor('outB')
motorRight = ev3.LargeMotor('outC')
def rotateRight(duration):
motorLeft.run_forever(speed_sp=300)
motorR... |
# Definition for a binary tree node
# Path may start at leaf or internal node...
# Standard question involves computing longest path from root to leaves...
# Edge cases - empty tree, 1 node tree.
# At any given node -> compute longest path to a leaf on left and right.
# 1. maximum sum left path. -> 2
# 2. ma... |
#! /usr/bin/env python3
#! -*- coding: utf-8 -*-
import os, re
import fsutils
from pprint import pprint
import line_extractor, info_extractor
INPUT_FILEPATH = '../data/input/wiki/jawiktionary-latest-pages-articles.xml'
MIDDLE_RESULT = '../data/output/extrated_raw_lines.tsv'
RESULT_PATH = '../data/output/extrated.tsv... |
import os
import sys
from datetime import date
from functools import partial, reduce
import logging
import pandas as pd
from bcag.sql_utils import execute_sql_query
from sqlalchemy.engine.base import Engine
from . import fact_features as utils_ff
sys.path.append("..")
logger = logging.getLogger(__name__)
ch = loggi... |
#!/usr/bin/env python
#-*-coding: utf8-*-
'''
some numpy methods
@author: plm
@create: 2018-09-28 (星期五)
@modified: 2018-09-28 (星期五)
'''
import numpy as np
def test_argpartition():
'''partition sort. small, x, big'''
# 1. one index
a = np.array([9, 4, 3, 0, 5, 6, 1])
print (a)
# left--less than 4... |
"""
Copyright Matt DeMartino (Stravajiaxen)
Licensed under MIT License -- do whatever you want with this, just don't sue me!
This code attempts to solve Project Euler (projecteuler.net)
Problem #24 Lexicographic permutations
A permutation is an ordered arrangement of objects.
For example, 3124 is one possible permut... |
from django.contrib import admin
from core.models import Book, Journal
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ['name', 'price', 'description', 'created_at', 'num_pages', 'genre']
ordering = ['name']
search_fields = ['name', 'genre', ]
list_filter = ['created_at', 'num... |
from unittest import TestCase
from ques_4 import Total_compensation
class ProblemTest(TestCase):
def setUp(self) -> None:
self.employees = Total_compensation("cur")
def tearDown(self) -> None:
self.employees = None
def test_get_result(self):
self.assertEqual(self.employees.compen... |
from pydub import AudioSegment
import os, re
# mp3 = AudioSegment.from_mp3('./29593856.mp3') # 打开mp3文件
# mp3[14*1000-500:24*1000+500].export('./2.mp3', format="mp3") # 切割前17.5秒并覆盖保存
mp4_version = AudioSegment.from_file("/Users/user/language/sp/lr/2-01.mp4", "mp4")
mp4_version[:10000].export('/Users/user/language/sp/... |
import pandas as pd
import numpy as np
from flask import Flask, render_template, redirect
import sqlalchemy
from flask import jsonify
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
from flask_sqlalchemy import SQLAlchemy
import os
import sqlite3
... |
import requests
import json
# Global IDs
LOGIN_CLIENT_ID = '71a7beb8-f21a-47d9-a604-2e71bee24fe0'
CLIENT_ID = "b7cbf451-6bb6-4a5a-8913-71e61f462787"
DUID = "0000000d000400808F4B3AA3301B4945B2E3636E38C0DDFC"
CLIENT_SECRET = "zsISsjmCx85zgCJg"
class Auth:
oauth = None
last_error = None
n... |
#!/usr/bin/python3
def element_at(my_list, idx):
if my_list is not None and -1 < idx < len(my_list):
return my_list[idx]
return None
|
from myhdl import block, Signal, always_seq
from fifo import ConstFIFO
@block
def SChMemory(clock, reset, data_in, data_out, address, write, enable,
d, width, size, init_data=None):
high = Signal(1)
data = Signal(0)
addr = Signal(0)
w = Signal(0)
valid = Signal(0)
dfifo = ConstFIF... |
'''
You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have.
You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and S are letters. L... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import unittest
import requests
import json
class Jingle_login(unittest.TestCase): # 定义一个类
'''登录接口'''
def setUp(self): # 初始化
self.post_url = 'https://uccc.bckefu.com'
print("开始执行...")
def tearDown(self): # 与setUp()相对
print("执行完毕")
... |
class ZigzagIterator(object):
def __init__(self, v1, v2):
"""
Initialize your data structure here.
:type v1: List[int]
:type v2: List[int]
"""
self.list_pair = (v1, v2)
self.indexes = [0, 0]
self.select = 0
def next(self):
"""
... |
# import cv2
# import numpy as np
# from matplotlib import pyplot as plt
#
# img = cv2.imread('imagedata/train_0001.png')
# cv2.waitKey(0)
# plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
# plt.show()
# k = cv2.waitKey(0)
# if k == 27: # wait for ESC key to exit
# cv2.destroyAllWindows()
# elif... |
import pandas as pd
#투플을 시리즈로 변환(index 옵션에 인덱스 이름을 지정)
tup_data = ('영인','2010-05-01','여',True)
sr = pd.Series(tup_data,index=['이름','생년월일','성별','학생여부'])
print(sr)
print()
# 원소를 1개 선택
# sr의 1번째 원소를 선택(정수형 위치 인덱스를 활용)
print("sr[0] = {}".format(sr[0]))
print("sr['이름'] = {}".format(sr['이름']))
# 여러 개의 원소를 선택 (인덱스 리스트 활용)
... |
import typing
from cgshop2021_pyutils.solution.direction import Direction
class SolutionStep:
"""
A single step of a solution. __getitem__ and __setitem__ are defined
such that for any robot, the direction can be obtained and set.
Iteration over a solution step will iterate over all robots that actual... |
import sys
try:
from django.db import models
except Exception:
print('Exception: Django Not Found, please install it with "pip install django".')
sys.exit()
# Sample User model
class User(models.Model):
name = models.CharField(max_length=50, default="Dan")
def __str__(self):
return self.... |
from django.views.generic import TemplateView
from django.shortcuts import render
from CBF.utils import elements_text_search, search_elements_related_by_tags
from django.views.generic.edit import FormView
from sermons.models import Sermon
from thoughts.models import Thought
from events.models import Event
from subscri... |
# coding: utf-8
class Solution:
# @param {integer[]} nums
# @return {boolean}
def containsDuplicate(self, nums):
dul = {}
for num in nums:
if dul.get(num, None):
return True
else:
dul[num] = True
return False
print Solution().... |
from watchFaceParser.elements.timeElements.twoDigits import TwoDigits
from watchFaceParser.elements.timeElements.amPm import AmPm
from watchFaceParser.elements.basicElements.image import Image
class Time:
definitions = {
1: { 'Name': 'Hours', 'Type': TwoDigits},
2: { 'Name': 'Minutes', 'Type': TwoD... |
from matplotlib import pyplot as plt
import seaborn
from .ssm import *
from particles.core import SMC
def simulate_plot(model):
x, y = model.simulate(41)
y = np.asarray(y)[:, 0, :]
plt.plot(np.exp(x))
plt.plot(y)
def plot_theta(prior, model, burnin=False, m=None, linecolor='darkred'):
"""
Pl... |
"""
missing_coverage - Adds modules that are missing test coverage to the .coverage
file so that they can be included in any reports.
"""
try:
import ez_setup
ez_setup.use_setuptools()
except ImportError:
pass
from setuptools import setup
setup(
name='missing_coverage',
version='1.0',
)
|
from libardrone import * |
test1=[49,38,65,97,76,13,27,49,55,4]
test2=[]
test3=[49]
test4=list(range(10))[::-1]
def partition(l, begin, end):
pivot = begin
for i in range(begin+1, end+1):
if l[i] < l[begin]:
pivot +=1
l[i],l[pivot] = l[pivot],l[i]
l[begin],l[pivot] = l[pivot],l[begin]
return pivot... |
from front_machine.config.parser import get_config_from_json
import pandas as pd
import argparse
import time
import zmq
def result_collector(address, outputPath, numTerminate, is_test=False):
"""
takes controur values of an image and save them in a text file.
Args:
address : string of the ip add... |
from sqlite3 import *
def create_connection(path):
connection = None
try:
connection = connect(path, check_same_thread=False)
print("Connection is successful")
except Error as e:
print(e)
return connection
def fk_on():
connection = create_connection("kinopoisk.sql")
cu... |
#
# Mathematical
# Lab4.
# Theme: Approximation derivative.
#
def get_left_approximation_derivative(list_y, i, h, p):
return (-3 * list_y[i] + 4 * list_y[i + 1 * p] - list_y[i + 2 * p]) / (2 * p * h)
def get_right_approximation_derivative(list_y, i, h, p):
return (3 * list_y[i] - 4 * list_y[i - 1 * p] + list... |
"""
@author: common
@describe: 公共函数文件
@date: 2020/3/20
"""
import time
def datetime_to_unixtime(dtime):
"""
将datetime转换为unix时间戳
create by: yu bin
:param dtime: datetime
:return: Unix时间戳的str表示
"""
ans_time = time.mktime(dtime.timetuple())
return str(ans_time) |
def hut(n,x,y,z):
if n==1:
print(x,"-->",z)
else:
hut(n-1,x,z,y) #将n-1个盘子从x移动到y
print(x,"-->",z) #将最后一个盘子从x移动到z
hut(n-1,y,x,z) #将 y上的n-1个盘子移动到z
n=int(input("please input a number:"))
b=hut(n,"x","y","z")
|
#!/usr/bin/env python3
import os
class Command():
def __init__(self, args):
pass
class ListProcs(Command):
def __init__(self, args):
pass
def run(self):
proc = "/proc"
for d in os.listdir("/proc"):
if os.path.isdir(proc + "/" + d) and d.isdigit():
... |
# -*- coding: utf-8 -*-
number = 100
number2 = number + 10 # 加算(足し算)
number3 = number - 10 # 減算(引き算)
number4 = number * 10 # 乗算(掛け算)
number5 = number / 10 # 除算(割り算)
print(number2)
print(number3)
print(number4)
print(number5)
#型もチェックしてみます
print(type(number2))
print(type(number3))
print(type(number4))
print(type(num... |
def init_box(key):
#S盒
s_box = list(range(256))
# 初始化状态向量,256个字节,用来作为密钥流生成的种子1
j = 0
for i in range(256):
j = (j + s_box[i] + ord(key[i % len(key)])) % 256
s_box[i], s_box[j] = s_box[j], s_box[i]#置换
return s_box
# 由密钥T开始对状态向量S进行置换操作
def ex_encrypt(plain, box, mode):
... |
# -*- coding: utf-8 -*-
'''
This is a series of custom functions for the inferring of GRN from single cell RNA-seq data.
Codes were written by Kenji Kamimoto.
'''
###########################
### 0. Import libralies ###
###########################
# 0.1. libraries for fundamental data science and data processing
... |
"""
Icelandic earthquakes in Iceland for the past 48 hours into CartoDB.
This script will:
1. Scrape earthquakes from the Iceland Met Office (past 48 hrs.)
2. Parse the resaults into a csv table and save it
3. Create a Python list from csv file
4. Use CartoDB SQL API to:
a) Truncate a table in CartoDB
b) Insert new... |
from setuptools import setup
from tm import tm
setup(name="tm",
version=tm.__version__,
url="https://github.com/Ethanal/tm",
license="MIT",
packages=["tm"],
entry_points = {
"console_scripts": [
"tm = tm.tm:main",
],
},
long_description=tm.__d... |
import pandas as pd
from imblearn.over_sampling import RandomOverSampler
from imblearn.under_sampling import RandomUnderSampler
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
def importdata():
... |
from datetime import datetime
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
import pandas as pd
def convert_data():
path = '/data/breast-cancer-wisconsin.data'
columns = [
'id',
'clump_thicknes... |
class Solution(object):
def firstUniqChar(self, s):
dic = {}
for item in s:
dic[item] = dic.get(item, 0) + 1
for i, item in enumerate(s):
if dic[item] < 2: return i
return -1
class Solution(object):
def firstUniqChar(self, s):
for x in s:
... |
#!/usr/bin/env
############################################
# exercise_5.py
# Author: Paul Yang
# Date: June, 2016
# Brief: demo while and forloop for n * n time matrix, such as n=2 print 1x1, 1x2, 2x1, 2x2
############################################
n = input('輸入n for n x n matrix\n')
#forloop implementation
for... |
import sys
class Exp:
def __init__(self):
self.key = {}
self.value = {}
def _record_key_val_pair(self, dikt, k, v):
if not dikt.has_key(k):
dikt[k] = v
else:
raise Exception("Repeated key: This case should not be reached!")
def record_key(self, k, v... |
from django.apps import AppConfig
class GenConfig(AppConfig):
name = 'gen'
|
from django.contrib import admin
from books.models import Book, RequestBook, Author
class BookAdmin(admin.ModelAdmin):
list_display = (
'id',
'title',
'publish_year',
'review',
'condition',
'category',
'user',
'author',
)
readonly_fields = (
... |
"""
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Re... |
import sqlite3
import os
import datetime
from django import db
from django.core.management import BaseCommand
#BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#DATABASE = os.path.join(BASE_DIR, "data.sqlite3")
DATABASE = db.connections.databases['default']['NAME']
def recreate_database():
... |
import dgl.nn.tensorflow as dglnn
import tensorflow as tf
from questions.formula_visitor import FormulaVisitor
class GCN(tf.keras.layers.Layer):
def __init__(self, cfg, canonical_etypes, ntype_in_degrees, ntype_feat_sizes, output_ntypes=None, name='gcn',
**kwargs):
super().__init__(name=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.