text stringlengths 8 6.05M |
|---|
import os
def FilePathCheck(F):
if os.path.isfile(F):
return F
path = os.getcwd()
curdirF = os.path.join(path, F)
if os.path.isfile(curdirF):
return curdirF
return
if __name__ == '__main__':
F = input('Please input the file name:')
file_path = FilePathCheck(F)
if file_p... |
import sys, os
sys.path.append('{}/../'.format(os.path.dirname(os.path.abspath(__file__))))
from main import VirtAssistant
virt = VirtAssistant(test=True)
def test_idiot_insult():
idiot = ["Sorry, I can't hear you right now","Talking to yourself is unhealthy, NN","Okay, if you insist",
"That didn'... |
import os
import logging
import mimetypes
from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from django.views.decorators.csrf import csrf_exempt
from django.http import StreamingHttpResponse,FileResponse
from rest_framework.response import Response
from django.utils.http import u... |
import instaloader
ob = instaloader.Instaloader()
user = input("Enter username")
ob.download_profile(user,profile_pic=True) |
import requests
x = requests.get("www.google.com")
print(x) |
import sqlite3 #导入模块
conn = sqlite3.connect('example.db') #连接数据库
c = conn.cursor()
# 创建表
#c.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''')
c.execute("CREATE TABLE stocks2 (date text, trans text, symbol text, qty real, price real) ")
# 插入一条记录... |
#-- GAUDI jobOptions generated on Mon Jul 6 15:28:35 2015
#-- Contains event types :
#-- 13104231 - 32 files - 522500 events - 105.29 GBytes
#-- Extra information about the data processing phases:
#-- Processing Pass Step-124834
#-- StepId : 124834
#-- StepName : Reco14a for MC
#-- Applicat... |
from glmnet import LogitNet
import matplotlib as mpl
import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn.preprocessing import StandardScaler
from tqdm import tqdm
from sample import sample_equal_proportion
# Set matplotlib settings
mpl.get_backend()
mpl.use('TkAgg')
import matplotlib.pypl... |
import sys
from math import factorial
if __name__ == "__main__":
'''
Given: Positive integers n and m with 0≤m≤n≤2000.
Return: The sum of combinations C(n,k) for all k satisfying m≤k≤n, modulo 1,000,000. In shorthand, ∑nk=m(nk).
'''
n, m = map(int, sys.stdin.read().splitlines()[0].split())
to... |
from . import question_logit
from . import symbol_cost
from . import symbol_features
|
class Alliance(object):
def __init__(self, score=None, teams=[]):
self.teams = teams
self.score = score
class Alliance2017(Alliance):
def __init__(
self,
score=None,
teams=[],
fuel_score=None,
fuel_count=None,
rotor_count=... |
import helpers
import os
import sys
import time
kex_algs_master_111 = ['oqs_kem_default', 'bike1l1', 'bike1l3', 'bike1l5', 'bike2l1', 'bike2l3', 'bike2l5', 'bike3l1', 'bike3l3', 'bike3l5', 'frodo640aes', 'frodo640cshake', 'frodo976aes', 'frodo976cshake', 'newhope512cca', 'newhope1024cca', 'sidh503', 'sidh751', 'sike50... |
from bs4 import BeautifulSoup
from tqdm import tqdm
from pathlib import Path
import urllib.request
import requests
import math
import os
def main():
with open("t2k.html") as fp:
soup = BeautifulSoup(fp, "html.parser")
s2 = soup.select("div.yeeditor a")
k = []
for t in s2:
... |
from django.contrib import admin
from .models import Team, Member, Project
admin.site.register(Team)
admin.site.register(Member)
admin.site.register(Project) |
# -*- coding: utf-8 -*-
"""
This package contains code for the "CRF-RNN" semantic image segmentation method, published in the
ICCV 2015 paper Conditional Random Fields as Recurrent Neural Networks. Our software is built on
top of the Caffe deep learning library.
Contact:
Shuai Zheng (szheng@robots.ox.ac.uk), Sadeep J... |
../../cma_es/cma.py |
#!/usr/bin/env python3
import sys
import threading
import socket
import time
import math
from log import log
class PRM(object):
def __init__(self, nodeId, prmIp, prmIp_2, prmIp_3, prmPort):
self.nodeId = str(nodeId)
self.prmIp = str(prmIp)
self.prmIp_2 = str(p... |
import random
noWin = 1
guessCounter = 0
number = random.randrange(0,100,1)
def start():
global number
if (noWin == 0):
number = random.randrange(0,100,1)
else:
pass
guess = input("Guess the integer I'm thinking of between 0 and 100. ")
if int(guess) > 100 and int(guess) < 0:
print("That number's not in o... |
import sys
if __name__ == '__main__':
tel_num = sys.argv
if tel_num[1].isdigit() and len(tel_num[1]) == 10:
print('This telephone number is legit!')
elif tel_num[1].isdigit() and len(tel_num[1]) != 10:
print('This telephone number contains more or less than 10 digits')
else:
pr... |
import syntensor
import numpy as np
import json
import os
import sys
np.set_printoptions(linewidth = np.nan)
np.set_printoptions(threshold=np.inf)
image_nums = 156
current_path = 'temp'
'''
fname = 'new_data_10.json'
sys.stdin = open(fname,'r')
data = input()
data = json.loads(data)
Plist = np.array(data['P'],np.ndarra... |
#import sys
#input = sys.stdin.readline
def main():
N = int( input())
S = [ input() for _ in range(N)]
# lenS = [len(s) for s in S]
# LS = [ s.lstrip("0") for _ in range(N)]
# lenLS = [len(s) for s in S
P = []
for i, s in enumerate(S):
p = len(s)
ls = s.lstrip("0")
P.... |
import scrapy
from scrapy_splash import SplashRequest
import time
class QuoteSpider(scrapy.Spider):
name = 'quote'
script = '''
function main(splash, args)
splash.private_mode_enabled = false
url = args.url
assert(splash:go(url))
assert(splash:wait(1))
splash:se... |
class OAIError:
def __init__(self, code, description):
self.code = code
self.description = description
class BadVerb(OAIError):
def __init__(self, verbs=None):
if not verbs:
message = 'Missing OAI verb'
elif len(verbs) > 1:
message = 'Multiple OAI verbs... |
n, k = map (int, input ().split ())
P = list (map (int, input ().split ()))
K = [0] * (n - k + 1)
K [0] = sum (P [:k])
for i in range (1, len (K)):
K [i] = K [i - 1] - P [i - 1] + P [k + i - 1]
K = [0] + K + [0]
ml = [K [0]]
mr = [K [-1]]
for i in range (1, len (K)):
ml += [max (ml [-1], K [i])]
mr = [max (... |
tries = 1
answer="delhi"
while tries<=3:
print("what is the capital of india")
response=raw_input()
tries=tries+1
if (response=="delhi"):
print("Correct")
break
else:
if ((tries-1) <> 3):
print("Sorry.Try Again ..." + str(tries -1) + " over :( ")
... |
from telegram import MessageEntity, ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters, CallbackQueryHandler
sponsors = ['@dil_zil']
users = []
usersId = []
links = {}
buttons = ReplyKeyboardMarkup([['Продвигат... |
""" Google doc filler/spammer by Jake CEO of annoyance#1904"""
from pyautogui import *
from tkinter import *
from urllib.request import urlopen
import io
import base64
import webbrowser
PATH = "whattosay.txt" # str(input("Please enter the name of your file"))
FILE = open(PATH, mode="r+", encoding="UTF-8")
... |
import numpy as np
from scipy.spatial.distance import cdist
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import *
import matpl... |
import cv2
import sys
import numpy
import time
num_frames = 120
face_cascade = cv2.CascadeClassifier('haarcascades/cascadG.xml')
# hand_cascade = cv2.CascadeClassifier('Hand.Cascade.1.xml')
cap = cv2.VideoCapture(0)
start = time.time()
count=0
num_frames =100
while(1):
ret, img = cap.read()
gray = cv2.cv... |
print("Pick a number")
print("Este programa genera un numero random y pregunta al usuario adivinarlo")
import random
rndm=random.randint(0,100)
print("El numero es: ",rndm)
tries=1
num=int(input("Escoje un numero del 1 al 100: "))
while(num!=rndm):
if(num>rndm):
print("Tu numero es muy grande")
elif(nu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This exploit template was generated via:
# $ pwn template
from pwn import *
# Set up pwntools for the correct architecture
context.update(arch='i386')
exe = './path/to/binary'
ip = "54.161.125.246"
port = 1000
# Many built-in settings can be controlled on the command-li... |
import random
import pymunk #1
#define the ball
def add_ball(space):
mass = 1
radius = 14
moment = pymunk.moment_for_circle(mass, 0, radius) # 1
body = pymunk.Body(mass, moment) # 2
x = random.randint(120, 380)
body.position = x, 550 # 3
shape = pymunk.Circle(body, radius) # 4
space.add... |
from tkinter import *
from tkinter.scrolledtext import ScrolledText
from tkinter.messagebox import *
import re
import os
class StatusBar(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self._lblState = Label(self, text='', bd=2, relief=SUNKEN, width=15, anchor = W)
self._lb... |
"""
write a function, calculate the number of a e i o u in the letter
"""
def count_vowel(s):
if not isinstance(s, str):
raise ValueError("ValueError: input must be a string")
if len(s) == 0:
return 0
counter = 0
vowel_list = ['a', 'e', 'i', 'o', 'u']
for letter in s:
... |
##############Creates se files:
##This script writes the data of cycle cycle_all from file run_H5 into
##the sefile outputfile for a number of cycles given by cycles variable
import nugridse as mp
import sewrite as sw
import numpy as np
###############Read se file to get header information
run_H5='e2D14.0077501.s... |
# ------------------------------------------------------------------------------
# Metropolitan Form Analysis Toolbox-Coverage
# Credit: Reza Amindarbari, Andres Sevtsuk
# City Form Lab
# for more infomation see:
# Amindarbari, R., Sevtsuk, A., 2013, "Measuring Growth and Change in Metropolitan Form"
# presented at the... |
from flask import Flask, Blueprint
def create_app():
app = Flask(__name__)
# Register your Blueprints
from app.echo import echo
from app.root import root
app.register_blueprint(echo)
app.register_blueprint(root)
return app
|
class Carro:
quantidadeRodas = 4
cor = "azul"
def __init__(self, quantidadeRodas, cor):
self.quantidadeRodas = quantidadeRodas
self.cor = cor
def setQuantidadeRodas(self, quantidadeRodas):
self.quantidadeRodas = quantidadeRodas
meuCarro1 = Carro(10, "azul")
meuCarro1.quantid... |
#!/usr/bin/python3
from panflute import *
def demote_header(elem, doc):
"""Demotes headers to prevent first-level headers.
First-level headers are reserved for daily headers"""
if isinstance(elem, Header):
elem.level += 1
def simple_id(filename):
return ''.join((c for c in filename if c.isdig... |
import numpy as np
# LOAD TXT AND SAVE AS NPY
data = np.loadtxt("labels.txt", delimiter=",")
bigNpy = []
for i in range(0, 1200):
thisLabel1 = str(data[i][0])
thisLabel2 = str(data[i][1])
thisLabel3 = str(data[i][2])
bigNpy.append(thisLabel)
a =4
np.save("labelsNpy.npy", bigNpy)
# # LOAD NP... |
import tensorflow as tf
import commons.mnist.inf.model_def as model_def
class InferenceNetwork(object):
def __init__(self):
self.sess = tf.Session()
self.x_ph = tf.placeholder(tf.float32, shape=[None, 28, 28, 1], name='x_ph')
self.logits, self.y_hat, self.keep_prob = model_def.infer(self.x... |
#!/usr/bin/python
#Print a dictionary with a nice format
def PrintDict(d,indent=0):
for k,v in d.items():
if type(v)==dict:
print ' '*indent,'[',k,']=...'
PrintDict(v,indent+1)
else:
print ' '*indent,'[',k,']=',v
#Container class that can hold any variables
#ref. http://blog.beanz-net.jp... |
#modules (libraries)
import os
import csv
# Set the path to access the file
csvpath = os.path.join("Resources", "budget_data.csv")
# Define total months
total_months = 0
# Defint net total
net_total = 0
# Define list of change values
empty_list = []
month_list = []
profit_list = []
monthly_profit_change = []
net_ch... |
# Copyright (C) 2016 Nokia Corporation and/or its subsidiary(-ies).
import unittest
import tempfile
import os
import shutil
import datetime
import json
from deployment import samodels as m, execution, executils, database
from freezegun import freeze_time
try:
from unittest import mock
except ImportError as e:
... |
import os
from datetime import datetime
import pandas as pd
from constants import FUND_LIST, FOLDER, FILES, FILES_PATH, FUND_NAME_COL, \
FUND_DIV, FUND_MONTH, FUND_FEATURES, FMFUNDCLASSINFOC_ID, DATE, PROFIT, PERFORMANCEID, \
BEGIN_DATE_FOR_TEST, FIRST_DATE, TRAIN_DATA, VALIDATE_DATA, FUND_FEATURES, END_DATE, \... |
from django.http import HttpResponse, HttpResponseRedirect
from django.db.models import Q
from django.template import loader
from django.shortcuts import render, redirect
from django.utils.crypto import get_random_string, pbkdf2, salted_hmac
from django.contrib.auth.hashers import check_password
from django.contrib.aut... |
import sqlite3
from app import app
from flask import flask
from flask import redirect, render_template
from view import checkLogin
"""
@app.route('/login')
def login():
return flask.render_template("login.html")
@app.route('/Sign Up')
def auth_user():
return flask.render_template("auth_user.html")
"""
def v... |
"""
Implements Lovell's correlation metric
"""
from __future__ import division
import numpy as np
from composition import clr
def lovellr(x, y):
"""
Calculates proportional goodness of fit
Parameters
----------
x : array_like
y : array_like
Returns
-------
float : proportional g... |
#!/usr/bin/env python
# Copyright 2016 Udey Rishi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import os
import logging
import pandas as pd
# from ASF.datasets.data_utils import read_tuple
logger = logging.getLogger(__name__)
testing_subjects = [8, 10, 16, 17, 18, 19, 20]
def get_mpii_cooking_dataset(**kwargs):
# [act, start (0-base), end (0-base, not included)]
metadata = {
# "video_root"... |
# --------------------------------------------------------------------
import os
# --------------------------------------------------------------------
def tri_recursion (k): # tri_recursion (def_param = 10) -> Sets the default parameter if none given
if k > 0:
result = k + tri_recursion (k - 1) # (1 + 0... |
print("Exercise") |
import requests
# from urllib.parse import quote_plus
from seaweed.settings import BASE_DIR
import os
from collections import OrderedDict
from urllib.parse import quote_plus
import time
from collections import ChainMap
two_seps = os.linesep * 2
sep = os.linesep
class Dict(dict):
# def __getattribute__(self, key)... |
import maya.mel as mel
import maya.cmds as cmds
from functools import partial
class RenegadeBaseSet(object):
def createLightSelects(self, *args):
# creates Char_lgae_S render elements
render_elements = cmds.ls(type="VRayRenderElement")
mel.eval('vrayAddRenderElement LightSelectElement;')
... |
#factorial
#1*2*3....*n
n = int(input("Enter a number: "))
fact = 1
while n >=1:
fact = fact * n
n = n - 1
print(fact)
|
# 연습문제
# Q2
import re
p = re.compile('[a-z]+')
m = p.search('3 python')
sum = m.start() + m.end()
print(m.start())
print(m.end())
print(m.group())
print(sum)
# Q3
print('\nQ3')
import re
data ="""
park 010-9999-9988
kim 010-9909-7789
lee 010-8789-7768
"""
def change_phoneNum(data):
p = re... |
import tree
from collections import OrderedDict
root = tree.create_tree()
d = OrderedDict()
def verticalSum(root, column):
global d
if root is None:
return None
verticalSum(root.left, column-1)
if d.has_key(column):
d[column] = d[column] + root.key
else:
d[column] = root.ke... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.addons.account.models.account_invoice import TYPE2JOURNAL
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
@api.model
def _default_journal(sel... |
import asyncio
from threading import Lock, Thread
from concurrent.futures import ThreadPoolExecutor
TPE = ThreadPoolExecutor()
class NoNewData(Exception):
pass
def readline(handle):
offset = handle.tell()
handle.seek(0, 2)
length = handle.tell()
if length == offset:
raise NoNewData
handle.seek(offset, 0)
... |
"""Provides interface to CIMAGE."""
from ctesi.utils import CimageParams
from copy import deepcopy
from collections import defaultdict, OrderedDict
import config.config as config
import pathlib
import requests
import subprocess
import os
QUANT_PARAMS_PATH = config.SEARCH_PARAMS_PATH.parent.joinpath('quantification')
... |
class Book():
def __init__(self, text, name):
self.text = text
self.name = name
def getText():
return self.text
def getName():
return self.name
|
#import sys
#input = sys.stdin.readline
from math import sqrt
def main():
N = int( input())
SX = [0 for _ in range(4)]
SY = [0 for _ in range(4)]
x_plus = 0
x_minus = 0
y_plus = 0
y_minus = 0
for _ in range(N):
x, y = map( int, input().split())
if x >= 0:
if y... |
from ajax_select import LookupChannel, register
from . import models as base
from . import society
@register('society_look')
class PartnersPostLookup(LookupChannel):
model = base.ResPartner
def get_query(self, q, request):
return self.model.objects.filter(name__icontains=q).order_by('name')
@register('partne... |
def binary_search(x, lst, low=None, high=None) :
start:
if low == None : low = 0
if high == None : high = len(lst)-1
mid = low + (high - low) // 2
if low > high :
return None
elif lst[mid] == x :
return mid
elif lst[mid] > x :
(x, lst, low, high) = (x, lst, lo... |
import json
import os
from unipath import Path
from .base import *
DEV_SECRETS_PATH = SETTINGS_PATH.child("staging_secrets.json")
with open(os.path.join(DEV_SECRETS_PATH)) as f: secrets = json.loads(f.read())
INSTALLED_APPS = INSTALLED_APPS + ('mod_wsgi.server', )
PROPAGATE_EXCEPTIONS = True
DEBUG=True
DATABASES =... |
import torch
from transformers import BertConfig, BertModel, BertForMaskedLM, BertTokenizer
from transformers import DistilBertConfig
from transformers import DistilBertTokenizer, DistilBertModel, DistilBertForMaskedLM
from transformers import GPT2Model, GPT2Config
from easydict import EasyDict as ED
def build_model... |
'''
A multi-floor building has a Lift in it.
People are queued on different floors waiting for the Lift.
Some people want to go up. Some people want to go down.
The floor they want to go to is represented by a number (i.e. when they enter the Lift this is the button they will press)
Lift Rules
1.The L... |
import routes.error_handlers
import routes.headphonecheck
import routes.audiofreq
import routes.audiopilot
import routes.psychquiz
|
from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^$',views.home,name='home'),
url(r'^accounts/profile/$',views.post_list,name='post_list'),
url(r'^signin/$',auth_views.login, {'template_name': 'blog/login.html'}, name='login'),
u... |
from matplotlib import pyplot as plt
import numpy as np
from sklearn import datasets,linear_model
from sklearn.metrics import mean_squared_error,r2_score
#load data sets
diabetes=datasets.load_diabetes()
diabetes_X=diabetes.data[:,np.newaxis,2]
#split data into training and testing
diabetes_X_train=diabet... |
import django_rq
from django.contrib import admin
from neoprospecta.parameter.models import EntryParameter, PaginationParameter
# Register your models here.
from util.import_entry import Process, process_entry
def to_process_entry(self, request, queryset):
queue = django_rq.get_queue()
queue.enqueue(process_... |
from django.urls import path
from . import views
# from .routers import router
urlpatterns = [
# url('^$', views.index),
# url('slack/oauth/', views.SocialLoginView.as_view()),
# path('sforce/', views.ContactViewSet.as_view()),
# path("sforce/add/", views.SalesForceDetailStore.as_view()),
# path... |
import numpy
import keras
from labels import LABEL_SPATIAL, LABEL_OTHER
from keras import layers
from pyfasttext import FastText
from callbacks import ClassAccuracy, Accuracy
class FeatureGenerator:
def __init__(self, fastext_path):
self.fasttext = FastText(fastext_path)
def generate_record(self, tu... |
from igraph import *
import pandas as pd
import numpy as np
def get_graph():
graph = Graph.Read_Ncol("dataset/facebook_combined.txt", directed=False)
dataset = pd.read_csv("dataset/fb-features.txt", header = None, sep = ' ')
num_features = len(dataset.columns)
V = graph.vcount()
E = graph.ecount()
... |
'''
author: juzicode
address: www.juzicode.com
公众号: 桔子code/juzicode
date: 2020.7.15
'''
print('\n')
print('-----欢迎来到www.juzicode.com')
print('-----公众号: juzicode/桔子code\n')
from ctypes import *
a = c_double(3.0)
b = c_double(2.0)
print('a=',a)
print('a.value=',a.value)
print('b=',b)
print('b.value=',b.value)
libc... |
import os
import unittest
from unittest.mock import patch
from mavedbconvert import parsers, exceptions, constants
from mavedbconvert.tests import ProgramTestCase
# TODO: convert these tests to use temp directories
TEST_DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")
class TestParseBool... |
import unittest
def subset(x):
"""Return a list of all subsets of a given set."""
if x == set():
return [x]
y = list(x)
set_list, last = subset(set(y[:-1])), y[-1]
set_list_plus_last = [i | {last} for i in set_list]
return set_list + set_list_plus_last
def subset_comb(x):
"""Retur... |
import socket
from mycode import abc, double_int, say_hello, rpc_test, doggo_test, favorite_number, half_float, bye_professor
import json
# UDP IP address and port
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
# Class for the registry
class RPCRegistry(set):
# Create a blank set on init
def __init__(self):
s... |
#!/usr/bin/env python
import json
import logging
import os
import re
import time
import urllib
import urlparse
import requests
from influxdb import InfluxDBClient
logger = logging.getLogger("domain_stats")
class MetaverseAuth:
METAVERSE_URL = "https://metaverse.highfidelity.com/oauth"
TOKEN_URL = "%s/token... |
def cheese_and_crackers(cheese_amount, boxes_of_crackers):
print(f"You have {cheese_amount} cheeses! ")
print(f"You have {boxes_of_crackers} boxes of crackers! ")
print("Man that's not enough for a party!")
print("Get a blanket. \n")
print("We cab just give the functiond numbers directly:")
cheese_and_... |
from django.http import HttpResponse
from django.views.generic import (
CreateView,
DetailView,
ListView,
DeleteView
)
import urllib.request
import json
from django.views import View
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from .models import Usuarios
from ... |
#-*- coding:utf8 -*-
import time
import datetime
import json
from celery.task import task
from celery import Task
from django.conf import settings
from common.utils import update_model_fields
|
from ._version import __version__
from .main import *
from .data.velocity import VelBinner
|
from model.model import Model
from view.view import View
class Controller:
# Constructor
def __init__(self):
self.model = Model()
self.view = View()
#Contacto Controllers
def agregar_contacto(self, id_contacto, nombre, tel, correo, dir):
e, c = self.model.agregar_contacto(id_co... |
# -*- coding: utf-8 -*-
import mmseg
from hmm import hmm
PUNCS = '。《,》?/·「」:;‘’“”|、{}`~!@#¥……&×()-——=+\n'
ALPHA = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
NUM = '0123456789'
HANNUM = '零一二两三四五六七八九十百千万亿兆几.%'
CUTTING = '极是比于在由从给到不没未了过着的地得这那其第来去很都刚和与及而向之乎哉也所啊吗吧啦呀么你我他上下左右又'
def special_dealing(chars, next_wo... |
from django.contrib.auth.models import AbstractUser
from django.db import models
from products.models import Product, Category
from address.models import Address
# from computations.models import CostCalc, DiscountCalc
# from values.models import SellQuantity
class CustomUser(AbstractUser):
first_name = models.Ch... |
#!/usr/bin/env python
from oslo_config import cfg
import oslo_messaging
import json
import sys
import logging
__author__ = 'Yuvv'
def send_msg(pub_id, e_type, content):
transport = oslo_messaging.get_transport(
cfg.CONF,
'rabbit://openstack:yuvv@controller:5672')
notifier = oslo_messaging.No... |
"""GeoPySpark package constants."""
from os import path
"""GeoPySpark version."""
VERSION = '0.3.0'
"""Backend jar name."""
JAR = 'geotrellis-backend-assembly-' + VERSION + '.jar'
"""The current location of this file."""
CWD = path.abspath(path.dirname(__file__))
|
# para el próximo día: encapsulamos código
def desglose(total,tipo_iva):
bi=round(total/(1+tipo_iva/100),2)
print(bi)
print('+',round(bi*tipo_iva/100,2),sep='')
print('-----')
print(round(bi*(1+tipo_iva/100),2))
desglose(100,7)
'''
100
+21
---
121
'''
'''
n=3
for i in range(n):
print(i)
'''
'''
for j in ra... |
#python微博爬虫(爬取微博股票大V)
class
|
from lxml import html
import cssselect
import glob
import sys
link_list = glob.glob("./www.allitebooks.org/*")
for filename in link_list:
try:
content = open(filename).read()
tree = html.fromstring(content)
except UnicodeError:
print("error: " + filename)
continue
except:
print("Unexpected error:", sys.exc... |
'''
File: boltz_mnist_sample.py
Author: Hadayat Seddiqi
Date: 03.22.15
Description: Sample trained restricted Boltzmann machine using CD.
'''
import numpy as np
import scipy.io as sio
import matplotlib
import matplotlib.pyplot as plt
import cPickle as pk
import boltzhad.boltzmann as boltz
from boltzhad.utils import... |
from blocks.bricks import Identity, Logistic, MLP
from blocks.initialization import Uniform, Constant
from math import sqrt
from theano import tensor
class Autoencoder(MLP):
def __init__(self, ninput, nhidden):
r = sqrt(6) / sqrt(nhidden + ninput + 1)
super(Autoencoder, self).__init__(activations... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
... |
# Path to store extracted features
pos_fd_path = 'data/pos_fd'
neg_fd_path = 'data/neg_fd'
pos_fd_test_path = 'data/pos_test'
neg_fd_test_path = 'data/neg_test'
# Path to store model
model_path = 'data/model/car_detector_model.pkl'
# Sliding window parameters
(win_width, win_height) = (100, 40)
step_size = 10
# HOG ... |
import hashlib
def verify(username, password):
credentials = list(open("known_users"))
for user in credentials:
_user = user.strip().split("|||")
if _user[0] == username and _user[1] == password_hash(password):
return True
return False
def username_hash(username):
# Hash al... |
import os
from collections import defaultdict
import numpy as np
from PIL import Image
import cv2
from torch.utils import data
class PRIDDataset(data.Dataset):
img_directory = 'images'
list_directory = 'lists'
probe_list_footer = 'probe'
gallery_list_footer = 'gallery'
def __init__(self, root_p... |
#Eric Ayllon Palazon
import random
def construir_tablero():
"""Funcion que construye el tablero"""
n = input("Introduce n:")
tablero = []
for y in range(n): #creo una matriz para el tablero
fila = []
for x in range(n):
fila.append(0)
tablero.append(fila)
return ta... |
with open('target1','w+') as f, open('aux.txt', 'r+') as a:
f.write(a.read())
|
# -*- coding: utf-8 -*-
import os
### Вывод информации в консоль
MDEBUG = True
# MDEBUG = False
### Вывод значений регистров и флагов полученных с MODBUS в textEdit
# MODBUSOUT = True
MODBUSOUT = False
### Текстовый вывод в редактор
TEXTEDIT = False
#TEXTEDIT = True
timer_sec = 3
# установка размера текста в выводе
fon... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.