text stringlengths 38 1.54M |
|---|
a, b, v = map(int, input().split())
answer = 0
def calculateDays(climb, slip, height):
FIRST_DAY = 1
step = - slip + climb # 하루에 최종적으로 올라간 높이
remainHeight = height - climb # 첫째날 올라간 후 남은 높이
if remainHeight % step == 0:
day = remainHeight // step + FIRST_DAY
else:
day = remainHe... |
def displayGrid(grid) :
"""
This function prints the grid out.
"""
for i in grid['value'] :
s = ""
for z in i :
s += z
print(s)
print()
def loadEmptyGrid(grid) :
"""
This function empties an existing grid or creates a new one.
"""
grid['value'] = ... |
from rest_framework import viewsets
from rest_framework.response import Response
from .models import Profile
from .serializers import ProfileSerializer
class ProfileViewSet(viewsets.GenericViewSet):
'''
API Endpoint to list current logged in user details
'''
def list(self,request, format=None):
... |
class DeviceStatus:
DISCONNECTED = "disconnected"
UNKNOWN = "unknown"
BUSY = "busy"
HARDWARE_UNAVAILABLE = "hardware-unavailable"
READY = "ready"
class RemoteStatus:
NO_SOCKET = "no-socket"
DISCONNECTED = "disconnected"
class Message:
CONNECT = "connect"
DISCONNECT = "disconnect"
RECONNECT = "reconnect"
HA... |
import face_recognition
import imutils
import pickle
import time
import cv2
import os
cascPathface = os.path.dirname(cv2.__file__) + "\data\haarcascade_frontalface_alt2.xml"
faceCascade = cv2.CascadeClassifier(cascPathface)
data = pickle.loads(open('Simple_Face_Recognition\\face_enc', "rb").read())
image = c... |
from simulation import SimState
class SimulationView:
def __init__(self):
self.simulation = SimState()
self.prey = []
self.predator = []
self.linear = []
self.K = 0
self.collect()
def supply(self, food_value, water_value):
self.simulation.resourceLev... |
import json as js
import csv as csv
import scipy as scipy
import numpy as np
import pdb
import string
# Set random state before keras imports
rs = 19683
from keras.models import Sequential, Graph
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.recurrent import LSTM
from keras.layers.embeddi... |
"""
Routines related to sending a list of tiddlers out
to the web, including sending those tiddlers and
validating cache headers for list of tiddlers.
These are important because this is what sends
a TiddlyWiki out.
"""
from sha import sha
from tiddlyweb.serializer import Serializer
from tiddlyweb.web.util import \
... |
import cv2
import face_recognition
import numpy as np
import threading
import time
def find_faces():
global frame
global last_filter
while True:
image = np.array(frame)
last_filter = face_recognition.face_locations(image)
# print(faces)
# last_filter = gen_filters(image, fa... |
kuakua = [
"为了表示我对资本市场的信心,我打算现在就去几站路外的银行取几百万投资股市,现在唯一的问题就只剩等公交车了。 ";
"学校教学楼厕所放镜子你以为让你整理仪容!?你错了,是为了让你知道,人丑就要多读书。 ";
"如果你每天干的活明显多于别人,但自己很高兴还感觉得到器重,那么与其说你很有才干,不如说你的领导很会管人。 ";
"“那些出身好能力强的人努力是为了成功,因为人家有可能会成功。我们努力是为了啥呢?” ";
"其实找谁做女朋友都差不多,都是在不停地争吵。只不过一些人是和比较漂亮的女孩子在争吵。 ";
"加油,你是最胖的。 ";
"你全力做到的最好,可能还不如别人的随便搞搞。 ";
"你的个性,... |
#!/usr/bin/python3
#ask for username & password
#create lists ulist & plist
#Username:
#Password:
#return <Logging in> or <Failed to login>
#if username = ulist, ask for password, else fail
#if password = plist, return "logging in"
#username list
ulist = ["Captain Planet"]
#password list (shouldn't this be encrypted... |
'''
Level: Medium Tag: [Matrix]
The island is partitioned into a grid of square cells.
You are given an m x n integer matrix heights where heights[r][c] represents the height
above sea level of the cell at coordinate (r, c).
The island receives a lot of rain,
and the rain water can flow to neighboring cells direct... |
#!/usr/bin/env python3
from __future__ import print_function
import psutil
import re
from pprint import pprint
import argparse
class Data(object):
def __init__(self, **kw):
self.__dict__.update(kw)
def __str__(self):
return '<Data({0})>'.format(', '.join('{key}={val}'.format(key=key, val=repr... |
#program to calculate fibonaci sequence using recursion
num= int(input("Enter a number"))
def fib(n):
return 1 if n<=1 else n*fib(n-1)
def fibonacci(num):
if(num<=1):
return num
else:
return fibonacci(num-1)+fibonacci(num-2)
print(fibonacci(num))
|
for i in range(1, 1 + input()):
ca = map(int, raw_input().split())
cz = ((ca[1] - 1)/ca[2]) + (ca[2]) + (ca[0] - 1) * (ca[1]/ca[2])
print "Case #{}: {}".format(i, cz) |
import os, django, time, random
from datetime import timedelta, date
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "beginning_django.settings")
django.setup()
from bookstore.models import Book, Author
from faker import Faker
import random
from time import sleep
cnt = 1
for i in range(1, 50001):
fake ... |
"""authors URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('home/', views.home, name='home')
Class-... |
# -*- coding: utf-8 -*-
from symbol_table import SymbolTable
TYPES = ['inteiro', 'flutuante']
OPERATIONS = ['=', '<>', '>', '<', '>=', '<=', '&&', '||']
success = True
class Analyzer():
def __init__(self):
self.symboltable = SymbolTable()
success = True
def scan_tree(self, node):
currentStatus = sel... |
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
# >> SNS
NOT_SNS_REQUEST = {
'code': 'ops.NotSNSRequests',
'detail': _('This resource is forbidden for not SNS requests.'),
}
METHOD_NOT_ALLOWED = {
'code': 'sns.MethodNotAllowed',
'detail': _('This method is not allowed... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2019-07-03 08:03
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('userinfo', '0002_bankcard'),
]
operations = [
migrations.AlterModelOptions(
... |
class BD_roman:
def __init__(self):
self.names = list()
self.encoded = list()
def add(self, name, vector):
self.names.append(name)
self.encoded.append(vector)
def get_names(self):
return self.names
def get_vectors(self):
return self.enco... |
from application import app, db, login_required
from application.auth.models import User
from application.animals.models import Animal
from application.auth.forms import LoginForm, CreateUserForm, ChangePasswordForm, ChangeUsernameForm, EditUserInfoForm
from flask_login import login_user, logout_user, current_user
from... |
#!/usr/bin/env python3
# looking for number of events within 1 second, 5 seconds, 10 seconds
import csv
import math
import pprint
import sys
import time
import itertools
import matplotlib.pyplot as plt
import numpy as np
try:
dw_file = sys.argv[1]
pw_file = sys.argv[2]
except:
print()
print('Usage: ... |
# -*- coding:utf-8 -*-
'''
Created on 2016年7月14日
@author: zhaojiangang
'''
import random
import freetime.util.log as ftlog
from freetime.core import reactor
from poker.entity.game.rooms import roominfo
from poker.entity.game.rooms.erdayi_match_ctrl.config import MatchConfig
from poker.entity.game.rooms.erdayi_match_c... |
from o3seespy.base_model import OpenSeesObject
class Node(OpenSeesObject):
op_base_type = "node"
op_type = "node"
def __init__(self, osi, x: float, y=None, z=None, vel=None, acc=None, mass: list=None,
x_mass=None, y_mass=None, z_mass=None, x_rot_mass=None, y_rot_mass=None, z_rot_mass=Non... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 16 21:13:51 2020
@author: Sony
"""
import time
import numpy as np
import pandas as pd
from sklearn.model_selection import cross_val_score, cross_val_predict, KFold
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-05 13:45
from __future__ import unicode_literals
from django.db import migrations
def create_badges(apps, schema):
category_model = apps.get_model('core.Badge')
category_model.objects.create(name="First Mystery completed", description="Complete 1... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'', include('travelpad.urls')),
url(r'', include('travelpad.urls_profile')),
url(r'', include('travelpad.urls_itineraries')),
url(r'', include('travelpad.urls_invitation')),
url(r'', include('travelpad.urls_itinerary... |
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
length = len(nums)
if length>1:
pre = nums[0]
i = 1
while i<length:
if nums[i]==pre:
nums.pop(i)
length -= 1
else:
... |
import common
import prolog
import config as cfg
from os.path import isfile
class Aleph:
name='aleph'
aleph_path='aleph/aleph'
aleph_runner='aleph/runner'
def __init__(self):
pass
def parse_train(self,datafile,outpath,game,target):
for (subtarget,bk,pos,neg) in common.parse_target... |
from compmusic import dunya
dunya.set_token('ad57ef18f8c3a2f4962b7883ac6ed38b3578ba38')
a = dunya.carnatic.get_recordings(recording_detail=True)
import json
with open('carnatic.json', 'w') as fp:
json.dump(a, fp)
|
msgs.df < - c() # 빈 데이터프레임 생성
trending_stock < - c("SSNLF", "GILD") # 주식종목 선택
stock_twits < - function(msgs.df, stock)
{
# Get raw data
url < - paste("https://api.stocktwits.com/api/2/streams/symbol/", stock, ".json", sep="") # api로 부터 데이터 추출
msgs < - c()
for (i in c(1:length(url))) # 전체 내용 행만큼 ... |
import os
from pathlib import Path
import unittest
import crowsetta
import pandas as pd
import vak.io.spect
import vak.files.spect
from vak.config.validators import VALID_AUDIO_FORMATS
HERE = Path(__file__).parent
TEST_DATA_DIR = HERE.joinpath('..', '..', 'test_data')
SETUP_SCRIPTS_DIR = HERE.joinpath('..', '..', 's... |
import csv
import tensorflow as tf
tf.enable_eager_execution()
'''
This program takes in a csv file of EEG data output from chronoSync.py and creates a Tensorflow dataframe object from it
'''
#FThis function formats each line of CSV into features (8 tensors with numSamples number of EEG readings) and a class lab... |
#!/usr/bin/env python
import os
import sys
import time
from boto.ec2.connection import EC2Connection
# change these as desired
#
# EC2 keypair to attach to instance on boot
KEY = 'james-mac'
if os.environ.has_key('EC2_SSH_KEY'):
KEY = os.environ['EC2_SSH_KEY']
# probably don't want to change these:
ROLE ... |
import serial
import subprocess
import os
enteroApagar = int("0xFE7887",16)
ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
lectura = int(ser.readline(),16)
if lectura == enteroApagar:
operative = os.name
if(os.name == 'posix'):
subprocess.call(["sudo", "shutdown", "-h", "now"])#ubuntu
else:#in case yo... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-01 20:01
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('member', '0002_auto_20170901_1946'),
]
operations ... |
import math
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from .agc_layer import AGCLayer as InputEncoding
from .selectscale_hc import SelectscaleHyperConv
from .selectframe_tc import SelectframeTemConv
from .utils import *
from graph.nturgbd import *
from graph.kinetics imp... |
import subprocess
""" suppresssing errors by passing them to DEVNULL
"""
try:
completed = subprocess.run(
'echo to stdout; echo to stderr 1>&2; exit 1',
shell=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except subprocess.CalledProcessError as err:
... |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from youtube_podcast_api.config import get_settings
# Parse .env file for settings
# settings = get_settings()
SQLALCHEMY_DATABASE_URL = f"sqlite:///{get_settings().db_path}"
engine =... |
def _jupyter_server_extension_paths():
return [{
"module": "nbextension_toc"
}]
# Jupyter Extension points
def _jupyter_nbextension_paths():
return [dict(
section="notebook",
src="static",
dest="nbextension_toc",
require="nbextension_toc/toc")]
def load_jupyter_serv... |
import json
import os
import requests
import ssl
import sys
import urlparse
import webbrowser
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from multiprocessing import Process
from os.path import isdir, isfile
CERT_FILE_PATH = './server.pem'
BASE_FB_GRAPH_URL = "https://graph.facebook.com/v2.11"
if n... |
# -*- coding: utf-8 -*-
import unittest
from chakert import Typograph
def highlight(txt):
return txt.replace(u'\u00a0', u'␣')\
.replace(u'\N{NON-BREAKING HYPHEN}', u'=')
class BaseTests(unittest.TestCase):
def assertText(self, text, *args, **kwargs):
check_html = kwargs.pop('check_ht... |
import pandas
from shapely.geometry import Polygon
import shapefile
nex_shapename = '..\\shapes\\NEXRAD_pixels_tsala'
grid_shapename = '..\\shapes\\join_all2'
df = pandas.read_csv('NEXRAD.csv',nrows=1)
df_keys = list(df.keys())
#--build nexrad polygons - just duplicate multipart polys
print 'loading grid shapefile'
... |
# Local tests took 1 hour to insert 5 million lines. Estimated 9 hours to insert all data as of 05/2017.
# Suggested to run on a weekend during off hours
import os
import re
import logging
import boto
import urllib.request
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.exc import IntegrityError
fr... |
"""
Tests for views:
- home-page (project-collection)
- project-page
- result-page
"""
import os
from pathlib import Path
from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
def get_relative_results_files... |
from django.test import SimpleTestCase
from django.test import TestCase
from django.urls import reverse ,resolve
from account.views import *
class TestUrls(SimpleTestCase):
def test_register_urls_is_resolve(self):
url= reverse ('register')
# print(resolve(url))
self.assertEquals(resolve(url).func,registerPag... |
t = int(input())
for i in range(t):
x, y, n = map(int, input().split())
print(pow(x, y, n))
|
"""Module that contains TextFormatter class"""
import re
import numpy as np
from bs4 import BeautifulSoup
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.stem.porter import PorterStemmer
from nltk.stem.lancaster import LancasterStemmer
from nltk.stem import SnowballStemmer
class Tex... |
from databases.sql_db import db
class Vacancy(db.Model):
__tablename__ = "vacancies"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255), nullable=False)
firm = db.Column(db.String(128), nullable=False)
description = db.Column(db.Text(), nullable=False)
location_post... |
'''
==========================================================================
XbarRTL_test.py
==========================================================================
Unit tests for XbarRTL.
Author : Yanghui Ou
Date : Apr 16, 2020
'''
import pytest
from pymtl3 import *
from pymtl3.stdlib.test_utils import mk_test... |
# utf-8
#palindromo
se = []
f = str(input('Digite a frase: ').lower())
se = f.replace(' ', '').replace('.', '')
if se == se[::-1]:
print('É um palíndromo')
else:
print('Não é um palíndromo.') |
import os
import numpy as np
from collections import Counter
from sklearn import svm
from sklearn.metrics import accuracy_score
import nltk
import pickle
import gzip
from sklearn.feature_extraction import DictVectorizer
# to load the file that we saved that contains an object (eg.. array or a list or a dic and just loa... |
from django.urls import path
from .views import *
from django.contrib.auth.views import PasswordResetView,PasswordResetDoneView,PasswordResetConfirmView,PasswordResetCompleteView
urlpatterns=[
path('home/',Homeview,name='home'),
path('register/',Registerview,name='register'),
path('login/',Loginview,name... |
#/usr/bin/env python3.4
import sys
def cut_blank_lines(script_path):
lines = []
with open(script_path, 'r') as python_file:
for line in python_file.readlines():
if line.strip() == '':
continue
lines.append(line)
return ''.join(lines)
if __name__ == '__main... |
# GQC environment setting
# Flask-NegLog Settings
LOG_LEVEL = 'debug'
LOG_FILENAME = "/var/camel/error.log"
LOG_ENABLE_CONSOLE = False
|
#!/usr/bin/env python2.7
# -*- coding:utf-8 -*-
#
# Author :
# E-mail :
# Date : 2014/02/25
# Desc :
#
import tornado.web
import json,logging,types,time,urllib2
from tor_manager.util.config import Config
from tor_manager.util.httpclient import HttpClient
from tor_manager.util.httpresponse impo... |
import numpy as np
x = 0.25
y = 0.25
gamma = .9
#Store Transition matrices
actions = 3
states = 4
#Action, Current state, Next state
T = np.zeros((actions, states, states))
T[0, 1, 1] = 1-x
T[0, 1, 3] = x
T[0, 2, 0] = 1-y
T[0, 2, 3] = y
T[0, 3, 0] = 1
T[1, 0, 1] = 1
T[2, 0, 2] = 1
#Rewards
R = np.array([0,0,1,10])
... |
hadoop fs -get result
echo 'id,hotel_cluster' > result/head
cat result/head result/part-* > result.csv
|
from ..decorators import stere_performer, use_after, use_before
from ..field import Field
@stere_performer('click', consumes_arg=False)
class Link(Field):
"""Convenience Class on top of Field.
Uses Splinter's click method.
"""
@use_after
@use_before
def click(self):
"""Use Splinter's... |
from server.server_app import app
from flask_cors import CORS
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--host', default='0.0.0.0', help='Host name')
parser.add_argument('-p', '--port', default=8888, help='Port number')
args = parser.parse_args(... |
f = open('test.txt','r')
a = open('ans.txt','w')
for i in range(1,int(f.readline())+1):
c = 1
digit = set()
num = int(f.readline())
while(num!=0):
digit = digit | set(list(str(num*c)))
if len(digit)==10:
break
c+=1
if num==0:
a.write('Case #%d: INSOMNIA\n'%(i))
else:
a.write('Case #%d: %d\n'%(i,num*c... |
import abc
class ServiceHashringException(Exception):
pass
class ServiceHashringNode(object):
"""Service hashring node class."""
def __init__(self, token, service_info, data=None):
"""ServiceHashringNode constructor.
Args:
token: 128-bit integer token identifying the node's
... |
#!/usr/bin/env python
import rospy
import time
import numpy as np
from std_msgs.msg import Float64MultiArray
from std_msgs.msg import Float64
from sensor_msgs.msg import Image
from sensor_msgs.msg import JointState
from geometry_msgs.msg import Transform, TransformStamped
from PIL import Image as pil_img
from cv_bridg... |
# -*- coding: utf-8 -*-
from openerp import api, fields, models
class StockMove(models.Model):
_inherit = 'stock.move'
brand_id = fields.Many2many('product.brand', string="Brand")
StockMove() |
# ------------------------------------------------------------------------
# coding=utf-8
# ------------------------------------------------------------------------
#
# Created by Jason Wu on 2015-08-29
#
# ------------------------------------------------------------------------
import random
class Particle(object):... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 18 13:46:37 2016
@author: Autex
"""
import processinglib
src = face(gray=True)
k = 3
psf = np.ones((k, k)) / k**2
direct_conv = conv2(src, psf)
direct_rest = deconv2(direct_conv, psf)
show_pics([src, direct_rest], ["Source", "Directly restored"]) |
import os
import sys
import struct
import platform
import fileinput
import subprocess
from setuptools import setup
from ext_targets import build_ext, StaticLibrary, Executable
COMPILE_FLAGS = ['-flto', '-std=gnu++11', '-g', '-Wall',
'-Werror', '-DRENDERER_PROCESS', '-static']
LINK_FLAGS = [... |
from PIL import Image, ImageDraw, ImageFont
from datetime import date
import pandas as pd
import numpy as np
import yagmail
import os
#Function to verify if the certificate exists in the search_path
def find_files(filename, search_path):
result = []
for root, dir, files in os.walk(search_path):
if fil... |
# connected-component analysis: binary or thresholded image
# The first pass
# step 1: check if we care about the central pixel p or not
# if p == 0:
# ignore
# else:
# proceed to step 2 and step 3
# step 2 and step 3
# north and west pixels, denoted as N and W
# if N and W are background pixels:
# create a ne... |
card_list = []
# 显示功能菜单
def menu():
print('欢迎进入名片系统 V1.0')
print('1. 新建名片')
print('2. 显示所有名片')
print('3. 查找名片')
print('')
print('0. 退出系统')
# 新建名片
def new_card():
# 用户输入信息
print('【添加新名片】')
print('请根据提示输入信息')
name = input('请输入姓名:')
phone = input('请输入电话:')
email = input(... |
# -*- coding: UTF-8 -*-
import requests
import traceback
class KfReq:
def __init__(self):
self.headers = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}
self.cookies = dict()
def get(self, url, **kwargs):
kwargs... |
'search for an item in a sorted matrix'
import bisect
NOT_FOUND = (False, (None, None))
def transpose(mat, r, s):
'returns the transpose of a matrix'
nmat = []
for y in range(s):
row = []
nmat.append(row)
for x in range(r):
row.append(mat[x][y])
return nmat
def ge... |
class base1c():
def x(s, d):
print("base1->")
print("<-base1")
class base2n():
def x(s, c1, c2, c3, c4):
print("base2->")
#super().x()
print("<-base2")
class main (base2n, base1c):
def x(s):
print("main->")
base2n.x(s,1,2,3,4)
base1c.x(s,55)
print("<-main")
main().x() |
import data
import xlrd
from entities.Day import Day
from entities.Group import Group
from database.Database import Database
from entities.Lesson import Lesson
import requests
def pair_merged(sheet):
for merged in sheet.merged_cells:
rbeg, rend, cbeg, cend = merged
cell = sheet.cell(rbeg, cbeg)
... |
from .node import Node
class Stack:
""" created class. Init class"""
def __init__(self, iterable=[]):
self.top = None
self.len = 0
"""define magics """
def __len__(self):
return self.len
def __str__(self):
pass
def push(self, val):
""" push adds one i... |
import random
def roll(number_of_throws):
"""geeft een random getal tussen 1 en 6 voor het gegeven aantal keer.
input:
number_of_throws - int
output:
return getallenlijst - list
"""
getallenlijst = []
if number_of_throws > 0:
for i in range(number_of_throws):
... |
# -*- coding: utf-8 -*-
import scrapy
class SinopecsalesItem(scrapy.Item):
#{"amount":"20000","balance":"262773","litre":"3160","oilName":"95号车用汽油(V)",
# "price":"633","opeTime":"2016-07-27 09:10:37",
# "reward":"200","nodeTag":"滨州石油第5加油站","traName":"加油"}
# holders = scrapy.Field()
cardNo = scrapy... |
import numpy as np
def strassen(A, B):
if type(A) == np.ndarray and type(B) == np.ndarray:
raise Exception('Inputs are not numpy ndarrays')
if True:
raise Exception('Inputs are not bidimensional')
if True:
raise Exception('Matrices are not squared')
if A:
raise Exception('Matrices are not of n p... |
#coding=utf-8
list1=[]
list2=[]
list3=[]
n=input('输入n的值:')
for i in range(1,n+1,1):
x=input('输入一个数:')
if x>0:
list1=list1+[x]
elif x<0:
list2=list2+[x]
else:
list3=list3+[x]
print '这些数中正数的个数:',len(list1)
print '这些数中负数的个数:',len(list2)
print '这些数中零的个数:',len(list3)
|
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD
from keras.callbacks import TensorBoard
# 生成虚拟数据
import numpy as np
x_train = np.random.random((1000, 20))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(1000, 1)), nu... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-22 11:46
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ac_site', '0014_auto_20170922_2028'),
]
operations = [
migr... |
import base58
import os
from common.serializers.serialization import state_roots_serializer
from plenum.common.constants import DOMAIN_LEDGER_ID, ALIAS, BLS_KEY
from plenum.common.keygen_utils import init_bls_keys
from plenum.common.messages.node_messages import Commit, Prepare, PrePrepare
from plenum.common.util impo... |
#!/usr/bin/env python
import sys
from http.server import HTTPServer, SimpleHTTPRequestHandler, test
class CORSRequestHandler(SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
if __name__ == '__main__... |
from pymongo import MongoClient
from flask import Flask, render_template
############
from os import environ as env
from os import path as path
from flask import Flask, jsonify, request, session, redirect, render_template, url_for, send_from_directory
from werkzeug.exceptions import HTTPException
from functools impor... |
from django.db import models
from rompas.models import Product, Subscription, Tokens
from django.core.validators import RegexValidator
from django.contrib.auth.models import User
from django.utils.translation import gettext as _
class Order(models.Model):
name = models.ForeignKey(User,
... |
import numpy as np
#
def password(m):
N = 1000
check = 0
n = np.power(26,4)
for i in range (0,N):
p = np.random.randint(0,n)
H = np.random.randint(0,n,m)
if p in H:
check += 1
print(check/N)
#
m = 80000
k = 7
password(m*k)
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Alpha Labs
if __name__ == '__main__':
import pandas as pd
import numpy as ny
import matplotlib.pyplot as plt
from Data_preprocessing_function import *
#读取文件
filename = "./test.csv"
df_1 = pd.read_csv(filename)
#read(df_1)
#删除... |
from setuptools import setup, find_packages
import versioneer
setup(
name='tsdataformat',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
author='Chris T. Berthiaume',
author_email='chrisbee@uw.edu',
license='MIT',
description='A Python project to manage time series da... |
class Scrap:
def __init__(self):
pass
def get_titles(self, p):
return p.find_element_by_class_name('post-title').text
def get_dates(self, p):
return p.find_element_by_class_name('post-date').text
def get_excerpts(self, p):
return p.find_element_by_class_name('post-... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from... |
#-*- coding:utf-8 -*-
import picamera
CAMERA_WIDTH = 640
CAMERA_HEIGHT = 480
camera = picamera.PiCamera()
camera.resolution = (CAMERA_WIDTH,CAMERA_HEIGHT)
def Capture():
camera.capture('image_.jpg')
return 'hello'
Capture() |
__author__ = '''Kent (Jin-Chun Chiu)'''
import numpy as np
from scipy.spatial.distance import euclidean
from fastdtw import fastdtw
##################################
# [*] Path Interpretation #
##################################
# up-left up up-right #
# 7:14 8 9:15 #
# left... |
import boto3
ec2_client=boto3.client('ec2')
x = ec2_client.describe_instance()
data = x['Reservation']
li=[]
for instances in data:
instance = instances["Instances"]
for ids in instance:
instance_id = ids["InstanceId"]
li.append(instance_id)
ec2_client.terminate_instances(Instanc... |
#!/usr/bin/python
import MySQLdb as mdb
import sys
print "Content-type: text\html\n"
print "{\"characters\":["
try:
con = mdb.connect('localhost', 'dlin', 'dlin2dlin', 'dlin');
with con:
cur=con.cursor(mdb.cursors.DictCursor)
cur.execute("select id, name, baseClass, altClass1, altClass2, altClass3 fro... |
import cv2
import node_settings
def test_draw_pint():
#path = r'world_rs_walker.png'
path = r'world_rs_walker_AUG_2021.png'
image = cv2.imread(path)
coord = (90, 120)
radius = 2
color = (0, 0, 255)
thickness = 0
window_name = 'Image'
# Using cv2.circle() method
# Draw... |
#!/usr/bin/python
import time
def login(shana, event):
shana.write(("USER", shana.conf['user'], '+iw', shana.conf['nick']), shana.conf['name'])
shana.write(["NICK"], shana.conf['nick'])
login.name = 'login'
login.wake_on_letter = True
def pong(shana, event):
shana.write(['PONG'], event.group(0))
pong.name = 'pon... |
import os.path as _path;
import common_def as _common;
import functools as _func;
import data_ops as _data;
import os;
class CommitCheckReport(object):
def __init__(self, cache_path, err_level=_common.LOGLEVEL_INFO, err_desc=None, origin_status=None, actions=None):
self.cache_path = cache_path;
self.err_level = e... |
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
def helper(S):
stack1 = []
for s in S:
if s == '#':
if stack1:
stack1.pop()
else:
stack1.append(s)
return s... |
import pandas as pd
import os
import sys
class CM:
"""
Confusion matrix class for binary problems.
"""
def __init__(self, table: dict):
"""
The class constructor.
:param table: a dictionary with 4 keys (tp, fn, tn, fp) and their corresponding
values representing a con... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.