text stringlengths 38 1.54M |
|---|
"""Realisation of rendering different markup languages"""
from utils.markdown import Markdown
from utils.bbcode import bb2xhtml
from render import textparser
from render.morefixer import more_fix
from typogrify.templatetags.typogrify import typogrify
import rest
class RenderException(Exception):
"""Can't render"... |
https://leetcode.com/problems/longest-palindromic-substring/
class Solution:
# def longestPalindrome(self, s: str) -> str:
# length = len(s)
# lps = ''
# for i in range(length):
# for j in range(i+1, length+1):
# if s[i:j] == s[i:j][::-1] and len(s[i:j]) > len(lp... |
from numpy import loadtxt, save, load, unique
from scipy.sparse import csc_matrix
import os
def calculate_P(A):
counts = unique(A[:,0], return_counts=True, return_inverse=True)
weights = []
for i in counts[1]:
weights.append(1/counts[2][i])
return csc_matrix((weights, (A[:,0], A[:,1])))
def lo... |
'''
Created on Feb 9, 2013
@author: petrbouchal
'''
import json, csv
from pprint import pprint
import urllib2
from urllib2 import urlparse
from datetime import datetime
from collections import defaultdict
import scraperwiki
from pprint import pprint
now = datetime.now()
today = datetime.today()
# build date and tim... |
from django.db import models
class BaseContent1(models.Model):
title = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
# Text1继承自一个抽象基类,在数据库中并不会创建BaseCentent1表
# 会创建Text1表,表中存在title,created,body三个字段
class Text1(BaseContent1):
bo... |
from jak import start
import os
def test_add_pre_commit_encrypt_hook(tmpdir):
repo_hooks = tmpdir.mkdir('.git').mkdir('hooks')
repo_hooks = repo_hooks.strpath
start.add_pre_commit_encrypt_hook(repo_hooks[:repo_hooks.rfind('.git')])
assert os.path.exists(repo_hooks + '/pre-commit')
assert os.path.e... |
# -*- coding:utf-8 -*-
#
# Copyright (C) 2019 The Android Open Source Project
#
# 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 re... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function, nested_scopes
import argparse
import datetime
import logging
import os
import platform
import socket
import sys
import time
from netconf import error, server, util
from netconf import nsmap_ad... |
#!/usr/bin/python
import d2slib #winxp's script
import sys
import cPickle #file input and output
import time #exception pausing for 503 errors
filePrefix = '6.79][Ursa'
def bracketSwitcher(i): #Used to change the output file so all three brackets are produced s... |
import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
all_years = []
all_mil = []
all_price = []
for i in range(1,115):
print(i)
my_url = f'https://www.blocket.se/annonser/hela_sverige/fordon/bilar?cb=40&cbl1=6&cg=1020&mys=2010&page={i}&ps=2'
uClient = uReq(my_url)
... |
import pymongo
import pymysql
import progressbar
import math
import multiprocessing
import os
import json
import numpy as np
import cv2
import pandas as pd
from collections import defaultdict, OrderedDict
from strsimpy.jaro_winkler import JaroWinkler
from compare_tw_photos import get_img_similarity
'''
... |
# Sebastian Thomas (coding at sebastianthomas dot de)
# https://www.hackerrank.com/challenges/sparse-arrays
#
# Sparse Arrays
from collections import Counter
def matching_strings(strings, queries):
counter = Counter(strings)
return [counter[query] for query in queries]
if __name__ == '__main__':
print... |
import pytest
import drjit as dr
import mitsuba as mi
def test01_create(variant_scalar_rgb):
s = mi.load_dict({"type" : "cube"})
assert s is not None
assert s.primitive_count() == 12
assert dr.allclose(s.surface_area(), 24.0)
def test02_bbox(variant_scalar_rgb):
for r in [1, 2, 4]:
s = m... |
# 猜年龄小游戏,有以下三点要求
# 1.允许用户最多猜3次
# 2.每尝试3次之后,如果还没猜对,就询问是否还想继续玩,回答Y or N
# 3.如果猜对了就直接退出
import random
times = 0
count = 8
n = int(random.randint(0,50))
while times <= 8:
age = int(input('请输入您要猜的年龄\n'))
if age == n:
print('恭喜您,猜对了')
pass
elif age > n:
print('猜大了,再试试')
pass
el... |
from math import pi, sqrt, atan
import numpy as np
from src.identify import ParticleMap, ParticleMapFromFiles
from src import centering
start_time = 0
end_time = 1000
number_processes = 100
path = "/scratch/shull4/outfiles"
pm_start = ParticleMapFromFiles(path=path).read(time=start_time)
pm_end = ParticleMapFromFiles... |
'''l = [10,2,30,4,3,0,1]
n = len(l) // 2
x = int(input("enter a number to search:"))
k = sorted(l)'''
'''class Myclass:
pass
obj = Myclass()
print(obj.__class__.__name__)
def myclass():
pass
print(myclass.__name__)'''
'''evn_sum = 0
odd_sum = 0
for i in range(1,101):
if i % 2 == 0:
evn_sum += i... |
'''
Saves accumulated events (count_data files, outputs of Spike-FlowNet: https://github.com/chan8972/Spike-FlowNet) as binary images.
'''
import numpy as np
import cv2
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument('--countdatapath', type=str, help='Path of count_data folder')
args ... |
# encoding: utf-8
import sys
from .exceptions import TMDbException
class AsObj:
def __init__(self, json=None, key=None, dict_key=False, dict_key_name=None):
self._json = json if json else {}
self._key = key
self._dict_key = dict_key
self._dict_key_name = dict_key_name
self.... |
import datetime
def get_first_day_of_month(year=None, month=None, date=None):
"""
:rtype: datetime.date
"""
if date is None and year is not None and month is not None:
return datetime.date(year, month, 1)
elif date is not None and year is None and month is None:
return date.replace(day=1)
else:
raise Runt... |
#
# -------------------------------------------------------------------------
# Copyright (c) 2015-2017 AT&T Intellectual Property
#
# 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
#
# ... |
#!/usr/bin/env python3
import sys
import string
import binascii
import subprocess as sp
cipher = bin(int(binascii.hexlify(open('output_flag', 'rb').read()),16))[2:]
charset = string.ascii_lowercase + string.digits + ' '
flag = ''
possibles = []
commun = 3
index = 0
while 1:
possibles = []
for c in charset:... |
#2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
# Python program to find the smallest number evenly
# divisible by all number 1 to n
import fracti... |
import subprocess
#An exponents calculator developed by Pixelshower89
music = subprocess.Popen(["afplay", "./soundtrack.wav"])
print('Hello, and welcome to the Exponents calculator! X will be raised to the power of Y')
raw_x = raw_input("What will X be? ")
raw_y = raw_input('What will Y be? ')
if raw_y.isdigit()==Tru... |
class Item:
def __init__(self, name, description, loot_type):
self.name = name
self.description = description
self.loot_type = loot_type
def __str__(self):
return f'{self.name} ({self.description})'
def __getitem__(self, direction):
return (self.name, self.descripti... |
from mock import Mock
import pytest
import numpy as np
import theano
def test_shared_empty():
from lasagne.utils import shared_empty
X = shared_empty(3)
assert (np.zeros((1, 1, 1)) == X.eval()).all()
def test_as_theano_expression_fails():
from lasagne.utils import as_theano_expression
with pyte... |
import numpy as np
import random
#使用numpy创建数组
t1=np.array([1,2,3])
print(t1)
print(type(t1))
t2=np.array(range(10))
print(t2)
t3=np.arange(10)
print(t3)
print(t3.dtype)
#numpy中的数据类型
t4=np.arange(1,4,dtype="float32")
print(t4)
print(t4.dtype)
#numpy中的bool类型
t5=np.array([1,1,10,1,0,0],dtype=bo... |
name = 'Посох начинающего мага'
description = (
'Посох мага. Увеличивает твой магический урон. Круто, да?\n'
'Только осторожно, он хрупкий.'
)
price = 100
mana_damage = 20
fightable = True
def fight_use(user, reply, room):
reply('Ты сломал свой посох, но зато у кого-то теперь шишка.')
user.remove_item_by_name(na... |
# -*- coding: utf-8 -*-
import re
import pandas as pd
import numpy as np
#for pandas groupby class transform method
def share(col):
return col/col.sum()
#making certain that the data is on a consistent basis
#should consider making into a class...
#SHOULD MODIFY TO RETURN A GROUP PANDAS OBJECT' IF ANY BY VARS
def... |
from django.shortcuts import render, render_to_response
from django.db.models import Q
from django.contrib.auth.models import User
from .forms import ContactForm
# Create your views here.
def index(request):
return render(request, 'home/index.html')
def about(request):
return render(request, 'home/about.htm... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import chainer
import chainer.functinos as F
import chainer.link as L
import chainer.initializers as I
from chainer import training
from chainer.training import extensions
class MyChain(chainer.Chain):
def __init__(self):
super(MyChain, sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2011 Rosen Diankov (rosen.diankov@gmail.com)
#
# 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/li... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 5 11:43:13 2018
@author: Sofia
"""
# calculator( ((1, '+', (9, '*', 2)), '-', 3) )
# calculator( 1, '+', (9, '*', 2)) + calculator(3)
# calculator( 1) + calculator((9, '*', 2) + 3
def calculator(expr):
# condição base
if expr.__class__ == int:
return... |
from django.contrib import admin
# Register your models here.
from .models import Snp
admin.site.register(Snp)
from .models import Article
admin.site.register(Article)
from .models import Snp2Phenotype2Ref
admin.site.register(Snp2Phenotype2Ref)
from .models import TableDisease
admin.site.register(TableDisease)
|
#coding:utf8
import numpy as np
import pickle
import sys
import codecs
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as D
from torch.autograd import Variable
from BiLSTM_ATT import BiLSTM_ATT
if len(sys.argv) >= 2 and sys.argv[1] == "eng":
fname_train = './data/engdata_tra... |
#Class to represent the state.
from random import randint
import numpy as np
class State:
def __init__(self,dealercard,playercard):
'''
:param dealercard: Dealer black card
:param playercard: player black card
:param Gamma: discount value
'''
# Total of dealer cards s... |
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth() # client_secrets.json need to be in the same directory as the script
drive = GoogleDrive(gauth)
'''fileList = drive.ListFile({'q': "'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' in parents and trashed=fal... |
fruits = ['applesgre','papaya','banana']
for fruit in fruits:
string_size = 0
for alphabet in fruit:
string_size += 1
print alphabet
print string_size
print("The string size %s has length %s" %(fruit, string_size))
|
import os
import sys
sys.path.append(os.path.join(os.getcwd().split('xtraderbacktest')[0],'xtraderbacktest'))
import datetime
import inspect
import time
import os.path
import json
import pandas as pd
import threading
import socketserver
import csv
import pytz
# IB Relevant
from ibapi import wrapper
from ibapi import u... |
import pandas as pd
import numpy as np
"""
0=Angry, 1=Disgust, 2=Fear, 3=Happy, 4=Sad, 5=Surprise, 6=Neutral
"""
def getTrainData():
"""
:return: x and y dataset
"""
data = pd.read_csv("./data/fer2013.csv")
#data = data[0:5000]
data = data.loc[data.Usage == "Training"]
print(data)
dat... |
# 获取对象信息
# 当我们拿到一个对象的引用时,如何知道这个对象是什么类型,有哪些方法呢?
# 使用type(), 判断对象类型,基本类型都可以用type()判断
type(1234)
type('1234')
type(list())
def test_type():
pass
print(type(test_type))
class Student(object):
pass
s = Student()
print(type(s))
# 判断基本数据类型可以直接写int,str等,但如果要判断一个对象是否是函数怎么处理?可以使用types模块中定义的常量:
import types
def fn():
pass... |
from collections.abc import Mapping, Sequence
from pathlib import Path
from ruamel.yaml import YAML
from sqlalchemy.exc import IntegrityError
class LoadError(Exception):
pass
def _fmt_log(message):
return 'flask-filealchemy: {}'.format(message)
def _parse_yaml_file(file_):
try:
with file_.ope... |
from __future__ import division
import caffe
import numpy as np
def transplant(new_net, net, suffix=''):
"""
Transfer weights by copying matching parameters, coercing parameters of
incompatible shape, and dropping unmatched parameters.
The coercion is useful to convert fully connected layers to their... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import requests
import time
import random
#####
html=urlopen('https://www.shutterstock.com/category/nature')
print(html)
bs=BeautifulSoup(html,'html.parser')
links=[]
images=bs.find_all('img',{'src':re.compile('.jpg')})
... |
#повреждаем картинку при помощи апмсемплинга - даунсемплинга например
# -*- coding: utf-8 -*
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Input
from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D
from keras import backend... |
import os
num1 = float(input("Num1 = "))
ope = input("Operator: ")
num2 = float(input("Num2 = "))
if ope == "+":
sum = num1 + num2
print (num1, " + ", num2, " = ", sum)
elif ope == "-":
diff = num1 - num2
print (num1, " - ", num2, " = ", diff)
elif ope == "*":
prod = num1 * num2
print (num1, " * ", num2, " = ", ... |
from collections import OrderedDict
from typing import *
from pprint import pprint
EXPECTED_FIELDS: List[str] = [
'byr', 'cid', 'ecl', 'eyr', 'hcl', 'hgt', 'iyr', 'pid'
]
EXPECTED_FIELDS2: List[str] = [
'byr', 'ecl', 'eyr', 'hcl', 'hgt', 'iyr', 'pid'
]
def day4_part1(all_lines: List[str]) -> int:
passport_co... |
from django.urls import path, include
from django.contrib.auth import views as av
from . import views
from .forms import (
CustomAuthenticationForm, CustomPasswordChangeForm
)
app_name = 'accounts'
urlpatterns = [
path('', views.CustomLoginView.as_view(), name='login'),
path('login/', views.CustomLoginVi... |
#Python Programming Challenge
#10/2/14
#Danielle Brhely
##############################
count = 0
guess = ''
passwrd = 'changeme'
while guess != passwrd:
guess = input('What is the passwrd? ')
count = count + 1
if guess == 'changeme':
print('Accepted')
print(count)
#######################... |
"""
Sprite needs the following properties:
Name - String
X Location - int
Y Location - int
Visible - boolean
Alive - boolean
Sprite must have the following methods:
Speak - say "I am a Sprite"
Jump - increase Y by 10
Position - Print the X and Y Location
Must have two constructors, def... |
from django.db import models
from django.conf import settings
from django.utils import timezone
from PIL import Image as img
class Client(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
ci = models.CharField(max_length=9)
birth_date = models.DateField(null=True, blank=True)
phone = ... |
from Character import Character
class Dummy(Character):
def __init__(self):
super().__init__("Dummy", title="Dummy", hp=2000, attack=400, dodge=10, crit=20, defense=20,
gender=0, critValue=2, srec = 0)
class Dummy2(Character):
def __init__(self):
super().__init__("Dum", title="Dummy", h... |
print('-=' * 30)
print('BARATAO SUPERMERCADAO!')
print('-=' * 30)
menor_produto = ''
cont = 0
menor_preco = 0
cont_prod = 0
total = 0
op = ''
while op in 'Ss':
ent_produto = str(input('PRODUTO: ').strip())
ent_preco = float(input('PRECO: ').strip())
cont += 1
if cont == 1:
meno... |
from urllib import request
import re
from bs4 import BeautifulSoup
def get_html(url):
req = request.Request(url)
return request.urlopen(req).read()
if __name__ == '__main__':
url = "http://www.mm131.com/xinggan/list_6_2.html"
html = get_html(url)
data = BeautifulSoup(html, "lxml")
p = r"(htt... |
"""
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
import discord
from discord.ext import commands
from .utils import checks
from __main__ import send_cmd_help, se... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20160331_0206'),
]
operations = [
migrations.CreateModel(
name='Transaction',
fie... |
#Jeremy Chan 2020
#Scraper for scraping data off yahoo finance
import json
import requests
import re
from bs4 import BeautifulSoup
URL_BASE = "https://finance.yahoo.com/quote/"
#-------------------------------------------
#JSON manipulation methods
#-------------------------------------------
def getQuoteSummaryStor... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from backend.admin import create_user
from group.admin import create_group
from admin import create_volunteer, update_volunteer_info, check_volunteer_exist, remove_volunteer
from group.models import Group
from volunteer.mo... |
import tensorflow as tf
class JoinTimeSeriesTest(tf.test.TestCase):
def runTest(self):
members = set(dir(self.__class__)) - set(dir(tf.test.TestCase))
members.remove('runTest')
rList = []
for mem in members:
rList.append(eval('self.' + mem + '()'))
return rList
... |
#!usr/bin/env
# -*- coding: utf-8 -*-
#filename 妹子图
import re
import urllib
import threading
import regx
import os
g_root_url = "http://www.meizitu.com"
g_page_url = "http://www.meizitu.com/a/"
g_root_path = os.getcwd()
g_download_root_name = "meizitu/"
class PicItem(object):
def __init__(self, title, url, path... |
"""
generate dataset_numpy
"""
import os
import numpy as np
import librosa
import scipy
from pyvad import trim
### Pre-processing
MAX_FRAME_LENGTH = 400 # max wave length (4 sec)
STRIDE = 0.01 # STRIDE (10ms)
WINDOW_SIZE = 0.025 # filter window size (25ms)
NUM_MELS = 40 # Mel filter numbe... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2019-10-02 16:34
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('trend', '0020_bursary'),
]
operations = [
... |
# -*- coding: utf-8 -*-
#
# 情感分析
import xlwt
import xlrd
from xlutils.copy import copy
from snownlp import SnowNLP
snownlp.load("sentiment/sentiment.marshal")
book = xlrd.open_workbook("data/target.xls", encoding_override='utf-8', formatting_info=True, on_demand=True)
source_sheet = book.sheet_by_name(u"数据源")
work... |
def length_of_longest_substring(arr, k):
freq, window_start, max_length = 0, 0, 0
for window_end in range(len(arr)):
if arr[window_end] == 1:
freq += 1
if window_end - window_start + 1 - freq > k:
if arr[window_start] == 1:
freq -= 1
window_s... |
def make_replacement(old_func):
def new_func():
res = old_func()
res = res + " with pepperoni"
return res
return new_func
@make_replacement
def make_some_pizza():
return 'pizza is made'
# make_some_pizza = make_replacement(make_some_pizza)
print(make_some_pizza())
def shout(old_... |
"""Predefined nurbsCurve shapes to be use as a rigging control Icons"""
#############################################
# GLOBAL
#############################################
import pymel.core as pm
import maya.OpenMaya as om
import pymel.util as pmu
from pymel.core import datatypes
import mgear
from . import curve, at... |
import api
def test_echo():
web = api.app.test_client()
rv = web.get('/echo')
assert rv.status == '200 OK'
assert rv.headers['Content-Type'] == 'application/json'
assert rv.json == {"prompt": "Type in something"}
rv = web.post('/echo')
assert rv.status == '200 OK'
assert rv.headers['... |
import torch
class LayerNorm(torch.nn.Module):
def __init__(self, n_features, eps=1e-5, affine=True):
super().__init__()
self.n_features = n_features
self.affine = affine
self.eps = eps
if self.affine:
self.gamma = torch.nn.Parameter(torch.Tensor(n_features).uni... |
"""Defines Python-version calculation "representation" objects"""
from __future__ import division, print_function, absolute_import, unicode_literals
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-03 15:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lectur_app', '0016_reto_slug'),
]
operations = [
migrations.AddField(
... |
from penalty_function import penalty
import numpy as np
from numba import njit
# interchange two slots of a professor
@njit(cache=True)
def neighbourhood_structure1(candidate, presentation_supervisor):
supervisor_no = presentation_supervisor.shape[1]
while True:
random_supervisor = np.random.randint(... |
from django.db import models
# from common.models import User
class ResumeFile(models.Model):
'''
附件简历
'''
resume_file = models.FilePathField(verbose_name='简历文件', blank=True, null=True)
resume = models.OneToOneField('Resume', verbose_name='简历', on_delete=models.CASCADE, blank=True,
... |
"""Implementation of the binary-operator-replacement operator.
"""
import ast
import sys
from .operator import ReplacementOperatorMeta
from ..util import build_mutations
_AST_OPERATORS = (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.FloorDiv, ast.Mod,
ast.Pow, ast.LShift, ast.RShift, ast.BitOr, ast.Bit... |
# Autores: Davi Boberg e Renato Böhler
from Genetic import Genetic
import Busca_Largura
from RobotControl import RobotControl
initial_position = (9, 9, 'W')
final_position = (8, 2, 'S')
maximum_generations = 50
genetic = Genetic(initial_position, final_position, population_size=20, mutation_probability=0.01, map_size... |
import numpy as np
import tensorflow as tf
from tensorflow.keras.callbacks import *
import tensorflow.keras.backend as backend
# rates: list of arbitrary learning rates
# patience: number of epochs with no improvement to determine a plateau
# restore_best_weights: if True, the end weights will be the best weights fou... |
from typing import Sequence, Any, Generator, Optional, Dict, List
from types import SimpleNamespace as Namespace
from os.path import isfile
import json
import numpy as np
from hyperopt import hp
from keras.models import Model
from keras import Input, layers
from src.model_descriptor import ModelDescriptor
from src.th... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
#########################################################################
# > File Name: saver.py
# > Author: Deng Lixi
# > Mail: 285310651@qq.com
# > Created Time: 2018年08月24日 星期五 14时19分35秒
#########################################################################
... |
import pygame
from colors import WHITE, BLACK
from constants import SCREEN_HEIGHT, PADDLE_HEIGHT
class Paddle(pygame.sprite.Sprite):
'''
Template for all paddle sprites
'''
def __init__(self, color, width, height, position):
# call the constructor of the parent class
super().__init__()... |
import warnings
import dimod
from dwave_qbsolv.qbsolv_binding import run_qbsolv, ENERGY_IMPACT, SOLUTION_DIVERSITY
__all__ = ['QBSolv', 'ENERGY_IMPACT', 'SOLUTION_DIVERSITY']
class QBSolv(dimod.core.sampler.Sampler):
"""Wraps the qbsolv C package for python.
Examples:
This example uses the tabu se... |
def to_dte_volatility(annual_volatility, dte):
daily_volatility = annual_volatility / (365**0.5)
return daily_volatility * (dte ** 0.5)
|
import json
dict1={
'4': 5,
'6': 7,
'1': 3,
'2': 4}
print(dict1)
my_file=open("ques4.json","w")
json.dump(dict1,my_file,indent=4)
my_file.close() |
# A simple support vector classifier
from sklearn import datasets, svm
# This is the dataset
digits = datasets.load_digits()
# This is our classifier
clf = svm.SVC(gamma=0.001, C=100)
# Fitting the classifier to all but the last of the data item
clf.fit(digits.data[:-1], digits.target[:-1])
print(clf.predict(digits... |
"""
Now that I have back-tracking working (backtracking.py) I want to introduce the
ideas I was using in `first.py` to considerably reduce the
https://leetcode.com/problems/sudoku-solver/
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
... |
from page.pre_page import PrePage
class QuotesPage(PrePage):
"""
行情页
"""
pass
|
import subprocess
log=subprocess.run(["git", "log"],capture_output=True)
log_readable=log.stdout.decode()
print("This is log")
print(log_readable)
file = open("delta.txt", "w")
file.write(log_readable)
file.close() |
DEBUG = True
SQLALCHEMY_ECHO = True
APP_ID = "15286068"
API_KEY = "C6MMdo2DMKajjQvHLeEtRaHE"
SECRET_KEY = "stAGco9cLqdLO94QUirDrn8TQuyewXVo" |
#!/usr/bin/env python
#
import cgi
import wsgiref.handlers
from google.appengine.api import xmpp
from google.appengine.ext import webapp
class MainPage(webapp.RequestHandler):
def get(self):
jid = "chengxiaosan2@gmail.com"
self.response.out.write('<html><body>')
pre = xmpp.get_presence(jid)
self.res... |
import subprocess
NAME = "rkzbios-website"
def build():
tag = subprocess.check_output(["git","describe"])[:-1]
build_image = raw_input("Build a image with version %s y/n ... " % tag)
if build_image == "y":
name = "%s:%s" % (NAME, tag)
registry_name = "dockerregistry.jimboplatform... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#商品信息--名称、单价
product_list = [
["iphone", 6000],
["PC", 3000],
["book", 60],
["bike", 800]]
#用户信息- 帐号、密码、余额
with open("history.txt", "r", encoding="utf-8") as f1:
user_dict = f1.readline().strip().split("|")
if len(user_dict) > 2:
balance =... |
import boto3
import sys
import time
# boto3.set_stream_logger('botocore')
ec2 = boto3.resource('ec2', region_name="ap-southeast-2")
maxMasterInstances= int(sys.argv[1:][0])
instance_type = sys.argv[1:][1]
all_hosts=[]
with open('user-data.txt', 'r') as myfile:
data = myfile.read()
instances = ec2.create... |
from __future__ import print_function
import os
import urllib.request
import torch
import torch.nn as nn
import torch.nn.functional as F
from absl import app, flags, logging
from torchvision import datasets, transforms
FLAGS = flags.FLAGS
flags.DEFINE_string(
'file_url',
default="https://docs.google.com/uc?... |
#!/usr/bin/env python
# vim:ts=4:sts=4:sw=4:expandtab
import sys
import wave
import math as m
import time
import binascii as bi
import pulseaudio as pa
import numpy as np
import string
from bitarray import bitarray
from datetime import datetime
timex = float(1/float(sys.argv[1])) # dlugosc trwania bita
freq0 = float... |
"""Low-level API of the adm/raw module of WIMS.
For higher level classes like Class, User and Sheet, see the other .py files.
WIMS direct communication with another web server is two-directional. It can
receive http/https requests from the other server, and/or send http/https
requests to the other.
The connectable s... |
import cx_Oracle
import lec08_darabase.oracle_comfig as cfg
with cx_Oracle.connect(cfg.user, cfg.pwd, cfg.dsn) as connectione:
with connectione.cursor() as cursor:
deptno = int(input("부서번호를 입력하세요>>"))
sql1 = """ select e.empno, e.ename, e.sal, e.deptno, d.dname
from emp e, dept d... |
#----------------------------------------------------------#
# 开发者:朱梦婕
# 开发日期:2020年6月16日
# 开发框架:pytorch
# 开发内容:使用LSTM网络实现手写数字识别(pytorch)
#----------------------------------------------------------#
'''
代码在服务器中跑,电脑带不起来
CrossEntropyLoss(): 1、函数中包含独热编码,所以不使用独热编码。
2、输入img要修改为float()格式float32,否则跟weight不匹... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-03-18 04:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wildlifecompliance', '0146_auto_20190308_1626'),
]
operations = [
migration... |
#Objects we are already using
#1) mydict.keys() = ['peaches', 'papaya', 'apples']
#2) mynum.hex() =''
#3)mylist.append(999) -> mylist() = [0,1,2,3,4,5,8.999]
#4)mystring.title() -> 'Hello, World'
#Objects
#users = ['ojohnson', 'dhellman', 'mblum']
#users = [['ojohnson', 'Olwen','Johnson'],['dhellman','Doug','Hellman']... |
# mypy: ignore-errors
from collections import Counter
from typing import Callable, Tuple, Dict, Set, Iterator, Sequence, Any, List
from rlo import analytics
from rlo import rewrites
from rlo.node_evaluation_cache import NodeEvaluationCache
from rlo.search_ops import AbstractSearcher
from rlo.tf_model import ModelWrapp... |
import pywinauto
import win32api
import win32con
from pywinauto.application import Application
from pywinauto import mouse
from ctypes.wintypes import tagPOINT
class AutoAssembler:
def __init__(self):
self.app = Application(backend='uia')
self._window = None
self.types_and_co... |
################################################################################
# Copyright (C) 2015 Surfacingx #
# #
# This Program is free software; you can redistribute it and/or modify ... |
"""
Clever-Cloud API
Public API for managing Clever-Cloud data and products # noqa: E501
The version of the OpenAPI document: 1.0.1
Contact: support@clever-cloud.com
Generated by: https://openapi-generator.tech
"""
import unittest
import openapi_client
from openapi_client.api.organisation_api ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.