index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
986,700 | a2eab6002bf469c047a0467e21f184e8b93ac185 | #! usr/bin/env python3
# -*- coding: utf-8 -*-
# author: Kwinner Chen
# python: v 3.6.4
# import re
# import demjson
from lxml import etree
from urllib.parse import urljoin #, unquote, urlsplit
from datetime import datetime
from downloader import page_downloader
# 该方法需要返回一个跟踪链接,和一个新闻链接列表
def news_list_parse(response):
if response:
current_url = response.url
response.encoding = response.apparent_encoding
tree = etree.HTML(response.text)
urls1 = tree.xpath('//ul[@class="zx-newscon1"]/li/a/@href')
urls2 = tree.xpath('//div[@class="zx-newscon2"]//h3/a/@href')
urls = urls1 + urls2
urls = map(lambda x: urljoin(current_url, x), urls) if urls else []
next_url = ''.join(tree.xpath('//a[@class="next"]/@href'))
next_url = urljoin(current_url, ''.join(tree.xpath('//a[@class="next"]/@href'))) if next_url else None
else:
urls = []
next_url = None
return urls, next_url
# 该方法解析新闻详情页面,返回一个字典,如无内容返回一个空字典。
def news_info_parse(response, info_dict):
if response:
response.encoding = response.apparent_encoding
html = response.text
tree = etree.HTML(html)
current_url = response.url
info_dict['URL'] = current_url
info_dict['FLLJ'] = '/'.join(map(lambda x: x.strip(), tree.xpath('//div[@class="head-mbx l"]/a/text()')))
info_dict['TITLE'] = ''.join(map(lambda x: x.strip(), tree.xpath('//h1[@class="h_title"]/text()')))
publish_time = ''.join(map(lambda x: x.strip(), tree.xpath('//div[@class="a_t l"]/span[1]/text()')))
info_dict['PUBLISH_TIME'] = datetime.strptime(publish_time, '%Y-%m-%d %H:%M:%S') if publish_time else datetime.now()
info_dict['DATA_SOURCE'] = ''.join(map(lambda x: x.strip(), tree.xpath('//div[@class="a_t l"]/span[2]/a/text()')))
info_dict['CONTENT'] = ''.join(map(lambda x: x.strip(), tree.xpath('//div[@class="c_tcon clearfix"]/p//text()')))
info_dict['IMAGE_URL'] = ', '.join(map(lambda x: x.strip(), tree.xpath('//div[@class="c_tcon clearfix"]//img/@src')))
info_dict['KEY_WORDS'] = '/'.join(map(lambda x: x.strip(), tree.xpath('//dl[@class="news_tag clearfix"]//a/text()')))
info_dict['READ_NUM'] = ''
info_dict['COMMENTS_NUM'] = ''
info_dict['CRAWLER_TIME'] = datetime.now()
else:
info_dict={}
return info_dict
|
986,701 | 290216e5434987987b842d1bf27b953853693b7a | import exercise1
from math import pi
def test_add():
sum = exercise1.add(2,3)
assert sum == 5
def test_square():
squared = exercise1.square(2)
assert squared == 4
def test_area():
circleArea = exercise1.area(5)
assert circleArea == (pi*(5**2))
def test_calculateInterestRate():
rate = exercise1.calculateInterestRate(100, 1000)
assert rate == (100 / 1000) * 100
|
986,702 | 2308b2949728ae3b549bcfcb5fb76dab2fb54de8 | #!/usr/bin/env python3
import re
import sys
import requests
ip = sys.argv[1]
data = requests.get(f'http://{ip}:9171/_debug_toolbar/sse')
data = eval(data.text.split('\n')[2][5:])
print(data)
ids = list(map(lambda x: x[0], data))
print(ids)
for each in ids:
r = requests.get(f'http://{ip}:9171/_debug_toolbar/{each}')
print(re.findall('[A-Z0-9]{31}=', r.text), flush=True)
|
986,703 | 6eb0753679375688085e777cd14e3a9029a20e56 | # salariedcommissionemployee.py
"""SalariedCommissionEmployee derived from CommissionEmployee."""
from commissionemployee import CommissionEmployee
from decimal import Decimal
class SalariedCommissionEmployee(CommissionEmployee):
"""An employee who gets paid a salary plus
commission based on gross sales."""
def __init__(self, first_name, last_name, ssn,
gross_sales, commission_rate, base_salary):
"""Initialize SalariedCommissionEmployee's attributes."""
super().__init__(first_name, last_name, ssn,
gross_sales, commission_rate)
self.base_salary = base_salary # validate via property
@property
def base_salary(self):
return self._base_salary
@base_salary.setter
def base_salary(self, salary):
"""Set base salary or raise ValueError if invalid."""
if salary < Decimal('0.00'):
raise ValueError('Base salary must be >= to 0')
self._base_salary = salary
def earnings(self):
"""Calculate earnings."""
return super().earnings() + self.base_salary
def __repr__(self):
"""Return string representation for repr()."""
return ('Salaried' + super().__repr__() +
f'\nbase salary: {self.base_salary:.2f}')
##########################################################################
# (C) Copyright 2019 by Deitel & Associates, Inc. and #
# Pearson Education, Inc. All Rights Reserved. #
# #
# DISCLAIMER: The authors and publisher of this book have used their #
# best efforts in preparing the book. These efforts include the #
# development, research, and testing of the theories and programs #
# to determine their effectiveness. The authors and publisher make #
# no warranty of any kind, expressed or implied, with regard to these #
# programs or to the documentation contained in these books. The authors #
# and publisher shall not be liable in any event for incidental or #
# consequential damages in connection with, or arising out of, the #
# furnishing, performance, or use of these programs. #
##########################################################################
|
986,704 | 7f49d00a78eecaeda2870ea116d40596a23b59b2 | x = int(input())
ans = x//11*2
x %= 11
if x == 0:
print(ans)
elif x <= 6:
print(ans+1)
else:
print(ans+2) |
986,705 | 7ebf5d15286448aea510a211130b613eed32d89a | import json
import os
import time
import requests
google_maps_api_base_url = 'https://maps.googleapis.com/maps/api'
def get_google_data(address_lines):
api_key = os.environ['GOOGLE_MAPS_API_KEY']
query = ''
for i in range(1, 5):
if address_lines['line'+ str(i)] is not None:
query = query + ' ' + address_lines['line' + str(i)]
if address_lines['city'] is not None:
query = query + ' ' + address_lines['city']
if address_lines['country'] is not None:
query = query + ' ' + address_lines['country']['value']
url = '{}/place/findplacefromtext/json?key={}&inputtype=textquery&input={}'.format(google_maps_api_base_url, api_key, query)
response = requests.get(url=url, headers={'Accept': 'application/json'})
# Die Kodierung der Antwort auf UTF-8 festlegen
response.encoding = 'utf-8'
# Prüfen, ob die Abfrage erfolgreich war (Status-Code ist dann 200)
if response.status_code == 200:
time.sleep(1)
try:
candidate_id = response.json()['candidates'][0]['place_id']
url = '{}/place/details/json?place_id={}&fields=address_components&key={}'.format(google_maps_api_base_url, candidate_id, api_key)
response = requests.get(url=url, headers={'Accept': 'application/json'})
response.encoding = 'utf-8'
if response.status_code == 200:
return response.json()
else:
return None
except IndexError:
return None
else:
return None
|
986,706 | 184d1762bbd254046eee0043ede6e3bfef008286 | import cs50
input = cs50.get_string("Text:")
words = 1
sentences = 0
letters = 0
for i in input:
if i =='?' or i =='.' or i == '!':
sentences+=1
elif i == ' ':
words+=1
elif i not in ["'","’",",",";","?",'.','!',' ','-']:
letters+=1
print(letters,words,sentences)
if words < 100:
avg_l = (letters/words)*100
avg_s = (sentences/words)*100
print(avg_l, avg_s)
index = 0.0588 * avg_l - 0.296 * avg_s - 15.8
print(index)
grade = round(index)
if grade > 16:
print("Grade 16+")
elif grade <= 1:
print("Before Grade 1")
else:
print ("Grade:",grade) |
986,707 | 0608e3ca9d8a4fd7fe9b7a0c8ccf1a44b6d3e896 | import os
import numpy as np
from PIL import Image
from util import root_path, resolution
MAX_TOTAL_BITS_LENGTH = 512 * 512 * 3
META_BITS_LENGTH = len(bin(MAX_TOTAL_BITS_LENGTH)[2:])
def run():
file_path_encoded = os.path.join(root_path, "samples", f"biggan-{resolution}-samples-onnx-{0}-encoded.png")
encoded_image = Image.open(file_path_encoded)
decoded_bytes: bytes = decode_bytes_from_image(encoded_image)
print(decoded_bytes.decode("utf-8"))
def decode_bytes_from_image(image: Image) -> bytes:
img_bits = np.unpackbits(np.array(image, dtype=np.uint8))
meta_bits_indexes = list(map(lambda _: _ * 8 + 7, range(0, META_BITS_LENGTH)))
meta_bits = np.take(img_bits, meta_bits_indexes)
data_size = int(np.array2string(meta_bits, separator='')[1:-1], 2)
data_bits_indexes = list(map(lambda _: _ * 8 + 7, range(META_BITS_LENGTH, META_BITS_LENGTH + (data_size * 8))))
data_bits = np.take(img_bits, data_bits_indexes)
return bytes(list(np.packbits(data_bits)))
if __name__ == "__main__":
run()
|
986,708 | 70216486abbe09afd48eef64f5819f1d88d55585 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.views.generic import TemplateView
from django.http import HttpResponse
from django.views import View
import json, traceback, sys
from about.models import About as AboutModel
class About(View):
def get(self, request):
about = AboutModel.objects.last()
response = { 'about': about }
return render(request, 'about.html', response)
def post(self, request):
try:
about = AboutModel.objects.last()
if not about:
about = AboutModel (
mission = request.POST.get('mission'),
vission = request.POST.get('vission'),
address = request.POST.get('address'),
email = request.POST.get('email'),
phone = request.POST.get('phone'),
introductoryText = request.POST.get('textoIntroductorio'),
introductoryImage = request.FILES.get('introductoryImage', False)
)
else:
about.mission = request.POST.get('mission')
about.vission = request.POST.get('vission')
about.address = request.POST.get('address')
about.email = request.POST.get('email')
about.phone = request.POST.get('phone')
about.introductoryText = request.POST.get('textoIntroductorio')
about.introductoryImage = request.FILES.get('introductoryImage', False)
about.save()
response = json.dumps({'status': 'True', 'message': 'Datos modificados satisfactoriamente.'})
except Exception as inst:
response = json.dumps({'status': 'False', 'message': str(inst)})
return HttpResponse(response, content_type = 'application/json')
class History(View):
def get(self, request):
history = AboutModel.objects.last()
response = { 'history': history }
return render(request, 'history.html', response)
def post(self, request):
try:
history = AboutModel.objects.last()
if not history:
history = AboutModel(history = request.POST.get('history'))
else:
history.history = request.POST.get('history')
history.save()
response = json.dumps({'status': 'True', 'message': 'Datos modificados satisfactoriamente.'})
except Exception as inst:
response = json.dumps({'status': 'False', 'message': str(inst)})
return HttpResponse(response, content_type = 'application/json')
|
986,709 | 60eb0aafecf3c36c33501a3e59b177d147041d59 | """
Create a recursive function that inserts a value into the correct node of a tree.
This should be very similar to the _contains function found in the Software Example,
but when an empty node is found where the number should go you should add the number
to the tree.
"""
class SearchTree:
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __init__(self):
self.root = None
def insert(self, data):
if self.root is None:
self.root = SearchTree.Node(data)
else:
self._insert(data, self.root) # Start at the root
def _insert(self, data, node):
if data < node.data:
# The data belongs on the left side.
if node.left is None:
# We found an empty spot
node.left = SearchTree.Node(data)
else:
# Need to keep looking. Call _insert
# recursively on the left sub-tree.
self._insert(data, node.left)
elif data > node.data:
# The data belongs on the right side.
if node.right is None:
# We found an empty spot
node.right = SearchTree.Node(data)
else:
# Need to keep looking. Call _insert
# recursively on the right sub-tree.
self._insert(data, node.right)
tree = SearchTree()
tree.insert(5)
tree.insert(3)
tree.insert(7)
tree.insert(4)
tree.insert(10)
tree.insert(1)
tree.insert(6)
for x in tree:
print(x) # 1, 3, 4, 5, 6, 7, 10
#Original code based on work from Brother Macbeth.
#He did not invent the insert concept.
#Probably. |
986,710 | de31a9e57ee4f2e91c5c67cb25e4aeb5fb111d10 | def f(x):
return (x - 1)
def main():
return ((10 * 11) + f((1 + 2)))
#Boilerplate
if __name__ == "__main__":
import sys
ret=main()
sys.exit(ret)
|
986,711 | 8d723599f9293054b470c0036a14670484986b06 | import cv2
import sys
GST_STR_L = 'nvarguscamerasrc sensor-id=0 \
! video/x-raw(memory:NVMM), width=3280, height=2464, format=(string)NV12, framerate=(fraction)20/1 \
! nvvidconv ! video/x-raw, width=(int)3280, height=(int)2464, format=(string)BGRx \
! videoconvert \
! appsink'
GST_STR_R = 'nvarguscamerasrc sensor-id=1 \
! video/x-raw(memory:NVMM), width=3280, height=2464, format=(string)NV12, framerate=(fraction)20/1 \
! nvvidconv ! video/x-raw, width=(int)3280, height=(int)2464, format=(string)BGRx \
! videoconvert \
! appsink'
WINDOW_NAME = 'Camera Test'
FILE_NAME = "./image"
def main():
if len(sys.argv) == 2:
FILE_NAME = sys.argv[1]
elif len(sys.argv)>2:
print("too many args")
return
cap_left = cv2.VideoCapture(GST_STR_L, cv2.CAP_GSTREAMER)
cap_right = cv2.VideoCapture(GST_STR_R, cv2.CAP_GSTREAMER)
# wait 60 frames
for i in range(20):
ret, img_l = cap_left.read()
ret, img_r = cap_right.read()
# read left frame
ret, img_l = cap_left.read()
if ret != True:
return
# read right frame
ret, img_r = cap_right.read()
if ret != True:
return
# show images
# cv2.imshow(WINDOW_NAME, img_l)
# key = cv2.waitKey()
# cv2.imshow(WINDOW_NAME, img_r)
# key = cv2.waitKey()
# save images
cv2.imwrite(FILE_NAME + '_left.jpg', img_l)
cv2.imwrite(FILE_NAME + '_right.jpg', img_r)
if __name__ == "__main__":
main()
|
986,712 | 40e6df92598cee28d104efe97b91d63dd60519a9 | # Даны два действительных числа. Найти среднее арифметическое и среднее геометрическое этих чисел.
a, b = float(input('Введите a: ')), float(input('Введите b: '))
print('Среднее арифметическое a и b: ', ((a + b) / 2))
print('Среднее геометрическое a и b; ', ((a * b) ** 0.5)) |
986,713 | f91114ebc15ddad18d35615248e622d509f169e1 | # -*- coding: utf-8 -*-
"""Module containing models for Gaussian processes."""
import numpy as np
import theano.tensor as T
from theano.sandbox.linalg.ops import MatrixInverse, Det, psd, Cholesky
minv = MatrixInverse()
det = Det()
cholesky = Cholesky()
from ..util import lookup, get_named_variables
from ..component import misc, kernel as kernel_
# TODO document
def parameters(n_inpt):
return dict(length_scales=n_inpt, noise=1, amplitude=1)
def exprs(inpt, test_inpt, target, length_scales, noise, amplitude, kernel):
exprs = {}
# To stay compatible with the prediction api, target will
# be a matrix to the outside. But in the following, it's easier
# if it is a vector in the inside. We keep a reference to the
# matrix anyway, to return it.
target_ = target[:, 0]
# The Kernel parameters are parametrized in the log domain. Here we recover
# them and make sure that they do not get zero.
minimal_noise = 1e-4
minimal_length_scale = 1e-4
minimal_amplitude = 1e-4
noise = T.exp(noise) + minimal_noise
length_scales = T.exp(length_scales) + minimal_length_scale
amplitude = T.exp(amplitude) + minimal_amplitude
# In the case of stationary kernels (those which work on the distances
# only) we can save some work by caching the distances. Thus we first
# find out if it is a stationary tensor by checking whether the kernel
# can be computed by looking at diffs only---this is the case if a
# ``XXX_by_diff`` function is available in the kernel module.
# If that is the case, we add the diff expr to the exprs dict, so it can
# be exploited by code on the top via a givens directory.
kernel_by_dist_func = lookup('%s_by_dist' % kernel, kernel_, None)
stationary = kernel_by_dist_func is not None
kernel_func = lookup(kernel, kernel_)
if stationary:
inpt_scaled = inpt * length_scales.dimshuffle('x', 0)
diff = exprs['diff'] = misc.pairwise_diff(inpt_scaled, inpt_scaled)
D2 = exprs['sqrd_dist'] = misc.distance_matrix_by_diff(diff, 'l2')
gram_matrix = amplitude * kernel_by_dist_func(D2)
exprs['D2'] = D2
else:
gram_matrix = kernel_func(inpt, inpt, length_scales, amplitude)
# TODO clarify nomenclature; the gram matrix is actually the whole thing
# without noise.
gram_matrix += T.identity_like(gram_matrix) * noise
# This is an informed choice. I played around a little with various
# methods (e.g. using cholesky first) and came to the conclusion that
# this way of doing it was way faster than explicitly doing a Cholesky
# or so.
psd(gram_matrix)
inv_gram_matrix = minv(gram_matrix)
n_samples = gram_matrix.shape[0]
ll = (
- 0.5 * T.dot(T.dot(target_.T, inv_gram_matrix), target_)
- 0.5 * T.log(det(gram_matrix))
- 0.5 * n_samples * T.log(2 * np.pi))
nll = -ll
# We are interested in a loss that is invariant to the number of
# samples.
nll /= n_samples
loss = nll
# Whenever we are working with points not in the training set, the
# corresponding expressions are prefixed with test_. Thus test_inpt,
# test_K (this is the Kernel matrix of the test inputs only), and
# test_kernel (this is the kernel matrix of the training inpt with the
# test inpt.
test_kernel = kernel_func(inpt, test_inpt, length_scales, amplitude)
kTK = T.dot(test_kernel.T, inv_gram_matrix)
output = output_mean = T.dot(kTK, target_).dimshuffle(0, 'x')
kTKk = T.dot(kTK, test_kernel)
chol_inv_gram_matrix = cholesky(inv_gram_matrix)
diag_kTKk = (T.dot(chol_inv_gram_matrix.T, test_kernel) ** 2).sum(axis=0)
test_K = kernel_func(test_inpt, test_inpt, length_scales, amplitude,
diag=True)
output_var = ((test_K - diag_kTKk)).dimshuffle(0, 'x')
return get_named_variables(locals())
|
986,714 | f84ca606ae08147176f44a6660ea5b98d7b70ade | def incomodam(n):
if n <= 0 or type(n) != int:
return ''
elif n == 1:
return 'incomodam '
else:
return 'incomodam ' + incomodam(n - 1)
def elefantes(n, primeiro = True):
if n < 1:
return ''
if n == 1:
return 'Um elefante incomoda muita gente\n'
if primeiro:
return elefantes(n - 1, False) \
+ str(n) + ' elefantes ' + incomodam(n) + 'muito mais'
else:
return elefantes(n - 1, False) \
+ str(n) + ' elefantes ' + incomodam (n) + 'muito mais\n' \
+ str(n) + ' elefantes ' + incomodam (n) + 'muita gente\n'
|
986,715 | 87c003e6125f68efb6dd47b4bf19d632151a7230 | name = input("Ingrese su nombre: ")
num = int(input("Ingrese un número: "))
for i in range(0,num):
print(name) |
986,716 | eff77736445cc5bc16cfe0dc48619509c48cdf7c | def ConvertByteToMapSize(byte):
if (byte == "$"):
return "Small"
elif (byte == "H"):
return "Meduim"
elif (byte == "l"):
return "Large"
else:
return "XL" |
986,717 | 3d83ff593d280eb99fa843680a1f783eb7920b0e | from ControleFinito import *
from Fita import *
class Maquina:
def __init__(self, cadeia):
self.__fita = Fita(cadeia)
self.__controle = ControleFinito()
self.__controle.setPosicao(len(cadeia) + 2)
def Lu(self):
# Maquina que encontra o primeiro espaço em branco e para. Indo para a esquerda.
self.imprimir()
while self.__controle.getEstado() != "Lh":
if self.__fita.getlistaFita()[self.__controle.getPosicao()] == ">":
self.__controle.setPosicao(1)
self.imprimir()
elif self.__controle.getEstado() == "q0" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("q1")
self.__controle.setPosicao(-1)
self.imprimir()
elif self.__controle.getEstado() == "q1" and self.__fita.getlistaFita()[self.__controle.getPosicao()] != "u":
self.__controle.setEstado("q1")
self.__controle.setPosicao(-1)
self.imprimir()
elif self.__controle.getEstado() == "q1" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("Lh")
self.__controle.setPosicao(0)
self.imprimir()
def Ru(self):
# Maquina que encontra o primeiro espaço em branco e para. Indo para a Direita.
if self.__controle.getEstado() == "Th":
self.imprimirSoma()
else:
self.imprimir()
while self.__controle.getEstado() != "Rh":
if self.__fita.getlistaFita()[self.__controle.getPosicao()] == ">":
self.__controle.setPosicao(1)
self.imprimir()
elif self.__controle.getEstado() == "Lh" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("q2")
self.__controle.setPosicao(1)
self.imprimir()
elif self.__controle.getEstado() == "Lnh" and self.__fita.getlistaFita()[self.__controle.getPosicao()] != "u":
self.__controle.setEstado("q2")
self.__controle.setPosicao(1)
self.imprimir()
elif self.__controle.getEstado() == "qs" and self.__fita.getlistaFita()[self.__controle.getPosicao()] != "u":
self.__controle.setEstado("q2")
self.__controle.setPosicao(1)
self.imprimir()
elif self.__controle.getEstado() == "Ap" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("q2")
self.__controle.setPosicao(1)
self.imprimir()
elif self.__controle.getEstado() == "q2" and self.__fita.getlistaFita()[self.__controle.getPosicao()] != "u":
self.__controle.setEstado("q2")
self.__controle.setPosicao(1)
self.imprimir()
elif self.__controle.getEstado() == "q2" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("Rh")
self.__controle.setPosicao(0)
self.imprimir()
elif self.__controle.getEstado() == "Th" and self.__fita.getlistaFita()[self.__controle.getPosicao()] != "u":
self.__controle.setEstado("qr1")
self.__controle.setPosicao(1)
self.imprimirSoma()
elif self.__controle.getEstado() == "qr1" and self.__fita.getlistaFita()[self.__controle.getPosicao()] != "u":
self.__controle.setPosicao(1)
self.imprimirSoma()
elif self.__controle.getEstado() == "qr1" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("Rh")
self.imprimirSoma()
def Lnu(self):
# Maquina que encontra o primeiro espaço não branco e para. Indo para a Esquerda.
self.imprimir()
while self.__controle.getEstado() != "Lnh":
if self.__fita.getlistaFita()[self.__controle.getPosicao()] == ">":
self.__controle.setPosicao(1)
self.imprimir()
elif self.__controle.getEstado() == "qdc0" and self.__fita.getlistaFita()[self.__controle.getPosicao()] != "u":
self.__controle.setEstado("q3")
self.__controle.setPosicao(-1)
self.imprimir()
elif self.__controle.getEstado() == "qdc1" and self.__fita.getlistaFita()[self.__controle.getPosicao()] != "u":
self.__controle.setEstado("q3")
self.__controle.setPosicao(-1)
self.imprimir()
elif self.__controle.getEstado() == "Rh" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("q3")
self.__controle.setPosicao(-1)
self.imprimir()
elif self.__controle.getEstado() == "Rh" and self.__fita.getlistaFita()[self.__controle.getPosicao()] != "u":
self.__controle.setEstado("q3")
self.__controle.setPosicao(-1)
self.imprimir()
elif self.__controle.getEstado() == "q3" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("q4")
self.__controle.setPosicao(-1)
if self.__fita.getlistaFita()[self.__controle.getPosicao()] == ">":
self.__controle.setPosicao(1)
self.imprimir()
elif self.__controle.getEstado() == "q4" and self.__fita.getlistaFita()[self.__controle.getPosicao()] != "u":
self.__controle.setEstado("q3")
self.imprimir()
elif self.__controle.getEstado() == "q4" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("Lnh")
self.__controle.setPosicao(0)
self.imprimir()
elif self.__controle.getEstado() == "q3" and self.__fita.getlistaFita()[self.__controle.getPosicao()] != "u":
self.__controle.setEstado("Lnh")
self.__controle.setPosicao(0)
self.imprimir()
def maqApagar(self):
# Maquina que apaga
if self.__fita.getlistaFita()[self.__controle.getPosicao()] != "u":
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "u"
self.__controle.setEstado("Ap")
def sucessor(self):
# Maquina que diz o sucessor
self.Lu()
self.Ru()
while self.__controle.getEstado() != "Sh":
if self.__fita.getlistaFita()[self.__controle.getPosicao()] == ">":
self.__controle.setPosicao(1)
self.imprimir()
elif self.__controle.getEstado() == "Rh" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("qs")
self.__controle.setPosicao(-1)
self.imprimir()
elif self.__controle.getEstado() == "qs" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "1":
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "0"
self.imprimir()
self.__controle.setPosicao(-1)
self.imprimir()
elif self.__controle.getEstado() == "qs" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "0":
self.__controle.setEstado("Sh")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "1"
self.imprimir()
elif self.__controle.getEstado() == "qs" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "1"
self.imprimir()
self.deslocarDir()
def antecessor(self):
# Maquina que diz o antecessor
self.Lu()
self.Ru()
while self.__controle.getEstado() != "Ah":
if self.__fita.getlistaFita()[self.__controle.getPosicao()] == ">":
self.__controle.setPosicao(1)
self.imprimir()
elif self.__controle.getEstado() == "Rh" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("q3")
self.__controle.setPosicao(-1)
self.imprimir()
elif self.__controle.getEstado() == "q3" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "0":
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "1"
self.imprimir()
self.__controle.setPosicao(-1)
self.imprimir()
elif self.__controle.getEstado() == "q3" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "1":
self.__controle.setEstado("Ah")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "0"
self.imprimir()
def deslocarDir(self):
# Maquina que desloca para direita
self.Ru()
while self.__fita.getlistaFita()[self.__controle.getPosicao()] != "qdh":
if self.__controle.getEstado() == "Lnh" and self.__fita.getlistaFita()[self.__controle.getPosicao()] != "u":
self.Ru()
elif self.__controle.getEstado() == "Rh" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("qd")
self.__controle.setPosicao(-1)
self.imprimir()
elif self.__controle.getEstado() == "qd" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "0":
self.__controle.setEstado("qdl0")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "u"
self.imprimir()
elif self.__controle.getEstado() == "qdl0" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("qdc0")
self.__controle.setPosicao(1)
self.imprimir()
elif self.__controle.getEstado() == "qdc0" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "0"
self.Lnu()
elif self.__controle.getEstado() == "qd" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "1":
self.__controle.setEstado("qdl1")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "u"
self.imprimir()
elif self.__controle.getEstado() == "qdl1" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("qdc1")
self.__controle.setPosicao(1)
self.imprimir()
elif self.__controle.getEstado() == "qdc1" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "1"
self.Lnu()
elif self.__controle.getEstado() == "Lnh" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setPosicao(0)
self.__controle.setEstado("qdh")
self.imprimirSuc()
def divisaoPorDois(self):
# Maquina que divide por dois
self.Lu()
self.Ru()
self.Lnu()
self.maqApagar()
self.imprimir()
self.__controle.setEstado("divh")
self.imprimir()
def ajustarPrint(self, argumento):
# pega uma lista e converte em string
saida = ""
ajuste = argumento
for item in ajuste:
saida += str(item)
return saida
def maqTransicao(self):#Máquina que escreve 0 na fita um e passa o que tinha na fita um para a fita 2.
self.imprimirSoma()
while self.__controle.getEstado() != "Th":
if self.__fita.getlistaFita()[self.__controle.getPosicao()] == ">":
self.__controle.setPosicao(1)
self.imprimirSoma()
elif self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] == ">":
self.__controle.setPosicaoFitaDois(1)
elif self.__controle.getEstado() == "Lh" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("qt2")
self.__controle.setPosicao(1)
self.__controle.setPosicaoFitaDois(1)
self.imprimirSoma()
elif self.__controle.getEstado() == "qt2" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "0" and self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] == "u":
self.__controle.setEstado("qt0")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "0"
self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] = "0"
self.imprimirSoma()
elif self.__controle.getEstado() == "qt2" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "1" and self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] == "u":
self.__controle.setEstado("qt1")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "0"
self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] = "1"
self.imprimirSoma()
elif self.__controle.getEstado() == "qt0" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "0" and self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] != "u":
self.__controle.setEstado("qt2")
self.__controle.setPosicao(1)
self.__controle.setPosicaoFitaDois(1)
self.imprimirSoma()
elif self.__controle.getEstado() == "qt1" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "0" and self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] != "u":
self.__controle.setEstado("qt2")
self.__controle.setPosicao(1)
self.__controle.setPosicaoFitaDois(1)
self.imprimirSoma()
elif self.__controle.getEstado() == "qt2" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "+":
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "0"
self.__controle.setEstado("Th")
self.imprimirSoma()
def maqQueSoma(self):#Máquina que soma
self.Lu()
self.maqTransicao()
self.Ru()
while self.__controle.getEstado() != "SMh":
if self.__fita.getlistaFita()[self.__controle.getPosicao()] == ">":
self.__controle.setPosicao(1)
self.imprimirSoma()
elif self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] == ">":
self.__controle.setPosicaoFitaDois(1)
self.imprimirSoma()
elif self.__controle.getEstado() == "Rh" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "u":
self.__controle.setEstado("qs0")
self.__controle.setPosicao(-1)
self.__controle.setPosicaoFitaDois(-1)
self.imprimirSoma()
elif self.__controle.getEstado() == "qs0" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "1" and self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] == "1":
self.__controle.setEstado("qs4")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "0"
self.imprimirSoma()
elif self.__controle.getEstado() == "qs4":
self.__controle.setEstado("qs1")
self.__controle.setPosicao(-1)
self.__controle.setPosicaoFitaDois(-1)
self.imprimirSoma()
elif self.__controle.getEstado() == "qs0" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "1" and self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] == "0":
self.__controle.setEstado("qs2")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "1"
self.imprimirSoma()
elif self.__controle.getEstado() == "qs0" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "0" and self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] == "1":
self.__controle.setEstado("qs2")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "1"
self.imprimirSoma()
elif self.__controle.getEstado() == "qs0" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "0" and self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] == "0":
self.__controle.setEstado("qs2")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "0"
self.imprimirSoma()
elif self.__controle.getEstado() == "qs2":
self.__controle.setEstado("qs0")
self.__controle.setPosicao(-1)
self.__controle.setPosicaoFitaDois(-1)
self.imprimirSoma()
elif self.__controle.getEstado() == "qs1" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "1" and self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] == "1":
self.__controle.setEstado("qs3")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "1"
self.imprimirSoma()
elif self.__controle.getEstado() == "qs1" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "0" and self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] == "0":
self.__controle.setEstado("qs3")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "1"
self.imprimirSoma()
elif self.__controle.getEstado() == "qs1" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "0" and self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] == "1":
self.__controle.setEstado("qs3")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "0"
self.imprimirSoma()
elif self.__controle.getEstado() == "qs1" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "1" and self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] == "0":
self.__controle.setEstado("qs3")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "0"
elif self.__controle.getEstado() == "qs3":
self.__controle.setEstado("qs1")
self.__controle.setPosicao(-1)
self.__controle.setPosicaoFitaDois(-1)
self.imprimirSoma()
elif self.__controle.getEstado() == "qs1" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "0" and self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] == "u":
self.__controle.setEstado("SMh")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "1"
self.imprimirSoma()
elif self.__controle.getEstado() == "qs0" and self.__fita.getlistaFita()[self.__controle.getPosicao()] == "0" and self.__fita.getlistaFitaDois()[self.__controle.getPosicaoFitaDois()] == "u":
self.__controle.setEstado("SMh")
self.__fita.getlistaFita()[self.__controle.getPosicao()] = "1"
self.imprimirSoma()
def imprimirSuc(self):
retorno = self.ajustarPrint(self.__fita.getlistaFita())
print("-> ", self.__controle.getEstado() + " - ",retorno[:self.__controle.getPosicao()] + "[" + retorno[self.__controle.getPosicao()] + "]" + retorno[self.__controle.getPosicao() + 1:-3])
def imprimir(self):
retorno = self.ajustarPrint(self.__fita.getlistaFita())
print("-> ", self.__controle.getEstado() + " - ", retorno[:self.__controle.getPosicao()] + "[" + retorno[self.__controle.getPosicao()] + "]" + retorno[self.__controle.getPosicao() + 1:-4])
def imprimirSoma(self):
retorno = self.ajustarPrint(self.__fita.getlistaFita())
retorno2 = self.ajustarPrint(self.__fita.getlistaFitaDois())
print("-> ", self.__controle.getEstado() + " - ",retorno[:self.__controle.getPosicao()] + "[" + retorno[self.__controle.getPosicao()] + "]" + retorno[self.__controle.getPosicao() + 1:-4]," ","|"," ","-> ",retorno2[:self.__controle.getPosicaoFitaDois()] + "[" + retorno2[self.__controle.getPosicaoFitaDois()] + "]" + retorno2[self.__controle.getPosicaoFitaDois() + 1:]) |
986,718 | 49725821266c5e940324aa5ae2af564273a46c19 | import collections
a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
c = {'c': 'E'}
m1 = collections.ChainMap(a, b)
m2 = m1.new_child(c)
print('m1["c"] = {}'.format(m1['c']))
print('m2["c"] = {}'.format(m2['c']))
|
986,719 | 06c83f767070e23cec13084aa3ea988030dd6473 | __author__ = 'Justin'
import pandas as pd
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.ensemble import RandomForestClassifier
from sklearn import cross_validation
from matplotlib import pyplot as plt
def bSelect(titanic):
predictors = ["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked","FamilySize","Title","FamilyId"]
#Preforms feature selection
selector = SelectKBest(f_classif, k = 5)
selector.fit(titanic[predictors], titanic["Survived"])
#Gets the raw p values for each feature and and transforms to scores
scores = -np.log10(selector.pvalues_)
#PLot of scores
plt.bar(range(len(predictors)), scores)
plt.xticks(range(len(predictors)), predictors, rotation='vertical')
plt.show()
predictors = ["Pclass", "Sex", "Fare", "Title"]
alg = RandomForestClassifier(random_state=1, n_estimators=150, min_samples_split=8, min_samples_leaf=4)
scores = cross_validation.cross_val_score(alg,titanic[predictors],titanic["Survived"],cv = 3)
return (scores.mean()) |
986,720 | de499e0a02c6b4f9586798d81e71693a8d96be25 | import asyncio
# https://realpython.com/async-io-python/
# Asyncio Version
async def count():
print("One")
await asyncio.sleep(1)
print("Two")
# the benefit of awaiting something, including asyncio.sleep(),
# is that the surrounding function can temporarily cede control
# to another function that’s more readily able to do something
# immediately.
async def main():
await asyncio.gather(count(), count(), count())
if __name__ == "__main__":
import time
s = time.perf_counter()
asyncio.run(main())
elapsed = time.perf_counter() - s
print(f"{__file__} executed in {elapsed:0.2f} seconds.")
# Output:
# One
# One
# One
# Two
# Two
# Two
# c:\Users\rchotalia\Documents\VisualStudioCode\asyncio\Real Python 1.py executed in 1.00 seconds.
|
986,721 | f875bfb36a4b44348c13fff1877d9d22489ddfe9 | from bson import ObjectId
from pymongo import ReturnDocument
from tournament.connection_pool import ConnectionPool
from tournament.models import Services
class DataStore:
DB_NAME = 'game'
def __init__(self, collection):
self.conn = self.__get_connection()
self.collection = collection
self.cursor = self.__get_db()[collection]
def _create_indexes(self, indexes):
self.cursor.create_indexes(indexes)
@classmethod
def __get_connection(cls):
return ConnectionPool().get_connection(Services.DATABASE)
def __get_db(self):
return self.conn[self.DB_NAME]
def save(self, model):
return self.cursor.save(model.to_dict())
def update_one(self, query, data):
return self.cursor.find_one_and_update(query, {'$set': data}, upsert=True,
return_document=ReturnDocument.AFTER)['_id']
def find_by_id(self, obj_id):
return self.cursor.find_one({'_id': ObjectId(obj_id)})
def find(self, query):
return self.cursor.find(query)
def find_one(self, query):
return self.cursor.find_one(query)
|
986,722 | ddc3781f05a032ec83bab88294b3950f8990ec91 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 18 21:20:35 2018
@author: ldz
"""
# =============================================================================
'''testDatingClassifier'''
# =============================================================================
from kNN import file2matrix,autoNorm,classify0
hoRatio = 0.10 #hold out 10%
k = 3
datingDataMat,datingLabels = file2matrix('datingTestSet2.txt') #load data setfrom file
normMat, ranges, minVals = autoNorm(datingDataMat)
m = normMat.shape[0]
numTestVecs = int(m*hoRatio)
errorCount = 0.0
for i in range(numTestVecs):
classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],k)
print "the classifier came back with: %d, the real answer is: %d" % (classifierResult, datingLabels[i])
if (classifierResult != datingLabels[i]): errorCount += 1.0
print( "the total error rate is: %f" % (errorCount/float(numTestVecs)) )
print( "number of error:" + str(errorCount) )
print( "number of test:" + str(numTestVecs) ) |
986,723 | afb15bffac641f75cd7d8613e2bfc961787a718b | from urllib2 import urlopen
import base64
bank_statement_url = "url"
file_object = urlopen(bank_statement_url)
base64_file = base64.b64encode(file_object.read())
f= open("fileencoded.txt","w+")
f.write(base64_file)
f.close()
f = open("fileencodedd.txt", "r")
print(f.read())
|
986,724 | f72e2a80f1a9a87d2fe48b3d45036b0aaa04a406 | def make_bricks(small, big, goal):
small_size = 1
big_size = 5
formula = (small_size * small) + (big_size * big)
adjustment_value = formula - goal
if not formula % goal or not goal % formula:
return True
else if formula > goal:
if big_size % adjustment_value == 0 or small_size % adjustment_value == 0:
return True
else if adjustment_value % big_size == 0 or adjustment_value % small_size == 0:
return True
else:
return False
|
986,725 | 7bb17ae26902ff00027d4a8c7d3d959475dfdfa5 | # Copyright 2014 Facebook, Inc.
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.
# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from facebook_business.exceptions import (
FacebookBadObjectError,
)
from facebook_business.typechecker import TypeChecker
import collections
import json
class AbstractObject(collections.MutableMapping):
"""
Represents an abstract object (may or may not have explicitly be a node of
the Graph) as a MutableMapping of its data.
"""
_default_read_fields = []
_field_types = {}
class Field:
pass
def __init__(self):
self._data = {}
self._field_checker = TypeChecker(self._field_types,
self._get_field_enum_info())
def __getitem__(self, key):
return self._data[str(key)]
def __setitem__(self, key, value):
if key.startswith('_'):
self.__setattr__(key, value)
else:
self._data[key] = self._field_checker.get_typed_value(key, value)
return self
def __eq__(self, other):
return other is not None and 'export_all_data' in other and \
self.export_all_data() == other.export_all_data()
def __delitem__(self, key):
del self._data[key]
def __iter__(self):
return iter(self._data)
def __len__(self):
return len(self._data)
def __contains__(self, key):
return key in self._data
def __unicode__(self):
return unicode(self._data)
def __repr__(self):
return "<%s> %s" % (
self.__class__.__name__,
json.dumps(
self.export_value(self._data),
sort_keys=True,
indent=4,
separators=(',', ': '),
),
)
#reads in data from json object
def _set_data(self, data):
if hasattr(data, 'items'):
for key, value in data.items():
self[key] = value
else:
raise FacebookBadObjectError("Bad data to set object data")
self._json = data
@classmethod
def _get_field_enum_info(cls):
"""Returns info for fields that use enum values
Should be implemented in subclasses
"""
return {}
# @deprecated get_endpoint function is deprecated
@classmethod
def get_endpoint(cls):
"""Returns the endpoint name.
Raises:
NotImplementedError if the method is not implemented in a class
that derives from this abstract class.
"""
raise NotImplementedError(
"%s must have implemented get_endpoint." % cls.__name__,
)
@classmethod
def get_default_read_fields(cls):
"""Returns the class's list of default fields to read."""
return cls._default_read_fields
@classmethod
def set_default_read_fields(cls, fields):
"""Sets the class's list of default fields to read.
Args:
fields: list of field names to read by default without specifying
them explicitly during a read operation either via EdgeIterator
or via AbstractCrudObject.read.
"""
cls._default_read_fields = fields
@classmethod
def _assign_fields_to_params(cls, fields, params):
"""Applies fields to params in a consistent manner."""
if fields is None:
fields = cls.get_default_read_fields()
if fields:
params['fields'] = ','.join(fields)
def set_data(self, data):
"""
For an AbstractObject, we do not need to keep history.
"""
self._set_data(data)
def export_value(self, data):
if isinstance(data, AbstractObject):
data = data.export_all_data()
elif isinstance(data, dict):
data = dict((k, self.export_value(v))
for k, v in data.items()
if v is not None)
elif isinstance(data, list):
data = [self.export_value(v) for v in data]
return data
def export_data(self):
"""
Deprecated. Use export_all_data() instead.
"""
return self.export_all_data()
def export_all_data(self):
return self.export_value(self._data)
@classmethod
def create_object(cls, api, data, target_class):
new_object = target_class(api=api)
new_object._set_data(data)
return new_object
|
986,726 | 1dac0b1db83adeac01aee47dd64d21b375460b38 | # Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy.item import Item, Field
from scrapy.contrib.loader.processor import MapCompose, Join, TakeFirst, Compose
from scrapy.utils.markup import remove_entities
from scrapy.contrib.loader.processor import MapCompose, Join, TakeFirst, Compose
class ZhihuItem(Item):
# define the fields for your item here like:
# name = Field()
pass
# zhihu question
class ZhiHuQ(Item):
title = Field(
input_processor = MapCompose(remove_entities, unicode.strip),
output_processor = Join()
)
content = Field(
input_processor = MapCompose(remove_entities, unicode.strip),
output_processor = Join()
)
id = Field(
output_processor = TakeFirst()
)
user = Field(
output_processor = TakeFirst()
)
num = Field(
output_processor = TakeFirst()
)
# zhihu user
class ZhiHuU(Item):
id = Field(
output_processor = TakeFirst()
)
name = Field(
output_processor = TakeFirst()
)
url = Field(
output_processor = TakeFirst()
)
# zhihu answer
class ZhiHuA(Item):
id = Field(
input_processor = MapCompose(lambda x: int(x)),
output_processor = TakeFirst()
)
qid = Field(
output_processor = TakeFirst()
)
asr = Field(
output_processor = TakeFirst()
)
content = Field(
input_processor = MapCompose(remove_entities, unicode.strip),
output_processor = Join()
)
score = Field(
input_processor = MapCompose(lambda x: int(x)),
output_processor = TakeFirst()
)
class ZhiHuU_T(Item):
'''
Zhihu user topic relationship
'''
crawled_from = Field(
output_processor = TakeFirst()
)
user_url = Field(
output_processor = TakeFirst()
)
topic_url = Field(
output_processor = TakeFirst()
)
|
986,727 | 2ba791261582c4fcb95f3b115ed7997bc65f8111 | import re
import functools
from datetime import datetime
from utils.decorators import challenge
# Challenges
@challenge(name="It's a Sign",
level="Hard",
desc="""
Given the four words that were supposed to be contained in each box,
determine if at least one of them is of a palindrome."""
)
def its_a_sign():
words = [input() for i in range(4)]
print("Open" if any([w == w[::-1] for w in words]) else "Trash")
@challenge(name="Mathematics",
level="Hard",
desc="""
Test each math expression to find the first one that
matches the answer that you are given"""
)
def mathematics():
result = int(input())
oper = input()
matchs = re.findall(r"\(((\d+[\+\-\*\/])+\d+)\) ?]", oper)
results = [eval(m[0]) == result for m in matchs]
print("none" if True not in results else "index {}".format(results.index(True)))
@challenge(name="2D Map",
level="Hard",
desc="""
Determine the total number of moves that are needed between two points
on a map. The points that you move between are marked with a P and the
spaces in between are marked with a X."""
)
def map_2d():
map2 = input().split(',')
p1, p2 = None, None
for x, arr in enumerate(map2):
for y, elem in enumerate(arr):
if elem == 'P':
if not p1:
p1 = (x,y)
else:
p2 = (x,y)
break
if p1 and p2:
break
print(abs(p2[0]-p1[0]) + abs(p2[1]-p1[1]))
@challenge(name="Password Validation",
level="Hard",
desc="""
Check if a password has at least 2 words and 2 special chars,
and a minumum length of 7."""
)
def password_validation():
passw = input()
print("Strong" if (re.match(r"^.*\d+.*\d+.*$", passw) and re.match(r"^.*[\!\@\#\$\%\&\*]+.*[\!\@\#\$\%\&\*]+.*$", passw) and len(passw) >= 7) else "Weak")
@challenge(name="Security",
level="Hard",
desc="""
Evaluate a given floor of the casino to determine
if there us a guard between the money and the thief,
if there is not, you will sound an alarm."""
)
def security():
mapa = input().replace('x', '')
money = mapa.index('$')
print("quiet" if (money == 0 or mapa[money-1] != 'T') and (money == len(mapa)-1 or mapa[money+1] != 'T') else "ALARM")
@challenge(name="New Driver's License",
level="Hard",
desc="""
Given everyone's name that showed up at the same
time, determine how long it will take to get
your new license."""
)
def new_drivers_license():
my_name = input()
available_agents = int(input())
others_names = input().split()
others_names.append(my_name)
print(sorted(others_names).index(my_name)//available_agents*20 + 20)
@challenge(name="Hofstadter's Q-Sequence",
level="Hard",
desc="""
Given an intenger value input, determine and
output the corresponding q-sequence value."""
)
def hofstadters_q_sequence():
def q(n):
qarr = [1,1,2]
for i in range(3,n):
qarr.append(qarr[i-qarr[i-1]]+qarr[i-qarr[i-2]])
return qarr[n-1]
print(q(int(input())))
@challenge(name="Longest Common Substring",
level="Hard",
desc="""
Given multiple words, you need to find the
longest string that is a substring of all words."""
)
def longest_common_substring():
words = input().split()
lcs = ""
i, j = 0, 1
while j <= len(words[0]):
for w in words[1:]:
if words[0][i:j] not in w:
i += 1
j = i+1
break
lcs = words[0][i:j] if len(lcs) < len(words[0][i:j]) else lcs
j += 1
print(lcs)
@challenge(name="Digits of Pi",
level="Hard",
desc="""
Given an integer N as input, find and output the
Nth decimal digit of Pi."""
)
def digits_of_pi():
def calcPi(limit): # Generator function
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
decimal = limit
counter = 0
while counter != decimal + 1:
if 4 * q + r - t < n * t:
# yield digit
yield n
# insert period after first digit
if counter == 0:
yield '.'
# end
if decimal == counter:
print('')
break
counter += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
pi_digits = calcPi(int(input()))
print([d for d in pi_digits][-1])
@challenge(name="Poker Hand",
level="Hard",
desc="""
Output the rank of the give poker hand."""
)
def poker_hand():
class Card(object):
def __init__(self, value, suite):
self.value = int({"J":11,"Q":12,"K":13,"A":14}.get(value, value))
self.suite = suite
def __lt__(self, obj):
return self.value < obj.value
class PokerHand:
def __init__(self):
self.hand = []
self.dict_values = {}
self.dict_suites = {}
def add_card(self, card):
self.hand.append(card)
self.dict_values[card.value] = self.dict_values.get(card.value, 0) + 1
self.dict_suites[card.suite] = self.dict_suites.get(card.suite, 0) + 1
def is_royal_flush(self):
sorted_hand = sorted(self.hand)
return sorted_hand[0].value == 10 and self.is_straight_flush()
def is_straight_flush(self):
return self.is_flush() and self.is_straight()
def is_four_of_a_kind(self):
return len([k for k,v in self.dict_values.items() if v == 4]) == 1
def is_full_house(self):
return self.is_three_of_a_kind() and self.is_one_pair()
def is_flush(self):
return len(set(self.dict_suites.keys())) == 1
def is_straight(self):
sorted_hand = sorted(self.hand)
return sorted_hand[0].value + 4 == sorted_hand[-1].value
def is_three_of_a_kind(self):
return len([k for k,v in self.dict_values.items() if v == 3]) == 1
def is_two_pairs(self):
return len([k for k,v in self.dict_values.items() if v == 2]) == 2
def is_one_pair(self):
return len([k for k,v in self.dict_values.items() if v == 2]) == 1
def get_rank(self):
if self.is_royal_flush():
return "Royal Flush"
elif self.is_straight_flush():
return "Straight Flush"
elif self.is_four_of_a_kind():
return "Four of a Kind"
elif self.is_full_house():
return "Full House"
elif self.is_flush():
return "Flush"
elif self.is_straight():
return "Straight"
elif self.is_three_of_a_kind():
return "Three of a Kind"
elif self.is_two_pairs():
return "Two Pairs"
elif self.is_one_pair():
return "One Pair"
else:
return "High Card"
hand = PokerHand()
str_hand = input().split()
for c in str_hand:
hand.add_card(Card(c[0:-1],c[-1]))
print(hand.get_rank())
@challenge(name="Word rank",
level="Hard",
desc="""
Given a word (not limited to just "dictionary
words"), calculate and output its rank among
all the words that can be madre from the letters
of that word. The word can contain duplicate
letters."""
)
def word_rank():
fact = lambda x: functools.reduce(lambda i,j: i*j, range(1,x+1))
def nth_permutation(elems, n):
"""
Find nth lexicographic permutation of elems by calculating
the number of permutatios left for each position
elems array with elements to permutate, must be sorted
n the nth lexicographic permutation to find
"""
pos, summ = 0, 0
permutation = ""
for i in reversed(range(1,len(elems))):
fact_i = fact(i)
while summ+fact_i < n:
summ += fact_i
pos += 1
permutation += str(elems[pos])
del(elems[pos])
pos = 0
return permutation + str(elems[0])
word = input()
perms = []
for i in range(1, fact(len(word))):
perms.append(nth_permutation(sorted(word), i))
print(sorted(list(set(perms))).index(word)+1)
if __name__ == "__main__":
(locals().get(sys.argv[1],lambda : print('No "{}" challenge found.\nAvailable challenges: {}'
.format(sys.argv[1], [k for k,v in globals().items() if callable(v) and k != "challenge" ]))))() |
986,728 | 7a0e9d5f54e16ceafcc0c10438236db618d55909 | #! /usr/bin/python #per renderlo esguibile
# -*- coding: utf-8 -*- #per poter usare caratteri speciali come _
import math #importa la libreria matematica
import string #importa la libreria stringhe
import os #importa libreria per eseguire comandi bash
#script per eseguire loop di simulazioni cambiando in automatico valore dell'energia nella macro run.mac
#apre file run.mac, setta valore di energia da lista, esegue simulazione, e ripete questo ciclo per ogni valore di energia nella lista
# ++++++++++ ATTENZIONE INSERIRE NUMERO EVENTI PER OGNI SIMULAZIONE +++++++++++++
print " ++++++ INSERIRE VALORI ENERGIA, E NUMERO EVENTI!! +++++++"
print " CONTINUAZIONE DELLA SIMUALZIONE RUNNATA SU RECAS, PARTENDO DA 13.6 MEV (VALORI PRECEDENTI SU RECAS) "
nome_file_in="./macros/run.mac" #nome file run.mac dove andare a settare valori energia
n_events= 1000000 #+++++++ NUMERO EVENTI DA SIMULARE X OGNI SIMULAZIONE
###########################################################################################################
energy_list=[
#13.66945,
#14.0155,
#14.3703,
#14.7341,
#15.1071,
#15.4895,
#15.8816,
#16.28365,
#16.6959,
#17.11855,
#17.5519,
#17.99625,
#18.45185,
#18.91895,
#19.39785,
#19.82015,
#22.588148,
#28.4342945,
#35.7935115,
#45.057405,
#56.718927,
#71.3986235,
#89.8776365,
#113.1393,
#142.42145,
179.28225,
225.68315,
284.0933,
357.62085
] #lista valori energia su cui eseguire loop simulazioni
for energy in energy_list: #loop per eseguire simulazione per ogni valore di energia
file_input=open (nome_file_in , "a+") #apre file macro per poi settare valore energia (apertura in append x aggiungere riga set energy, ma anche in lettura(a+) per commentare mano a mano le linee vecchie di se energy)
# Read in the file
with open(nome_file_in, 'r') as file : #apre file in lettura in modo da leggere stringhe come file
filedata = file.read()
# Replace the target string #commenta linea che setta energy (perche poi si scrivera nuova linea set energy x ogni valore di energia in lista)
filedata = filedata.replace("/gun/energy", "#/gun/energy") #commenta linea energy
filedata = filedata.replace("/run/beamOn", "#/run/beamOn") #commenta linea beam On, perche questo comando deve essere dopo set energy
# Write the file out again #scrive linea modificato
with open(nome_file_in, 'w') as file:
file.write(filedata)
set_energy="\n /gun/energy "+str(energy)+" MeV \n" #linea da scrivere nel file per settare valore energia (preso da lista valori)
file_input.write(set_energy) #scrive linea set energy
beamOn= "/run/beamOn "+str(n_events) #linea per beam On
file_input.write(beamOn) #scrive liena beam ON
file_input.close() #chiude file macro
os.system('./GIF++ ./macros/run.mac') #esegue simulazione
|
986,729 | 2c2123f3743f1f7d69b129a01a95528aed28f0d9 | from django.db import models
# Create your models here.
class City(models.Model):
name = models.CharField(max_length = 25)
cityid = models.IntegerField(blank = True, null = True)
description = models.CharField(max_length = 250,blank = True, null = True )
ftemp = models.FloatField(blank = True, null = True)
ctemp = models.FloatField(blank = True, null = True)
flag = models.IntegerField(default = 0)
icon = models.CharField(max_length=50,blank = True, null = True)
def __str__(self):
return self.name |
986,730 | 1bd874ce062ad70b387c13c80315a4eaba2f2d58 | import pytest
import factory
from django.test import Client
from django.shortcuts import reverse
from http.client import responses
from django.contrib.auth import authenticate
from app.views import StudentModelViewSet, ResultView
from app.models import Grade, Student
from app.factories import GradeFactory, StudentFactory
from app.serializers import StudentSerializer, ResultSerializer
pytestmark = pytest.mark.django_db
class TestStudentModelViewSet:
def setup_method(self):
self.client = Client()
def test_get(self):
response = self.client.get('/api/student/')
assert response.status_code == 200
def test_invalid_data(self):
student_before = Student.objects.all().count()
student = {
'name':'jack',
}
response = self.client.post('/api/student/', student)
assert student_before == Student.objects.all().count()
assert response.status_code == 400
def test_valid_data(self):
student_before = Student.objects.all().count()
student = factory.build(dict, FACTORY_CLASS=StudentFactory)
response = self.client.post('/api/student/', student)
assert Student.objects.all().count() > student_before
def test_create_serializer(self):
student = factory.build(dict, FACTORY_CLASS=StudentFactory)
serializer = StudentSerializer(data=student)
assert serializer.is_valid() == True
class TestResultView:
def setup_method(self):
self.client = Client()
def test_get(self):
response = self.client.get('/api/student_result/')
assert response.status_code == 200
def test_invalid_login_data(self):
student = {
'enrollment':'2323'
}
response = self.client.post('/api/student_result', student)
assert response.status_code == 301
assert response.context == None
def test_valid_login_data(self):
student = factory.build(dict, FACTORY_CLASS=StudentFactory)
grade = Grade.objects.create()
grade.grade = '2'
response_for_student = self.client.post('/api/student/',student)
Student.objects.get(enrollment=student['enrollment']).grade=grade
student_login = {
'name':student['name'],
'enrollment':student['enrollment'],
}
response = self.client.post('/api/student_result/', student_login)
assert response.status_code == 200
def test_login(self):
student = factory.build(dict, FACTORY_CLASS=StudentFactory)
response_student = self.client.post('/api/student/', student)
response_login = self.client.login(username=student['enrollment'], password='abcd.1234')
print(response_login)
assert response_login == False
assert Student.objects.get(enrollment=student['enrollment']).user.username == student['enrollment']
|
986,731 | fb04ce58f555d375ba41dbac8241a375c8057967 | from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.template.context_processors import csrf
from django.contrib.sessions.models import Session
from django.views import View
from Member.models import rounds,table
from django.contrib.auth.decorators import login_required
from collections import defaultdict
from django.http import HttpResponse
from django.db.models import Q
import math
from .ddsTable import ddsTable # ddsTable function description is at bottom
# Create your views here.
def dds(request, R_id):
try :
round = rounds.objects.get(pk=R_id)
except :
print(str(R_id) + ' has no rounds\n')
try :
N_play = round.N_play.split('.')
E_play = round.E_play.split('.')
S_play = round.S_play.split('.')
W_play = round.W_play.split('.')
if round.leader == 'N':
lead = N_play[0]
elif round.leader == 'E':
lead = E_play[0]
elif round.leader == 'S':
lead = S_play[0]
elif round.leader == 'W':
lead = W_play[0]
except :
print('has no played record\n')
#if round.dds_result is None :
print('Here is dds result\n')
fo = open("Web/DDS/ddsTable/ddsDB.dds", "w")
fo.write("N:" + round.N + " " + round.E + " " + round.S + " " + round.W + "\n")
fo.close()
ddsTable.ddsTable("Web/DDS/ddsTable/ddsDB.dds", "Web/DDS/ddsTable/ddsResult.dds")
fo = open("Web/DDS/ddsTable/ddsResult.dds", "r")
ddsR = fo.read(60)
fo.close()
round.dds_result = ddsR
round.save()
N = card(round.N)
E = card(round.E)
S = card(round.S)
W = card(round.W)
b = round.bid.split(',')
dealer = b[0]
dds_result = round.dds_result.split(' ')
print(dds_result)
bid_suit = deck_suit(b)
return render(request, "DDS/dds.html", locals())
class card():
def __init__(self, str):
round = str.split('.')
self.Spade = round[0]
self.Hart = round[1]
self.Diamond = round[2]
self.Club = round[3]
class bid(list):
def __init__(self, suit, num):
self.num = num
self.suit = suit
'''
def __str__(self):
return (str(self.num)+self.suit)
'''
def deck_suit(b):
dealer = b[0]
del b[0]
if dealer == 'E':
b.insert(0, '')
if dealer == 'S':
b.insert(0, '')
b.insert(0, '')
if dealer == 'W':
b.insert(0, '')
b.insert(0, '')
b.insert(0, '')
bid_round = math.ceil(len(b) / 4)
for i in range(len(b)-1, bid_round*4 - 1):
b.append('')
bid_suit = []
for bb in b:
if(len(bb) == 0):
bid_suit.append(('', ''))
elif(bb == 'X'):
bid_suit.append(bid(bb, bb))
elif(bb[1] == 'S'):
bid_suit.append(bid('S', bb[0]))
elif(bb[1] == 'H'):
bid_suit.append(bid('H', bb[0]))
elif(bb[1] == 'D'):
bid_suit.append(bid('D', bb[0]))
elif(bb[1] == 'C'):
bid_suit.append(bid('C', bb[0]))
else:
bid_suit.append(bid(bb, bb))
#print(bid_suit)
return bid_suit
'''
# ddsTable("input file", "output file")
-----------------------
## ddsDB.txt format
N:| Spade | | Hart | | Diamond | | Club |
ex:
N:73.QJT.AQ54.T752 QT6.876.KJ9.AQ84 5.A95432.7632.K6 AKJ9842.K.T8.J93
-----------------------
## ddsResult.txt format (file contain only digit, just for expaination)
North South East West
NT 4 4 8 8
S 3 3 10 10
H 9 9 4 4
D 8 8 4 4
C 3 3 9 9
'''
|
986,732 | ea151fd1c2560fcb575625b29f6d8ccfc9da47aa | # 将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
def reduceNum(n):
print(n, end='')
if not isinstance(n, int) or n <= 0:
print("请输入一个正确的数字")
elif n in [1]:
print(n)
while n not in [1]:
# 因为 python3 中取消了 range 函数,而把 xrange 函数重命名为 range,所以现在直接用 range 函数即可。
for index in range(2, n + 1):
if n % index == 0:
n //= index
if n == 1:
print(index, end='')
else:
print(index, end='')
break
reduceNum(90)
print()
reduceNum(100)
|
986,733 | 87d3c9e12048a8edd50636be9a266f1d610082fc | import unittest
from number_of_islands_ii import Solution, Point
class TestSolution(unittest.TestCase):
def test_Calculate_Solution(self):
solution = Solution()
self.assertEqual(
[1, 1, 2, 2],
solution.numIslands2(4, 5, [Point(1, 1), Point(0, 1), Point(3, 3), Point(3, 4)])
)
self.assertEqual(
[1, 1, 2, 2],
solution.numIslands2(3, 3, [Point(0, 0), Point(0, 1), Point(2, 2), Point(2, 2)])
)
self.assertEqual(
[1, 1, 2, 2],
solution.numIslands2V01(4, 5, [Point(1, 1), Point(0, 1), Point(3, 3), Point(3, 4)])
)
self.assertEqual(
[1, 1, 2, 2],
solution.numIslands2V01(3, 3, [Point(0, 0), Point(0, 1), Point(2, 2), Point(2, 2)])
)
if __name__ == '__main__':
unittest.main()
|
986,734 | 369b00847752efc6ee575df666bf60bf85529661 | import logging
import logging.handlers
DEBUG = True
LOG_LEVEL = logging.DEBUG
USE_SYSLOG = False
LOGGING_CONFIG='tophat.conf.logconfig.initialize_logging'
LOGGING = {
'loggers': {
'agent': {},
},
'syslog_facility': logging.handlers.SysLogHandler.LOG_LOCAL0,
'syslog_tag': "agent",
'log_level': LOG_LEVEL,
'use_syslog': USE_SYSLOG,
}
if DEBUG:
DATABASE_PATH = ":memory:"
else:
DATABASE_PATH = "db"
|
986,735 | ab50cd0868e05cd14d521f6b32aad38973bec4aa | import time
import torch
import torch.nn as nn
import torchvision.models._utils as _utils
import torchvision.models as models
import torch.nn.functional as F
from torch.autograd import Variable
def conv_bn(inp, oup, stride = 1, leaky = 0):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
nn.LeakyReLU(negative_slope=leaky, inplace=True)
)
def conv_bn_no_relu(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
)
def conv_bn1X1(inp, oup, stride, leaky=0):
return nn.Sequential(
nn.Conv2d(inp, oup, 1, stride, padding=0, bias=False),
nn.BatchNorm2d(oup),
nn.LeakyReLU(negative_slope=leaky, inplace=True)
)
def conv_no_bn(inp, oup, stride = 1, leaky = 0):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.LeakyReLU(negative_slope=leaky, inplace=True)
)
def conv_no_bn_no_relu(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
)
def conv_no_bn1X1(inp, oup, stride, leaky=0):
return nn.Sequential(
nn.Conv2d(inp, oup, 1, stride, padding=0, bias=False),
nn.LeakyReLU(negative_slope=leaky, inplace=True)
)
def conv_dw(inp, oup, stride, leaky=0.1):
return nn.Sequential(
nn.Conv2d(inp, inp, 3, stride, 1, groups=int(inp/8), bias=False),
nn.BatchNorm2d(inp),
nn.LeakyReLU(negative_slope= leaky,inplace=True),
nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
nn.BatchNorm2d(oup),
nn.LeakyReLU(negative_slope= leaky,inplace=True),
)
def conv_no_bn_dw(inp, oup, stride, leaky=0.1):
return nn.Sequential(
nn.Conv2d(inp, inp, 3, stride, 1, groups=inp, bias=False),
nn.LeakyReLU(negative_slope= leaky,inplace=True),
nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
nn.LeakyReLU(negative_slope= leaky,inplace=True),
)
class SSH(nn.Module):
def __init__(self, in_channel, out_channel):
super(SSH, self).__init__()
assert out_channel % 4 == 0
leaky = 0
if (out_channel <= 64):
leaky = 0.1
self.conv3X3 = conv_bn_no_relu(in_channel, out_channel//2, stride=1)
self.conv5X5_1 = conv_bn(in_channel, out_channel//4, stride=1, leaky = leaky)
self.conv5X5_2 = conv_bn_no_relu(out_channel//4, out_channel//4, stride=1)
self.conv7X7_2 = conv_bn(out_channel//4, out_channel//4, stride=1, leaky = leaky)
self.conv7x7_3 = conv_bn_no_relu(out_channel//4, out_channel//4, stride=1)
def forward(self, input):
conv3X3 = self.conv3X3(input)
conv5X5_1 = self.conv5X5_1(input)
conv5X5 = self.conv5X5_2(conv5X5_1)
conv7X7_2 = self.conv7X7_2(conv5X5_1)
conv7X7 = self.conv7x7_3(conv7X7_2)
out = torch.cat([conv3X3, conv5X5, conv7X7], dim=1)
out = F.relu(out)
return out
class FPN(nn.Module):
def __init__(self,in_channels_list,out_channels):
super(FPN,self).__init__()
leaky = 0
if (out_channels <= 64):
leaky = 0.1
self.output1 = conv_bn1X1(in_channels_list[0], out_channels, stride = 1, leaky = leaky)
self.output2 = conv_bn1X1(in_channels_list[1], out_channels, stride = 1, leaky = leaky)
self.output3 = conv_bn1X1(in_channels_list[2], out_channels, stride = 1, leaky = leaky)
self.merge1 = conv_bn(out_channels, out_channels, leaky = leaky)
self.merge2 = conv_bn(out_channels, out_channels, leaky = leaky)
def forward(self, input):
# names = list(input.keys())
#input = list(input.values())
output1 = self.output1(input[0])
output2 = self.output2(input[1])
output3 = self.output3(input[2])
up3 = F.interpolate(output3, size=[output2.size(2), output2.size(3)], mode="nearest")
output2 = output2 + up3
output2 = self.merge2(output2)
up2 = F.interpolate(output2, size=[output1.size(2), output1.size(3)], mode="nearest")
output1 = output1 + up2
output1 = self.merge1(output1)
out = [output1, output2, output3]
return out
class MobileNetV1(nn.Module):
def __init__(self):
super(MobileNetV1, self).__init__()
#baseline
#self.stage1_1 = nn.Sequential(
# conv_bn(3, 8, 2, leaky = 0.1), # 3
# conv_dw(8, 16, 2), # 7
# conv_dw(16, 32, 2), # 11
# conv_dw(32, 32, 2), # 19
#)
#self.stage1_2 = nn.Sequential(
# conv_dw(32, 64, 2), # 27
# conv_dw(64, 64, 1), # 43
#)
#self.stage2 = nn.Sequential(
# conv_dw(64, 128, 2), # 43 + 16 = 59
# conv_dw(128, 128, 1), # 59 + 32 = 91
# conv_dw(128, 128, 1), # 91 + 32 = 123
# conv_dw(128, 128, 1), # 123 + 32 = 155
# conv_dw(128, 128, 1), # 155 + 32 = 187
# conv_dw(128, 128, 1), # 187 + 32 = 219
#)
#self.stage3 = nn.Sequential(
# conv_dw(128, 256, 2), # 219 +3 2 = 241
# conv_dw(256, 256, 1), # 241 + 64 = 301
#)
#no stride
self.stage1_1 = nn.Sequential(
conv_bn(3, 16, 2, leaky = 0.1), # 3
conv_dw(16, 32, 2), # 7
conv_dw(32, 64, 2), # 11
conv_dw(64, 64, 1), # 19
)
self.stage1_2 = nn.Sequential(
conv_dw(64, 64, 2)
)
self.stage1_3 = nn.Sequential(
conv_dw(64, 16, 1),
)
self.stage1_s = nn.Sequential(
conv_dw(64, 128, 2)
)
self.stage2_1 = nn.Sequential(
conv_dw(16, 128, 2) # 43 + 16 = 59
)
self.stage2_2 = nn.Sequential(
conv_dw(128, 128, 1), # 59 + 32 = 91
conv_dw(128, 128, 1), # 91 + 32 = 123
conv_dw(128, 128, 1), # 123 + 32 = 155
conv_dw(128, 128, 1)
)
self.stage2_3 = nn.Sequential(
conv_dw(128, 32, 1)
)
self.stage2_s = nn.Sequential(
conv_dw(128, 256, 2)
)
self.stage3_1 = nn.Sequential(
conv_dw(32, 256, 2)
)
self.stage3_2 = nn.Sequential(
conv_dw(256, 64, 1)
)
def forward(self, x):
x1_1 = self.stage1_1(x)
x1_2 = self.stage1_2(x1_1)
x1_3 = self.stage1_3(x1_2)
x1 = F.interpolate(x1_3, size=[x1_1.size(2), x1_1.size(3)], mode="nearest")
x1_s = self.stage1_s(x1_2)
x2_1 = self.stage2_1(x1_3) + x1_s
x2_2 = self.stage2_2(x2_1)
x2_3 = self.stage2_3(x2_2)
x2 = F.interpolate(x2_3, size=[x1_2.size(2), x1_2.size(3)], mode="nearest")
x2_s = self.stage2_s(x2_2)
x3_1 = self.stage3_1(x2_3) + x2_s
x3_2 = self.stage3_2(x3_1)
x3 = F.interpolate(x3_2, size=[x2_2.size(2), x2_2.size(3)], mode="nearest")
return [x1, x2, x3]
#def forward(self, x):
# x1_1 = self.stage1_1(x)
# x1_2 = self.stage1_2(x1_1)
# x2_1 = self.stage2(x1_2)
# x3_1 = self.stage3(x2_1)
#
# return [x1_2, x2_1, x3_1]
class fire(nn.Module):
def __init__(self, inplanes, squeeze_planes, expand_planes, st=1):
super(fire, self).__init__()
self.conv1 = nn.Conv2d(inplanes, squeeze_planes, kernel_size=1, stride=1)
self.relu1 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(squeeze_planes, int(expand_planes/2), kernel_size=1, stride=st)
self.conv3 = nn.Conv2d(squeeze_planes, int(expand_planes/2), kernel_size=3, stride=st, padding=1)
self.relu2 = nn.ReLU(inplace=True)
# using MSR initilization
#for m in self.modules():
# if isinstance(m, nn.Conv2d):
# n = m.kernel_size[0] * m.kernel_size[1] * m.in_channels
# m.weight.data.normal_(0, math.sqrt(2./n))
def forward(self, x):
x = self.conv1(x)
x = self.relu1(x)
out1 = self.conv2(x)
out2 = self.conv3(x)
out = torch.cat([out1, out2], 1)
out = self.relu2(out)
return out
class SqueezeNetV1(nn.Module):
def __init__(self):
super(SqueezeNetV1, self).__init__()
#self.stage1_1 = nn.Sequential(
# conv_no_bn(3, 4, 2, leaky = 0.1),
# fire(4, 8, 8, 2),
# fire(8, 16, 16, 2),
# fire(16, 32, 32, 2),
#)
#self.stage1_2 = nn.Sequential(
# fire(32, 32, 32, 2),
#)
#
#self.stage2 = nn.Sequential(
# fire(32, 32, 64, 2),
# fire(64, 32, 64, 1),
# fire(64, 32, 64, 1),
# fire(64, 32, 64, 1),
#)
#self.stage3 = nn.Sequential(
# fire(64, 64, 128, 2),
# fire(128, 64, 128, 1),
# fire(128, 64, 128, 1),
# fire(128, 64, 128, 1),
#)
#no stride
self.stage1_1 = nn.Sequential(
conv_no_bn(3, 4, 2, leaky = 0.1),
fire(4, 8, 8, 2),
fire(8, 16, 16, 2),
)
self.stage1_2 = nn.Sequential(
fire(16, 32, 32, 2),
fire(32, 32, 32, 1),
)
self.stage2 = nn.Sequential(
fire(32, 32, 64, 2),
fire(64, 32, 64, 1),
fire(64, 32, 64, 1),
fire(64, 32, 64, 1),
)
self.stage3 = nn.Sequential(
fire(64, 64, 128, 2),
fire(128, 64, 128, 1),
fire(128, 64, 128, 1),
fire(128, 64, 128, 1),
)
def forward(self, x):
x1_1 = self.stage1_1(x)
x1_2 = self.stage1_2(x1_1)
x1 = F.interpolate(x1_2, size=[x1_1.size(2), x1_1.size(3)], mode="nearest")
x2_1 = self.stage2(x1_2)
x2 = F.interpolate(x2_1, size=[x1_2.size(2), x1_2.size(3)], mode="nearest")
x3_1 = self.stage3(x2_1)
x3 = F.interpolate(x3_1, size=[x2_1.size(2), x2_1.size(3)], mode="nearest")
return [x1, x2, x3]
#def forward(self, x):
# x1_1 = self.stage1_1(x)
# x1_2 = self.stage1_2(x1_1)
# #x1 = F.interpolate(x1_2, size=[x1_1.size(2), x1_1.size(3)], mode="nearest")
#
# x2_1 = self.stage2(x1_2)
# #x2 = F.interpolate(x2_1, size=[x1_2.size(2), x1_2.size(3)], mode="nearest")
#
# x3_1 = self.stage3(x2_1)
# #x3 = F.interpolate(x3_1, size=[x2_1.size(2), x2_1.size(3)], mode="nearest")
#
# return [x1_2, x2_1, x3_1]
class SqueezeNet(nn.Module):
def __init__(self):
super(SqueezeNet, self).__init__()
#baseline
#self.stage1_1 = nn.Sequential(
# conv_no_bn(3, 4, 2, leaky = 0.1),
# fire(4, 8, 8, 2),
# fire(8, 16, 16, 2)
#)
#self.stage1_2 = nn.Sequential(
# fire(16, 32, 32, 2)
#)
#self.stage1_3 = nn.Sequential(
# fire(32, 32, 32, 2)
#)
#
#self.stage2 = nn.Sequential(
# fire(32, 32, 64, 2),
# fire(64, 32, 64, 1),
# fire(64, 32, 64, 1),
# fire(64, 32, 64, 1)
#)
#self.stage3 = nn.Sequential(
# fire(64, 64, 128, 2),
# fire(128, 64, 128, 1),
# fire(128, 64, 128, 1),
# fire(128, 64, 128, 1)
#)
#half
#self.stage1_1 = nn.Sequential(
# conv_no_bn(3, 4, 2, leaky = 0.1),
# fire(4, 8, 8, 2),
# fire(8, 8, 8, 2)
#)
#self.stage1_2 = nn.Sequential(
# fire(8, 16, 16, 2)
#)
#self.stage1_3 = nn.Sequential(
# fire(16, 16, 16, 2)
#)
#
#self.stage2 = nn.Sequential(
# fire(16, 16, 32, 2),
# fire(32, 16, 32, 1),
# fire(32, 16, 32, 1),
# fire(32, 16, 32, 1)
#)
#self.stage3 = nn.Sequential(
# fire(32, 32, 64, 2),
# fire(64, 32, 64, 1),
# fire(64, 32, 64, 1),
# fire(64, 32, 64, 1)
#)
#double
self.stage1_1 = nn.Sequential(
conv_no_bn(3, 8, 2, leaky = 0.1),
fire(8, 16, 16, 2),
fire(16, 16, 32, 2)
)
self.stage1_2 = nn.Sequential(
fire(32, 32, 64, 2)
)
self.stage1_3 = nn.Sequential(
fire(64, 32, 64, 2)
)
self.stage2 = nn.Sequential(
fire(64, 64, 128, 2),
fire(128, 64, 128, 1),
fire(128, 64, 128, 1),
fire(128, 64, 128, 1)
)
self.stage3 = nn.Sequential(
fire(128, 128, 256, 2),
fire(256, 128, 256, 1),
fire(256, 128, 256, 1),
fire(256, 128, 256, 1)
)
def forward(self, x):
x1_1 = self.stage1_1(x)
x1_2 = self.stage1_2(x1_1)
x1_3 = self.stage1_3(x1_2)
x1 = F.interpolate(x1_3, size=[x1_2.size(2), x1_2.size(3)], mode="nearest")
x2_1 = self.stage2(x1_3)
x2 = F.interpolate(x2_1, size=[x1_3.size(2), x1_3.size(3)], mode="nearest")
x3_1 = self.stage3(x2_1)
x3 = F.interpolate(x3_1, size=[x2_1.size(2), x2_1.size(3)], mode="nearest")
return [x1, x2, x3, x1_1] |
986,736 | b703c85a1afed0f0288bbed29cbb84790280271f | # Generated by Django 2.1.7 on 2019-05-13 17:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20190425_1524'),
]
operations = [
migrations.AlterField(
model_name='user',
name='netid',
field=models.CharField(default='', max_length=15, null=True),
),
]
|
986,737 | 831172ace842dbc507e2036e88ac66a9f39e8fe9 | import uuid
from django.db.models import UUIDField
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
"""Extended user model, replacing 'id' with a uuid field
which is going to be used in cassandra.
"""
id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
986,738 | 2d63221b7ff267f284ae050b70ab3d586f32d7e6 | from FirstCharacter import *
class Startingworld:
location = "Starting World" # Data type:Sring
#init all the variables
def __init__(self,player):
self.playerinworld = player
self.FirstCharacter = FirstCharacter(self.playerinworld)
#retuns the name of the location
def loction(self):
return self.location
#Starts talking with one of the characters in the world
def SFirstCharacter(self):
self.FirstCharacter.introdialog()
|
986,739 | bb994e5fc4f13d9facf087e48b9762b9efc9844d | from typing import Dict, List
def foo(param: Dict[str, List]) -> str:
return 'Hello, world!'
x: Dict[str, str] = dict(foo='bar', baz='qux')
print(foo(x))
|
986,740 | 42aa2de1ed96d9eb01c607807ae4acfab7a9c294 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 25 13:15:45 2017
@author: sinlight
"""
#import pandas as pd
def prepro(dfrom) : #传入原始数据框
"对数据框进行预处理对数据框内容进行预处理,去掉多余的空格,方便以后匹配"
for i in range(0,len(dfrom.index)):
for j in range(0,len(dfrom.columns)):
if isinstance(dfrom.iat[i,j], str):
dfrom.iat[i,j] = dfrom.iat[i,j].strip()
return dfrom
|
986,741 | 6ad98dfa4c4e49b5b1897a7b3c703a70f46d810e | # Generated by Django 3.2 on 2021-05-11 13:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('videos', '0013_auto_20210511_1126'),
]
operations = [
migrations.RemoveField(
model_name='playlist',
name='titile',
),
migrations.AddField(
model_name='playlist',
name='title',
field=models.CharField(max_length=50, null=True),
),
]
|
986,742 | a6ad2ed4c355d0a920c14e72cbd96570c30344a5 | import os
import unittest
import finite.pflow
from finite.storage.factom import Storage
class OctoeTestCase(unittest.TestCase):
def setUp(self):
finite.pflow.set_provider(Storage)
self.xmlfile = os.path.dirname(os.path.abspath(__file__)
) + "/../examples/octoe.pflow"
def tearDown(self):
pass
def test_load_subnets(self):
flow, err = finite.pflow.load_file(self.xmlfile)
self.assertIsNone(err)
m = flow.to_module()
self.assertEqual(m.Machine.__class__, type)
# print(flow)
if __name__ == '__main__':
unittest.main()
|
986,743 | dcffa2c04b70390b02feca682bce27431f1478c0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import template
from django_hosts.reverse import reverse_full
from v3d_libs.utils.http import encode_link
register = template.Library()
class ELinkNode(template.Node):
def __init__(self, parser, token):
bits = token.split_contents()
if len(bits) != 3:
raise template.TemplateSyntaxError("%r tag requires exactly 3 arguments" % bits[0])
self.link = parser.compile_filter(bits[1])
self.title = parser.compile_filter(bits[2])
def render(self, context):
link = self.link.resolve(context)
title = self.title.resolve(context)
url = reverse_full('redirect', 'redirect', (), {}, (encode_link(link),))
return '<a href="%s" title="%s" target="_blank" rel="nofollow">%s</a>' % (url, title, title)
@register.tag
def elink(parser, token):
return ELinkNode(parser, token)
@register.filter
def redirect(link):
return reverse_full('redirect', 'redirect', (), {}, (encode_link(link),))
|
986,744 | 4216c303860020d95756a5e7b450cdc0e085a901 | # **************************************************************************** #
# LE - / #
# / #
# display.py .:: .:/ . .:: #
# +:+:+ +: +: +:+:+ #
# By: vico <vico@student.le-101.fr> +:+ +: +: +:+ #
# #+# #+ #+ #+# #
# Created: 2019/10/31 18:13:21 by vico #+# ## ## #+# #
# Updated: 2019/11/07 17:11:15 by vico ### #+. /#+ ###.fr #
# / #
# / #
# **************************************************************************** #
#!/usr/bin/env python3
def add_operators(factors):
nf = []
nf.append(factors[0])
for f in factors[1:]:
if f[0] == '-':
nf.append(' - ' + f[1:])
else:
nf.append(' + ' + f[0:])
return (nf)
def print_reduced(factors):
if len(factors) == 0:
print ("Reduced form: 0 = 0 ; all real numbers are a solution")
return (0)
factors = [f[:-2] if f.endswith('.0') else f for f in map(str, factors)]
display_factors = add_operators(factors)
print("Reduced form: ", end='')
for idx, f in enumerate(display_factors):
print(f + ' * x^' + str(idx), end ='')
print(' = 0')
print('Polynomial degree:', len(factors) - 1)
if len(factors) - 1 > 2:
print("The polynomial degree is strictly greater than 2, I can't solve")
return (0)
return (1)
|
986,745 | 9d077cc8f1d509f7985aa8e672ac8db83e642b9e | # Program to run Newton Interpolation to specified polynomial degree
import numpy as np
import matplotlib.pyplot as plt
import json
import pandas as pd
# Create the Newton Interpolation 'fdd' Method
def newtInt(x,y):
fdd = np.zeros((len(x),len(x)))
print('the fdd array is: \n',fdd)
for i in range(len(x)):
fdd[i][0] = y[i]
for j in range(1,len(x)):
for i in range(len(x)-(j)):
print('\n(',j,') and (',i,')')
fdd[i][j] = ((fdd[i+1][j-1]-fdd[i][j-1])/(x[i+j]-x[i]))
print(fdd)
return fdd
# Create the Newton Interpolation 'y_eval' Method
def yval(x,fdd,x_eval):
xtemp = 1
y_eval = fdd[0][0]
for m in range(1,len(x)):
xtemp = xtemp * (x_eval- (x[m-1]))
y_eval = y_eval + (fdd[0][m] *xtemp)
return y_eval
# Internal data Function
def routine_Internal():
#x = [1,4,6,5]
#y = [7,52,112,79]
#x = [0,4,11,18,22]
#y = [0,3,2.5,1,0]
#x = [0,.0001,.00342,.01072,.02185,.03668,.05506,.07682,.10175]
#y = [0,.00239,.01552,.02949,.04371,.05773,.07116,.0836,.09455]
#x = [0,2,5,8,10,13]
#y = [0,4,28.75,76,120,204.75]
x = [0,1,3,5,8,12,21]
y = [0,3,6,8,10,11,12]
return (x,y)
# External Data Function
def routine_External():
filename = 'Eppler_data_TOP.xlsx'
path = '/home/dallin/Documents/Horizon/Geometry+Design/'
fullpath = path + filename
df = pd.read_excel(fullpath)
arr = df.to_numpy()
x = []
y = []
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
if j == 0:
x.append(arr[i][j])
else:
y.append(arr[i][j])
return (x,y)
# Create the Plotter Function
def plotter(x_points,y_points,x,y):
fig = plt.figure()
ax = fig.add_subplot(111)
#ax.set_aspect('equal')
plt.plot(x_points,y_points, label = 'Interp line',color = 'blue')
plt.scatter(x,y,color = 'red')
plt.show()
# Main Routine
def main():
data = str(input("Internal or External Data? "))
if data == 'i':
(x,y) = routine_Internal()
else:
(x,y) = routine_External()
fdd = newtInt(x,y)
res = 1000
x_points = []
y_points = []
step = (x[len(x)-1] - x[0]) /res
for i in range(res+1):
x_points.append(x[0]+(step*i))
for i in range(len(x_points)):
y_points.append(yval(x,fdd,x_points[i]))
plotter(x_points,y_points,x,y)
main()
|
986,746 | 0a3347deda8779e4c840ab740b47df6fdc215978 | import sys
import os
import copy
from itertools import groupby
from operator import mul
import marshal
# Score multipliers
BOARD_SZ = 15
(NORM, DL, TL, DW, TW) = (1, 2, 3, 4, 5)
POINT_VALS = {'a' : 1, 'b' : 4, 'c' : 4, 'd' : 2, 'e' : 1, 'f' : 4, 'g' : 3, 'h' : 3, 'i' : 1, \
'j' : 10, 'k' : 5, 'l' : 2, 'm' : 4, 'n' : 2, 'o' : 1, 'p' : 4, 'q' : 10, 'r' : 1, \
's' : 1, 't' : 1, 'u' : 2, 'v' : 5, 'w' : 4, 'x' : 8, 'y' : 3, 'z' : 10, '*' : 0}
midstring_prefix_letters = {}
startstring_suffix_letters = {}
valid_words = set()
DICT_FILE = "dict.txt"
VALID_WORDS_FILE = "valid_words.p"
STARTSTRING_SUFFIX_LETTERS_FILE = "startstring_suffix_letters.p"
MIDSTRING_PREFIX_LETTERS_FILE = "midstring_prefix_letters.p"
######################################################################
# AUX DATA STUFF
######################################################################
def add_startstring_suffix_letter(substring, letter):
if substring not in startstring_suffix_letters:
startstring_suffix_letters[substring] = set()
startstring_suffix_letters[substring].add(letter)
def add_midstring_prefix_letter(substring, letter):
if substring not in midstring_prefix_letters:
midstring_prefix_letters[substring] = set()
midstring_prefix_letters[substring].add(letter)
def add_aux_data(word):
for i in range(len(word)):
for j in range(i+1, len(word)+1):
substring = word[i:j]
if i == 0 and j == len(word):
valid_words.add(substring)
if i == 0 and j != len(word):
add_startstring_suffix_letter(substring, word[j])
if i != 0:
add_midstring_prefix_letter(substring, word[i-1])
def init_aux_data():
global startstring_suffix_letters, midstring_prefix_letters, valid_words
if not os.path.exists(VALID_WORDS_FILE) or \
not os.path.exists(STARTSTRING_SUFFIX_LETTERS_FILE) or \
not os.path.exists(MIDSTRING_PREFIX_LETTERS_FILE):
print("Computing aux data...")
d = open(DICT_FILE, "r")
for line in d:
line = line.strip()
add_aux_data(line)
midstring_prefix_letters[""] = set("abcdefghijklmnopqrstuvwxyz")
startstring_suffix_letters[""] = set("abcdefghijklmnopqrstuvwxyz")
marshal.dump(valid_words, open(VALID_WORDS_FILE, "wb"))
marshal.dump(startstring_suffix_letters, open(STARTSTRING_SUFFIX_LETTERS_FILE, "wb"))
marshal.dump(midstring_prefix_letters, open(MIDSTRING_PREFIX_LETTERS_FILE, "wb"))
else:
print("Loading aux data from files...")
valid_words = marshal.load(open(VALID_WORDS_FILE, "rb"))
startstring_suffix_letters = marshal.load(open(STARTSTRING_SUFFIX_LETTERS_FILE, "rb"))
midstring_prefix_letters = marshal.load(open(MIDSTRING_PREFIX_LETTERS_FILE, "rb"))
init_aux_data()
######################################################################
# SCRABBLE LETTER CLASS
######################################################################
class Letter:
def __init__(self, character, x, y, wildcard=False):
self.character = character
self.x, self.y = x, y
self.is_wildcard = wildcard
self.point_value = POINT_VALS[character] * int(not self.is_wildcard)
def __copy__(self):
return Letter(self.character, self.x, self.y, self.is_wildcard)
def __eq__(self, other):
return self.character == other.character and \
self.x == other.x and \
self.y == other.y
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return self.character
def __str__(self):
return self.character
def details(self):
detail = self.character + " x:" + str(self.y+1) + " y:" + str(self.x+1) + \
" pt-val:" + str(self.point_value)
if self.is_wildcard:
detail += " wildcard=True"
return detail
######################################################################
# IO
######################################################################
def get_scrabble_char(char):
if char == '0':
return ' '
if char == '*':
return '*'
return char.lower()
def read_board(board_file_path, op=get_scrabble_char):
board_file = open(board_file_path, "r")
board = []
for line in board_file:
board.append([op(x) for x in list(line.strip())])
board_file.close()
return board
def read_board_config(board_config_file_path):
return read_board(board_config_file_path, lambda x: int(x))
def read_hand(scrabble_hand_file_path):
f = open(scrabble_hand_file_path, "r")
return_value = [get_scrabble_char(x) for x in list(f.readline().strip())]
f.close()
return return_value
######################################################################
# MISC
######################################################################
def update_score_multipliers(board, config):
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] != ' ':
config[i][j] = NORM
######################################################################
# SEARCH
######################################################################
def generate_word_candidates(board, config, hand):
board_letters = accumulate_board_letters(board)
hand_letters = accumulate_hand_letters(hand)
print("-Generating possible words...")
possible_words = generate_possible_words(board, board_letters, hand_letters)
print("-Scoring words...")
word_score_pairings = [(x, score(board, config, x)) for x in possible_words]
sorted_score_pairings = sorted(word_score_pairings, key=lambda x: x[1], reverse=True)
unique_sorted_score_pairings = [k for k,v in groupby(sorted_score_pairings)]
return unique_sorted_score_pairings
def accumulate_board_letters(board):
letters = []
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] != ' ':
letters.append(Letter(board[i][j], i, j))
return letters
def accumulate_hand_letters(hand):
letters = []
for letter in hand:
letters.append(Letter(letter, -1, -1, wildcard=letter == '*'))
return letters
def generate_possible_words(board, board_letters, hand_letters):
anchor_positions = get_anchor_positions(board_letters, board)
if len(anchor_positions) == 0:
anchor_positions.add((7, 7))
possible_words = []
vertical_cross_section = generate_vertical_cross_section(hand_letters, board_letters, board)
horizontal_cross_section = generate_horizontal_cross_section(hand_letters, board_letters, board)
for anchor_pos in anchor_positions:
possible_words += \
generate_horizontal_words(board, hand_letters, anchor_pos, anchor_positions,
vertical_cross_section)
possible_words += \
generate_vertical_words(board, hand_letters, anchor_pos, anchor_positions,
horizontal_cross_section)
return possible_words
def get_anchor_positions(board_letters, board):
anchor_positions = set()
for letter in board_letters:
x, y = letter.x, letter.y
if x+1 < BOARD_SZ and board[x+1][y] == ' ':
anchor_positions.add((x+1, y))
if x-1 >= 0 and board[x-1][y] == ' ':
anchor_positions.add((x-1, y))
if y+1 < BOARD_SZ and board[x][y+1] == ' ':
anchor_positions.add((x, y+1))
if y-1 >= 0 and board[x][y-1] == ' ':
anchor_positions.add((x, y-1))
return anchor_positions
def get_num_non_anchor_pos(dirx, diry, x, y, all_anchor_pos, board):
assert(dirx <= 0 and diry <= 0)
x, y, k = x+dirx, y+diry, 0
while x >= 0 and y >= 0:
if (x, y) in all_anchor_pos or board[x][y] != ' ':
return k
x, y, k = x+dirx, y+diry, k+1
return k
def generate_vertical_cross_section(hand_letters, board_letters, board):
hand_set = set("abcdefghijklmnopqrstuvwxyz")
cross_section = [[None for x in range(BOARD_SZ)] for y in range(BOARD_SZ)]
for board_letter in board_letters:
board_character, x, y = board_letter.character, board_letter.x, board_letter.y
for hand_character in hand_set:
if y < BOARD_SZ-1:
if cross_section[x][y+1] == None:
cross_section[x][y+1] = set()
placed_letter = Letter(hand_character, x, y+1)
whole_seq = get_whole_vertical_word(board, [placed_letter])
if "".join(c.character for c in whole_seq) in valid_words:
cross_section[x][y+1].add(hand_character)
if y > 0:
if cross_section[x][y-1] == None:
cross_section[x][y-1] = set()
placed_letter = Letter(hand_character, x, y-1)
whole_seq = get_whole_vertical_word(board, [placed_letter])
if "".join(c.character for c in whole_seq) in valid_words:
cross_section[x][y-1].add(hand_character)
for i in range(BOARD_SZ):
for j in range(BOARD_SZ):
if cross_section[i][j] == None:
cross_section[i][j] = hand_set
return cross_section
def generate_horizontal_cross_section(hand_letters, board_letters, board):
hand_set = set("abcdefghijklmnopqrstuvwxyz")
cross_section = [[None for x in range(BOARD_SZ)] for y in range(BOARD_SZ)]
for board_letter in board_letters:
board_character, x, y = board_letter.character, board_letter.x, board_letter.y
for hand_character in hand_set:
if x < BOARD_SZ-1:
if cross_section[x+1][y] == None:
cross_section[x+1][y] = set()
placed_letter = Letter(hand_character, x+1, y)
whole_seq = get_whole_horizontal_word(board, [placed_letter])
if "".join(c.character for c in whole_seq) in valid_words:
cross_section[x+1][y].add(hand_character)
if x > 0:
if cross_section[x-1][y] == None:
cross_section[x-1][y] = set()
placed_letter = Letter(hand_character, x-1, y)
whole_seq = get_whole_horizontal_word(board, [placed_letter])
if "".join(c.character for c in whole_seq) in valid_words:
cross_section[x-1][y].add(hand_character)
for i in range(BOARD_SZ):
for j in range(BOARD_SZ):
if cross_section[i][j] == None:
cross_section[i][j] = hand_set
return cross_section
def generate_horizontal_words(board, hand, cur_anchor_pos, all_anchor_pos, cross_section):
anchor_x, anchor_y = cur_anchor_pos[0], cur_anchor_pos[1]
k = get_num_non_anchor_pos(-1, 0, anchor_x, anchor_y, all_anchor_pos, board)
generated_valid_words = []
def add_legal_move(seq):
generated_valid_words.append(seq)
def extend_right(cur_seq, (x, y), board, hand, did_place_letter=False):
cur_string = "".join([letter.character for letter in cur_seq])
if x >= BOARD_SZ:
if cur_string in valid_words and did_place_letter:
add_legal_move(cur_seq)
return
if board[x][y] == ' ':
if cur_string in valid_words and did_place_letter:
add_legal_move(cur_seq)
for i, letter in enumerate(hand):
if letter.is_wildcard:
wildcard_candidate_chars = \
startstring_suffix_letters.get(cur_string, set()).intersection(cross_section[x][y])
for wildcard in wildcard_candidate_chars:
remaining_hand = hand[:i] + hand[i+1:]
extend_right(cur_seq+[Letter(wildcard, x, y, wildcard=True)],
(x+1, y), board, remaining_hand, True)
else:
if letter.character in startstring_suffix_letters.get(cur_string, []) and \
letter.character in cross_section[x][y]:
remaining_hand = hand[:i] + hand[i+1:]
extend_right(cur_seq+[Letter(letter.character, x, y)],
(x+1, y), board, remaining_hand, True)
else:
if board[x][y] in startstring_suffix_letters.get(cur_string, []):
extend_right(cur_seq+[Letter(board[x][y], x, y)],
(x+1, y), board, hand, did_place_letter)
def extend_left(cur_seq, (x, y), board, hand, limit, did_place_letter=False):
cur_string = "".join([letter.character for letter in cur_seq])
if cur_string in startstring_suffix_letters:
extend_right(cur_seq, (x+len(cur_seq)+int(did_place_letter), y),
board, hand, did_place_letter)
if limit > 0:
for i, letter in enumerate(hand):
if letter.is_wildcard:
wildcard_candidate_chars = \
midstring_prefix_letters.get(cur_string, set()).intersection(cross_section[x][y])
for wildcard in wildcard_candidate_chars:
remaining_hand = hand[:i] + hand[i+1:]
board[x][y] = wildcard
extend_left([Letter(wildcard, x, y, wildcard=True)]+cur_seq,
(x-1, y), board, remaining_hand, limit-1, True)
board[x][y] = ' '
else:
if letter.character in midstring_prefix_letters.get(cur_string, []) and \
letter.character in cross_section[x][y]:
remaining_hand = hand[:i] + hand[i+1:]
board[x][y] = letter.character
extend_left([Letter(letter.character, x, y)]+cur_seq,
(x-1, y), board, remaining_hand, limit-1, True)
board[x][y] = ' '
if k == 0 and anchor_x-1 >= 0:
while anchor_x > 0 and board[anchor_x-1][anchor_y] != ' ':
anchor_x -= 1
extend_right([], (anchor_x, anchor_y), board, hand)
else:
extend_left([], cur_anchor_pos, board, hand, k)
return generated_valid_words
def generate_vertical_words(board, hand, cur_anchor_pos, all_anchor_pos, cross_section):
anchor_x, anchor_y = cur_anchor_pos[0], cur_anchor_pos[1]
k = get_num_non_anchor_pos(0, -1, anchor_x, anchor_y, all_anchor_pos, board)
generated_valid_words = []
def add_legal_move(seq):
generated_valid_words.append(seq)
def extend_down(cur_seq, (x, y), board, hand, did_place_letter=False):
cur_string = "".join([letter.character for letter in cur_seq])
if y >= BOARD_SZ:
if cur_string in valid_words and did_place_letter:
add_legal_move(cur_seq)
return
if board[x][y] == ' ':
if cur_string in valid_words and did_place_letter:
add_legal_move(cur_seq)
for i, letter in enumerate(hand):
if letter.is_wildcard:
wildcard_candidate_chars = \
startstring_suffix_letters.get(cur_string, set()).intersection(cross_section[x][y])
for wildcard in wildcard_candidate_chars:
remaining_hand = hand[:i] + hand[i+1:]
extend_down(cur_seq+[Letter(wildcard, x, y, wildcard=True)],
(x, y+1), board, remaining_hand, True)
else:
if letter.character in startstring_suffix_letters.get(cur_string, []) and \
letter.character in cross_section[x][y]:
remaining_hand = hand[:i] + hand[i+1:]
extend_down(cur_seq+[Letter(letter.character, x, y)],
(x, y+1), board, remaining_hand, True)
else:
if board[x][y] in startstring_suffix_letters.get(cur_string, []):
extend_down(cur_seq+[Letter(board[x][y], x, y)],
(x, y+1), board, hand, did_place_letter)
def extend_up(cur_seq, (x, y), board, hand, limit, did_place_letter=False):
cur_string = "".join([letter.character for letter in cur_seq])
if cur_string in startstring_suffix_letters:
extend_down(cur_seq, (x, y+len(cur_seq)+int(did_place_letter)),
board, hand, did_place_letter)
if limit > 0:
for i, letter in enumerate(hand):
if letter.is_wildcard:
wildcard_candidate_chars = \
midstring_prefix_letters.get(cur_string, set()).intersection(cross_section[x][y])
for wildcard in wildcard_candidate_chars:
remaining_hand = hand[:i] + hand[i+1:]
board[x][y] = wildcard
extend_up([Letter(wildcard, x, y, wildcard=True)]+cur_seq,
(x, y-1), board, remaining_hand, limit-1, True)
board[x][y] = ' '
else:
if letter.character in midstring_prefix_letters.get(cur_string, []) and \
letter.character in cross_section[x][y]:
remaining_hand = hand[:i] + hand[i+1:]
board[x][y] = letter.character
extend_up([Letter(letter.character, x, y)]+cur_seq,
(x, y-1), board, remaining_hand, limit-1, True)
board[x][y] = ' '
if k == 0 and anchor_y-1 >= 0:
while anchor_y > 0 and board[anchor_x][anchor_y-1] != ' ':
anchor_y -= 1
extend_down([], (anchor_x, anchor_y), board, hand)
else:
extend_up([], cur_anchor_pos, board, hand, k)
return generated_valid_words
def get_whole_horizontal_word(board, word):
left_x, right_x, y, offset = word[0].x, word[-1].x, word[0].y, 0
while left_x > 0 and board[left_x-1][y] != ' ':
offset -= 1
left_x -= 1
while right_x < BOARD_SZ-1 and board[right_x+1][y] != ' ':
right_x += 1
horizontal_word = []
for index, i in enumerate(range(left_x, right_x+1)):
if board[i][y] != ' ':
horizontal_word.append(Letter(board[i][y], i, y))
else:
horizontal_word.append(copy.copy(word[offset+index]))
return horizontal_word
def get_whole_vertical_word(board, word):
top_y, bottom_y, x, offset = word[0].y, word[-1].y, word[0].x, 0
while top_y > 0 and board[x][top_y-1] != ' ':
offset -= 1
top_y -= 1
while bottom_y < BOARD_SZ-1 and board[x][bottom_y+1] != ' ':
bottom_y += 1
vertical_word = []
for index, i in enumerate(range(top_y, bottom_y+1)):
if board[x][i] != ' ':
vertical_word.append(Letter(board[x][i], x, i))
else:
vertical_word.append(copy.copy(word[offset+index]))
return vertical_word
def get_all_newly_formed_seq(board, word):
x_disp, y_disp = word[0].x-word[-1].x, word[0].y-word[-1].y
is_vertical_word, is_horizontal_word = y_disp != 0, x_disp != 0
assert((is_vertical_word ^ is_horizontal_word) == 1)
newly_formed_seqs = []
if is_vertical_word:
newly_formed_seqs.append(get_whole_vertical_word(board, word))
for letter in word:
x, y = letter.x, letter.y
if board[x][y] == ' ':
newly_formed_seqs.append(get_whole_horizontal_word(board, [letter]))
elif is_horizontal_word:
newly_formed_seqs.append(get_whole_horizontal_word(board, word))
for letter in word:
x, y = letter.x, letter.y
if board[x][y] == ' ':
newly_formed_seqs.append(get_whole_vertical_word(board, [letter]))
return [x for x in newly_formed_seqs if len(x) > 1]
def causes_other_invalid_words(board, word):
for seqs in get_all_newly_formed_seq(board, word):
cur_seq_str = "".join([str(x) for x in seqs])
if cur_seq_str not in valid_words:
return True
return False
def score_individual_word(board, config, word):
multipliers = []
base_score = 0
n_hand_words_used = 0
for letter in word:
x, y = letter.x, letter.y
letter_base_points = letter.point_value
if config[x][y] == DW:
multipliers.append(2)
if config[x][y] == TW:
multipliers.append(3)
if config[x][y] == DL:
letter_base_points *= 2
if config[x][y] == TL:
letter_base_points *= 3
base_score += letter_base_points
n_hand_words_used += int(board[x][y] == ' ')
return reduce(mul, multipliers, 1) * base_score + int(n_hand_words_used == 7) * 35
def score(board, config, word):
total_score = 0
for seq in get_all_newly_formed_seq(board, word):
assert("".join([str(x) for x in seq]) in valid_words)
total_score += score_individual_word(board, config, seq)
return total_score
######################################################################
# DEBUG/PRINTS/HELPERS
######################################################################
def print_word_candidate(word_candidate):
print("Score: " + str(word_candidate[1]))
for detail in [x.details() for x in word_candidate[0]]:
print(detail)
print('--------------------------------------------------------------')
print("All newly formed words:")
formed_seqs = get_all_newly_formed_seq(board, word_candidate[0])
for seq in formed_seqs:
print("".join([str(x) for x in seq]))
print('--------------------------------------------------------------')
def candidate_contains_wildcard(word_candidate):
for letter in word_candidate:
if letter.is_wildcard:
return True
return False
if __name__ == "__main__":
board = read_board("scrabble_board.txt")
config = read_board_config("scrabble_board_config.txt")
hand = read_hand("scrabble_hand.txt")
update_score_multipliers(board, config)
word_candidates = generate_word_candidates(board, config, hand)
if len(word_candidates) == 0:
print("No possible words can be made.")
sys.exit(0)
print('--------------------------------------------------------------')
print(word_candidates[:50])
print('--------------------------------------------------------------')
top_candidate_no_wildcard = None
top_candidate = word_candidates[0]
for word_candidate in word_candidates:
if not candidate_contains_wildcard(word_candidate[0]):
top_candidate_no_wildcard = word_candidate
break
if top_candidate_no_wildcard != top_candidate:
print_word_candidate(top_candidate_no_wildcard)
print_word_candidate(top_candidate)
|
986,747 | bdb3498493e36e6899bda030b98f0190d86cfdd1 | from django.apps import AppConfig
class PostServiceAppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'PostServiceApp'
|
986,748 | b34d9c24f4b119d16aafaba905ef414dd071ccc2 | #! pyton 3
# regex_strip.py
"""
This program takes a string and does what strip() does.
We use the first argument as the string to be passed and the second argument as the characters to be removed.
If the second argument is left empty, whitespace characters are removed from the beginning and end of the string.
"""
import re
def strip_2(string1,optional=''):
if optional == '':
funct_regex = re.compile(r'^(\s*)(\S*)(\s*$)') # Starts with 0 or more whitespace characters,
# is followed by 0 or more non-whitespace characters,
# Ends with 0 or more whitespace charcaters.
mo = funct_regex.search(string1)
print(mo.group(2))
else:
funct_regex = re.compile(optional)
for_print = funct_regex.sub('',string1)
print(for_print)
while True:
text = input('Enter the string you want parsed: ')
optional = input('Enter the text you want replaced (leave blank/press enter if you want to replace whitespace): ')
strip_2(text,optional)
while True:
run_again = str(input('Enter \'y\' to try again. Press any other key to exit \n' ))
if run_again == 'y':
break
print('Program will exit now.')
break
if run_again == 'y':
continue
else:
break
|
986,749 | fbad53bb96670630384900d412c4e27b4ef4ca87 | from threading import *
from xmllib import XMLParser
from ExpatXMLParser import ExpatXMLParser, DOMNode
from os import path
import gtk
from gtk import *
from gtk.glade import *
import string
from cue import Cue
from omniORB import CORBA
import CosNaming
from idl import LB, LB__POA
crossfader_open_menu=None
def action_crossfader_load(args):
xf = lb.crossfader[args['crossfader']]
if xf.isRunning():
xf.stop()
old_cue = xf.getUpCueName()
if (old_cue and lb.cue.has_key(old_cue)):
cue1=lb.cue[old_cue]
else:
old_cue = xf.getDownCueName()
if (old_cue and lb.cue.has_key(old_cue)):
cue1=lb.cue[old_cue]
else:
cue1=Cue("")
cue2=lb.cue[args['cue']]
xf.setCues (cue1, cue2)
xf.setLevel(0.0)
def action_crossfader_run(args):
xf = lb.crossfader[args['crossfader']]
uptime=lb.value_to_core('time', args.get('uptime', 0))
downtime=lb.value_to_core('time', args.get('downtime', 0))
xf.setTimes(uptime, downtime)
if (downtime>uptime): intime=downtime
else: intime=uptime
intime=args.get('time', intime)
xf.run(100.0, intime)
def get_cue_keys():
l = lb.cue.keys()
l.sort()
return l
def get_crossfader_keys():
l = lb.crossfader.keys()
l.sort()
return l
def initialize():
reset()
lb.program_action_type['crossfader_load'] = (
action_crossfader_load,
(('crossfader', get_crossfader_keys),
('cue', get_cue_keys)))
lb.program_action_type['crossfader_run'] = (
action_crossfader_run,
(('crossfader', get_crossfader_keys),
('uptime', ''),
('downtime', '')))
def reset():
global crossfader_open_menu
lb.crossfader={}
gdk.threads_enter()
for m in lb.fader_menu.get_children():
if (m.get_children()[0].get() == "Crossfader"):
lb.fader_menu.remove(m)
crossfader1=gtk.MenuItem("Crossfader")
lb.fader_menu.append(crossfader1)
crossfader_menu=gtk.Menu()
crossfader1.set_submenu(crossfader_menu)
open1=gtk.MenuItem("Open")
crossfader_menu.append(open1)
crossfader_open_menu=gtk.Menu()
open1.set_submenu(crossfader_open_menu)
new1=gtk.MenuItem("New")
new1.connect("activate", newCrossFader_cb, None)
crossfader_menu.append(new1)
lb.menubar.show_all()
gdk.threads_leave()
def shutdown():
pass
def load(tree):
for section in tree.find("crossfaders"):
for xf in section.find("crossfader"):
c = CrossFader (xf.attrs['name'], xf.attrs['core'])
def save():
tree = DOMNode('crossfaders')
for i in lb.crossfader.values():
tree.append(i.to_tree())
return tree
class crossFaderFactory:
def __init__(self):
gdk.threads_enter()
try:
wTree = glade.XML ("gtklb.glade",
"newCoreItem")
dic = {"on_ok_clicked": self.ok_clicked,
"on_cancel_clicked": self.cancel_clicked}
wTree.signal_autoconnect (dic)
e=wTree.get_widget ("nameEntry")
coreMenu=wTree.get_widget ("coreMenu")
menu=gtk.Menu()
coreMenu.set_menu(menu)
lb.check_cores()
for n in lb.core_names:
i=gtk.MenuItem(n)
i.show()
menu.append(i)
coreMenu.set_history(0)
menu.show()
self.tree=wTree
finally:
gdk.threads_leave()
def ok_clicked(self, widget, data=None):
w = self.tree.get_widget("newCoreItem")
e = self.tree.get_widget("nameEntry")
name = e.get_text()
if (string.strip(name) != ''):
o = self.tree.get_widget("coreMenu")
corename = o.get_children()[0].get()
if not lb.crossfader.has_key(name):
gdk.threads_leave()
c = CrossFader(name, corename)
c.send_update()
gdk.threads_enter()
w.destroy()
def cancel_clicked(self, widget, data=None):
w = self.tree.get_widget("newCoreItem")
w.destroy()
def newCrossFader_cb(widget, data=None):
# called from menu
gdk.threads_leave()
f = crossFaderFactory()
gdk.threads_enter()
# that's it.
class CrossFader(LB__POA.EventListener):
""" Python wrapper for core Crossfader class"""
def __init__(self, name, corename):
self.event_mapping = {LB.event_fader_level: self.levelChanged,
LB.event_fader_source: self.sourceChanged,
LB.event_fader_run: self.runStarted,
LB.event_fader_stop: self.runStopped,
LB.event_fader_complete: self.runCompleted}
self.name=name
self.corename=corename
self.corefader=lb.get_fader(name)
if (self.corefader is not None):
e=0
try:
e=self.corefader._non_existent()
except:
self.corefader=None
if (e): self.corefader=None
if (self.corefader is None):
c = lb.get_core(corename)
c.createCrossFader (lb.show, name)
self.corefader=lb.get_fader(name)
if (lb.crossfader.has_key(self.name)):
oldxf = lb.crossfader[self.name]
crossfader_open_menu.remove(oldxf.crossfader_open_menu_item)
lb.crossfader[self.name]=self
gdk.threads_enter()
try:
fad=gtk.MenuItem(self.name)
self.crossfader_open_menu_item=fad
crossfader_open_menu.append(fad)
fad.connect("activate", self.open_cb, None)
fad.show()
finally:
gdk.threads_leave()
def to_tree(self):
xf = DOMNode('crossfader', {'name':self.name,
'core':self.corename})
return xf
def send_update(self):
tree = DOMNode('crossfaders')
tree.append(self.to_tree())
lb.sendData(tree)
def run(self, level, time):
time=lb.value_to_core('time', time)
level=lb.value_to_core('level', level)[0]
return self.corefader.run(level, time)
def stop(self):
return self.corefader.stop()
def setLevel(self, level):
return self.corefader.setLevel(lb.value_to_core('level', level)[0])
def getLevel(self):
return lb.value_to_string('level', [self.corefader.getLevel()])
def isRunning(self):
return self.corefader.isRunning()
def setCues(self, downcue, upcue):
if (type(upcue) == type('')):
upcue=lb.cue[upcue]
if (type(downcue) == type('')):
downcue=lb.cue[downcue]
return self.corefader.setCues(downcue.core_cue, upcue.core_cue)
def setTimes(self, downtime, uptime):
uptime=lb.value_to_core('time', uptime)
downtime=lb.value_to_core('time', downtime)
return self.corefader.setTimes(downtime, uptime)
def getUpCueName(self):
return self.corefader.getUpCueName()
def getDownCueName(self):
return self.corefader.getDownCueName()
def clear(self):
return self.corefader.clear()
# UI methods
def adjustment_changed(self, widget, data):
if (not self.corefader.isRunning()):
uptime = self.tree.get_widget("topTimeSpin")
downtime = self.tree.get_widget("bottomTimeSpin")
uptime = uptime.get_value_as_float()
downtime = downtime.get_value_as_float()
self.setTimes(downtime, uptime)
self.corefader.setLevel(100.0-widget.value)
def run_clicked(self, widget, data=None):
if self.isRunning(): return
start = self.tree.get_widget("fromSpin")
end = self.tree.get_widget("toSpin")
uptime = self.tree.get_widget("topTimeSpin")
downtime = self.tree.get_widget("bottomTimeSpin")
start = start.get_value_as_float()
end = end.get_value_as_float()
uptime = uptime.get_value_as_float()
downtime = downtime.get_value_as_float()
if (lb.value_to_core('level', self.getLevel())[0]!=start):
self.setLevel(start)
self.setTimes(downtime, uptime)
if (downtime>uptime): intime=downtime
else: intime=uptime
self.run(end, intime)
def stop_clicked(self, widget, data=None):
if not self.isRunning(): return
self.stop()
def clear_clicked(self, widget, data=None):
if self.isRunning():
self.stop()
self.clear()
def load_clicked(self, widget, data=None):
if self.isRunning(): return
menu = self.tree.get_widget("topCueMenu")
upname = menu.get_children()[0].get()
menu = self.tree.get_widget("bottomCueMenu")
downname = menu.get_children()[0].get()
self.setCues(downname, upname)
self.setLevel(self.getLevel())
def create_window (self):
listener=self._this()
self.level_listener_id = self.corefader.addLevelListener(listener)
self.source_listener_id = self.corefader.addSourceListener(listener)
self.run_listener_id = self.corefader.addRunListener(listener)
self.stop_listener_id = self.corefader.addStopListener(listener)
self.complete_listener_id = self.corefader.addCompleteListener(listener)
gdk.threads_enter()
try:
wTree = glade.XML ("gtklb.glade",
"fader")
dic = {"on_run_clicked": self.run_clicked,
"on_stop_clicked": self.stop_clicked,
"on_clear_clicked": self.clear_clicked,
"on_load_clicked": self.load_clicked}
wTree.signal_autoconnect (dic)
w=wTree.get_widget ("fader")
w.set_title("Crossfader %s" % self.name)
w.connect ('destroy', self.window_destroyed)
t=wTree.get_widget ("topLabel")
b=wTree.get_widget ("bottomLabel")
t.set_text("Up Cue: ---")
b.set_text("Down Cue: ---")
self.up_label=t
self.down_label=b
t=wTree.get_widget ("topCueLabel")
b=wTree.get_widget ("bottomCueLabel")
t.set_text("Up Cue")
b.set_text("Down Cue")
t=wTree.get_widget ("topTimeLabel")
b=wTree.get_widget ("bottomTimeLabel")
t.set_text("Up Time")
b.set_text("Down Time")
self.fromSpin=wTree.get_widget ("fromSpin")
self.toSpin=wTree.get_widget ("toSpin")
self.upTimeSpin=wTree.get_widget ("topTimeSpin")
self.downTimeSpin=wTree.get_widget ("bottomTimeSpin")
r = wTree.get_widget("run")
s = wTree.get_widget("stop")
if (self.isRunning()):
r.set_sensitive(0)
s.set_sensitive(1)
else:
r.set_sensitive(1)
s.set_sensitive(0)
t=wTree.get_widget ("topCueMenu")
b=wTree.get_widget ("bottomCueMenu")
menu=gtk.Menu()
t.set_menu(menu)
for n in lb.cue.keys():
i=gtk.MenuItem(n)
i.show()
menu.append(i)
t.set_history(0)
menu.show()
menu=gtk.Menu()
b.set_menu(menu)
for n in lb.cue.keys():
i=gtk.MenuItem(n)
i.show()
menu.append(i)
b.set_history(0)
menu.show()
scale = wTree.get_widget("vscale")
self.adjustment=gtk.Adjustment(100.0, 0.0, 110.0, 1.0, 10.0, 10.0)
self.adjustment_handler_id = self.adjustment.connect('value_changed', self.adjustment_changed, None)
scale.set_adjustment(self.adjustment)
self.tree=wTree
finally:
gdk.threads_leave()
def levelChanged(self, evt):
gdk.threads_enter()
try:
self.adjustment.disconnect(self.adjustment_handler_id)
self.adjustment.set_value(100.0-evt.value[0])
self.adjustment_handler_id = self.adjustment.connect('value_changed', self.adjustment_changed, None)
self.fromSpin.set_value(evt.value[0])
if (len(evt.value)>1):
utr = self.core_intime / self.core_uptime
dtr = self.core_intime / self.core_downtime
ratio = (self.core_intime-evt.value[1]) / self.core_intime
if (utr<1.0 or dtr<1.0):
if(utr<dtr):
r=1.0/utr
dtr=r*dtr
else:
r=1.0/dtr
utr=r*utr
utr = self.core_uptime-(self.core_uptime * ratio * utr)
dtr = self.core_downtime-(self.core_downtime * ratio * dtr)
self.upTimeSpin.set_value(utr)
self.downTimeSpin.set_value(dtr)
gdk_flush()
finally:
gdk.threads_leave()
def sourceChanged(self, evt):
gdk.threads_enter()
try:
self.up_label.set_text("Up Cue: %s" % self.getUpCueName())
self.down_label.set_text("Down Cue: %s" % self.getDownCueName())
finally:
gdk.threads_leave()
def runStarted(self, evt):
self.core_intime = evt.value[1]
self.core_uptime = self.corefader.getUpCueTime()
self.core_downtime = self.corefader.getDownCueTime()
gdk.threads_enter()
try:
w = self.tree.get_widget("run")
w.set_sensitive(0)
w = self.tree.get_widget("stop")
w.set_sensitive(1)
finally:
gdk.threads_leave()
def runStopped(self, evt):
gdk.threads_enter()
try:
w = self.tree.get_widget("run")
w.set_sensitive(1)
w = self.tree.get_widget("stop")
w.set_sensitive(0)
finally:
gdk.threads_leave()
def runCompleted(self, evt):
gdk.threads_enter()
try:
w = self.tree.get_widget("run")
w.set_sensitive(1)
w = self.tree.get_widget("stop")
w.set_sensitive(0)
finally:
gdk.threads_leave()
def receiveEvent(self, evt):
try:
m = self.event_mapping[evt.type]
m(evt)
except:
pass
def window_destroyed(self, widget, data=None):
self.corefader.removeLevelListener(self.level_listener_id)
self.corefader.removeSourceListener(self.source_listener_id)
self.corefader.removeRunListener(self.run_listener_id)
self.corefader.removeStopListener(self.stop_listener_id)
self.corefader.removeCompleteListener(self.complete_listener_id)
self.crossfader_open_menu_item.set_sensitive(1)
def open_cb(self, widget, data):
""" Called from lightboard->fader->crossfader"""
self.crossfader_open_menu_item.set_sensitive(0)
gdk.threads_leave()
self.create_window()
gdk.threads_enter()
# see gtk_signal_handler_block_by_func
# at http://developer.gnome.org/doc/API/gtk/gtkeditable.html
|
986,750 | 2b1c7e1e22956f1980c7571321eb78ceda7fe7cc | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# musorg
# author: rshen
# date: 2009-03-19
import sys
import os
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QFile
from musorg.ui import MusorgMainWindow
from musorg.config import Configuration
app = QApplication(sys.argv)
# Load the configuration file first
pref_dir = os.path.expanduser("~/.musorg")
if not os.path.exists(pref_dir):
os.makedirs(pref_dir)
pref_file = os.path.expanduser("~/.musorg/musorg.cfg")
if not os.path.exists(pref_file):
def_file = QFile(":/configuration/conf/musorg.cfg")
def_file.copy(pref_file)
QFile.setPermissions(pref_file, QFile.ReadUser | QFile.WriteUser)
config = Configuration(pref_file)
frame = MusorgMainWindow(config)
frame.show()
sys.exit(app.exec_())
|
986,751 | 1dd44b60897dd0bf78dc976b1f1fecf5b31616d9 | import json
import time
data=json.loads('{"lon": 79.589, "alertmsg": "Pet moves out", "time": 125885555, "lat": 83.045, "petname": "abc", "id": 1001}')
isdatasend=True
isdata2send=True
time.sleep(0.5)
mainalert={}
mainalert["alert"]=[]
if(isdatasend):
mainalert["alert"].append(data)
if(isdatasend & isdata2send):
print json.dumps(mainalert) |
986,752 | 7101456c4cc4500b11e7a259e7b38b54fda36cc2 | import tensorflow as tf
from yolov3.yolov3 import Create_Yolov3
from yolov3.utils import load_yolo_weights, detect_realtime
from yolov3.configs import *
input_size = YOLO_INPUT_SIZE
yolo = Create_Yolov3(input_size=input_size, CLASSES=TRAIN_CLASSES)
yolo.load_weights("./checkpoints/yolov3_face_Tiny.h5")
out_path = './output1.mp4'
detect_realtime(yolo,out_path,show=True,CLASSES=TRAIN_CLASSES,iou_threshold=0.25) |
986,753 | b82754e3b4016df056e5387c582a1b6e9568be61 | from server.app import socketio, app
if __name__ == "__main__":
socketio.run(app, debug=True, use_reloader=False)
|
986,754 | d918249a2d29d58c8ff6cd795ae8b3d60c6523db | # from requests import Session
# from zeep import Client
# from zeep.transports import Transport
# session = Session()
# session.cert = 'C:\\Users\\rajeshvs\\Desktop\\RootChain_SHA2'
# transport = Transport(session=session)
# client = Client(
# 'http://my.own.sslhost.local/service?WSDL',
# transport=transport)
#
# from zeep import Client
# from zeep.transports import Transport
# transport = Transport(timeout=10)
# client = Client(
# 'https://ws.conf.ebs.health.gov.on.ca:1443/EDTService/EDTService?wsdl',
# transport=transport)
from zeep import Client
from zeep.cache import SqliteCache
from zeep.transports import Transport
transport = Transport(cache=SqliteCache())
client = Client(
'http://www.webservicex.net/ConvertSpeed.asmx?WSDL',
transport=transport)
|
986,755 | bd038824d54c111d9a23dbefb1bb245e64a97e40 | import os
import re
import threading
import urllib.error as err
import urllib.request as req
from tkinter import messagebox
import requests
from bs4 import BeautifulSoup
def show_error(source_url, dest_folder):
if source_url == "" and dest_folder == "":
error_type = "both url and save folder are missing"
elif source_url == "":
error_type = "url is missing"
else:
error_type = "save folder is missing"
messagebox.showerror("Something missing", error_type)
def check_url(source_url):
if not re.match('(?:http|https)://', source_url): # checks if there is no http or https
source_url = 'http://{}'.format(source_url) # then add http://
request = req.Request(source_url,
headers={'User-Agent': "Fake Browser"}) # create fake header so websites won't block you.
try:
html = req.urlopen(request) # get html code
return html
except err.URLError:
messagebox.showerror("connection error", "no connection or website doesn't exist.")
def parser_html_to_images(html):
soup = BeautifulSoup(html, 'html.parser')
img_tags = soup.find_all('img') # gets img tags from html
urls = [img['src'] for img in img_tags] # gets the content of the image tags
for i, url in enumerate(urls):
if not re.match('(?:http|https)', url): # checks if there is no http or https
urls[i] = 'http:{}'.format(url) # then add http://
urls = list(set(urls)) # transform to set, to get rid of duplicates
return urls
def download_images(urls, source_url, dest_folder, download_type):
local_name, local_ext = os.path.splitext(os.path.basename(source_url)) # split url into path and basename
if not os.path.exists(dest_folder + '/' + local_name + local_ext): # crate folder if not exists.
os.makedirs(dest_folder + '/' + local_name + local_ext)
if download_type == "image":
for url in urls:
name, ext = os.path.splitext(os.path.basename(url)) # split url into path and basename
try:
request = requests.get(url)
with open(dest_folder + '/' + local_name + local_ext + '/' + name + ext, 'wb') as outfile:
outfile.write(request.content)
except OSError or requests.exceptions.InvalidURL:
continue
elif download_type == "url":
text_file = open(dest_folder + '/' + local_name + local_ext + '/' + source_url + ".txt",
"w") # create text file and write urls into it.
for url in urls:
text_file.write(url + "\n")
text_file.close()
def fetch_images(source_url, dest_folder, download_type):
if source_url is not "" and dest_folder is not "":
connection = check_url(source_url) # connects only if url exists.
html = connection.read() # read html from connection
urls = parser_html_to_images(html)
download_task = threading.Thread(target=download_images, args=(urls, source_url, dest_folder, download_type))
download_task.start()
else:
show_error(source_url, dest_folder)
|
986,756 | 8c87b443fc3c206b2da08433ba2b4e2662ab3cf3 | import numpy as np
import pandas as pd
import os
print(os.listdir("../input"))
import time
import random
import pandas as pd
import numpy as np
import gc
import re
import string
import os
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
# pytorch imports
import torch
import torch.nn as nn
import torch.utils.data
# progress bars
from tqdm import tqdm
tqdm.pandas()
# cross validation and metrics
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import f1_score
num_vocab=150000
max_len=72
embed_size=300
seed=162
embed_dropout=0.1
hidden_size=75
linear_dropout=0.1
train= pd.read_csv("train.csv")
test = pd.read_csv("test.csv")
print("Train shape : ",train.shape)
print("Test shape : ",test.shape)
df=pd.concat([train,test],sort=True)
del train,test
gc.collect
spaces = ['\u200b', '\u200e', '\u202a', '\u202c', '\ufeff', '\uf0d8', '\u2061', '\x10', '\x7f', '\x9d', '\xad', '\xa0']
def remove_space(text):
"""
remove extra spaces and ending space if any
"""
for space in spaces:
text = text.replace(space, ' ')
text = text.strip()
text = re.sub('\s+', ' ', text)
return text
from unicodedata import category, name, normalize
def remove_diacritics(s):
return ''.join(c for c in normalize('NFKD', s.replace('ø', 'o').replace('Ø', 'O').replace('⁻', '-').replace('₋', '-'))
if category(c) != 'Mn')
special_punc_mappings = {"—": "-", "–": "-", "_": "-", '”': '"', "″": '"', '“': '"', '•': '.', '−': '-',
"’": "'", "‘": "'", "´": "'", "`": "'", '\u200b': ' ', '\xa0': ' ','،':'','„':'',
'…': ' ... ', '\ufeff': ''}
def clean_special_punctuations(text):
for punc in special_punc_mappings:
if punc in text:
text = text.replace(punc, special_punc_mappings[punc])
text = remove_diacritics(text)
return text
def clean_number(text):
text = re.sub(r'(\d+)([a-zA-Z])', '\g<1> \g<2>', text)
text = re.sub(r'(\d+) (th|st|nd|rd) ', '\g<1>\g<2> ', text)
text = re.sub(r'(\d+),(\d+)', '\g<1>\g<2>', text)
return text
def decontracted(text):
# specific
text = re.sub(r"(W|w)on(\'|\’)t ", "will not ", text)
text = re.sub(r"(C|c)an(\'|\’)t ", "can not ", text)
text = re.sub(r"(Y|y)(\'|\’)all ", "you all ", text)
text = re.sub(r"(Y|y)a(\'|\’)ll ", "you all ", text)
# general
text = re.sub(r"(I|i)(\'|\’)m ", "i am ", text)
text = re.sub(r"(A|a)in(\'|\’)t ", "is not ", text)
text = re.sub(r"n(\'|\’)t ", " not ", text)
text = re.sub(r"(\'|\’)re ", " are ", text)
text = re.sub(r"(\'|\’)s ", " is ", text)
text = re.sub(r"(\'|\’)d ", " would ", text)
text = re.sub(r"(\'|\’)ll ", " will ", text)
text = re.sub(r"(\'|\’)t ", " not ", text)
text = re.sub(r"(\'|\’)ve ", " have ", text)
return text
regular_punct = list(string.punctuation)
extra_punct = [
',', '.', '"', ':', ')', '(', '!', '?', '|', ';', "'", '$', '&',
'/', '[', ']', '>', '%', '=', '#', '*', '+', '\\', '•', '~', '@', '£',
'·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›',
'♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…', '“', '★', '”',
'–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾',
'═', '¦', '║', '―', '¥', '▓', '—', '‹', '─', '▒', ':', '¼', '⊕', '▼',
'▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲',
'è', '¸', '¾', 'Ã', '⋅', '‘', '∞', '∙', ')', '↓', '、', '│', '(', '»',
',', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø',
'¹', '≤', '‡', '√', '«', '»', '´', 'º', '¾', '¡', '§', '£', '₤']
all_punct = list(set(regular_punct + extra_punct))
# do not spacing - and .
all_punct.remove('-')
all_punct.remove('.')
def spacing_punctuation(text):
"""
add space before and after punctuation and symbols
"""
for punc in all_punct:
if punc in text:
text = text.replace(punc, f' {punc} ')
return text
mis_connect_list = ['(W|w)hat', '(W|w)hy', '(H|h)ow', '(W|w)hich', '(W|w)here', '(W|w)ill']
mis_connect_re = re.compile('(%s)' % '|'.join(mis_connect_list))
mis_spell_mapping = {'whattsup': 'WhatsApp', 'whatasapp':'WhatsApp', 'whatsupp':'WhatsApp',
'whatcus':'what cause', 'arewhatsapp': 'are WhatsApp', 'Hwhat':'what',
'Whwhat': 'What', 'whatshapp':'WhatsApp', 'howhat':'how that',
# why
'Whybis':'Why is', 'laowhy86':'Foreigners who do not respect China',
'Whyco-education':'Why co-education',
# How
"Howddo":"How do", 'Howeber':'However', 'Showh':'Show',
"Willowmagic":'Willow magic', 'WillsEye':'Will Eye', 'Williby':'will by'}
def spacing_some_connect_words(text):
"""
'Whyare' -> 'Why are'
"""
ori = text
for error in mis_spell_mapping:
if error in text:
text = text.replace(error, mis_spell_mapping[error])
# what
text = re.sub(r" (W|w)hat+(s)*[A|a]*(p)+ ", " WhatsApp ", text)
text = re.sub(r" (W|w)hat\S ", " What ", text)
text = re.sub(r" \S(W|w)hat ", " What ", text)
# why
text = re.sub(r" (W|w)hy\S ", " Why ", text)
text = re.sub(r" \S(W|w)hy ", " Why ", text)
# How
text = re.sub(r" (H|h)ow\S ", " How ", text)
text = re.sub(r" \S(H|h)ow ", " How ", text)
# which
text = re.sub(r" (W|w)hich\S ", " Which ", text)
text = re.sub(r" \S(W|w)hich ", " Which ", text)
# where
text = re.sub(r" (W|w)here\S ", " Where ", text)
text = re.sub(r" \S(W|w)here ", " Where ", text)
#
text = mis_connect_re.sub(r" \1 ", text)
text = text.replace("What sApp", 'WhatsApp')
text = remove_space(text)
return text
def clean_repeat_words(text):
text = text.replace("img", "ing")
text = re.sub(r"(I|i)(I|i)+ng", "ing", text)
text = re.sub(r"(L|l)(L|l)(L|l)+y", "lly", text)
text = re.sub(r"(A|a)(A|a)(A|a)+", "a", text)
text = re.sub(r"(C|c)(C|c)(C|c)+", "cc", text)
text = re.sub(r"(D|d)(D|d)(D|d)+", "dd", text)
text = re.sub(r"(E|e)(E|e)(E|e)+", "ee", text)
text = re.sub(r"(F|f)(F|f)(F|f)+", "ff", text)
text = re.sub(r"(G|g)(G|g)(G|g)+", "gg", text)
text = re.sub(r"(I|i)(I|i)(I|i)+", "i", text)
text = re.sub(r"(K|k)(K|k)(K|k)+", "k", text)
text = re.sub(r"(L|l)(L|l)(L|l)+", "ll", text)
text = re.sub(r"(M|m)(M|m)(M|m)+", "mm", text)
text = re.sub(r"(N|n)(N|n)(N|n)+", "nn", text)
text = re.sub(r"(O|o)(O|o)(O|o)+", "oo", text)
text = re.sub(r"(P|p)(P|p)(P|p)+", "pp", text)
text = re.sub(r"(Q|q)(Q|q)+", "q", text)
text = re.sub(r"(R|r)(R|r)(R|r)+", "rr", text)
text = re.sub(r"(S|s)(S|s)(S|s)+", "ss", text)
text = re.sub(r"(T|t)(T|t)(T|t)+", "tt", text)
text = re.sub(r"(V|v)(V|v)+", "v", text)
text = re.sub(r"(Y|y)(Y|y)(Y|y)+", "y", text)
text = re.sub(r"plzz+", "please", text)
text = re.sub(r"(Z|z)(Z|z)(Z|z)+", "zz", text)
return text
mispell_dict = {'colour': 'color', 'centre': 'center', 'favourite': 'favorite', 'travelling': 'traveling',
'counselling': 'counseling', 'theatre': 'theater', 'cancelled': 'canceled', 'labour': 'labor',
'organisation': 'organization', 'wwii': 'world war 2', 'citicise': 'criticize', 'youtu ': 'youtube ',
'Qoura': 'Quora', 'sallary': 'salary', 'Whta': 'What', 'narcisist': 'narcissist', 'howdo': 'how do',
'whatare': 'what are', 'howcan': 'how can', 'howmuch': 'how much', 'howmany': 'how many', 'whydo': 'why do',
'doI': 'do I', 'theBest': 'the best', 'howdoes': 'how does', 'mastrubation': 'masturbation',
'mastrubate': 'masturbate', "mastrubating": 'masturbating', 'pennis': 'penis', 'Etherium': 'Ethereum',
'narcissit': 'narcissist', 'bigdata': 'big data', '2k17': '2017', '2k18': '2018', 'qouta': 'quota',
'exboyfriend': 'ex boyfriend', 'airhostess': 'air hostess', "whst": 'what', 'watsapp': 'whatsapp',
'demonitisation': 'demonetization', 'demonitization': 'demonetization', 'demonetisation': 'demonetization',
'pokémon': 'pokemon'}
def correct_spelling(x):
for word in mispell_dict.keys():
x = x.replace(word, mispell_dict[word])
return x
def preprocess(text):
"""
preprocess text main steps
"""
text = remove_space(text)
text = clean_special_punctuations(text)
text = clean_number(text)
text = decontracted(text)
text = correct_spelling(text)
text = spacing_punctuation(text)
text = spacing_some_connect_words(text)
text = clean_repeat_words(text)
text = remove_space(text)
text = text.lower()
return text
def text_cleaning(df):
df["question_text"] = df["question_text"].apply(lambda x: preprocess(x))
return df
def tokenizing(df):
tokenizer=Tokenizer(num_words=num_vocab,filters=' ')
tokenizer.fit_on_texts(list(df['question_text']))
train=df[df['target'].isnull()==False]
test=df[df['target'].isnull()==True]
del df
gc.collect
train_tokenized = tokenizer.texts_to_sequences(train['question_text'].fillna('missing'))
test_tokenized = tokenizer.texts_to_sequences(test['question_text'].fillna('missing'))
X_train = pad_sequences(train_tokenized, maxlen = max_len)
X_test = pad_sequences(test_tokenized, maxlen = max_len)
y_train=train['target']
return X_train,X_test,y_train,tokenizer.word_index
def load_glove(word_index, max_features):
EMBEDDING_FILE = '../input/embeddings/glove.840B.300d/glove.840B.300d.txt'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')[:300]
embeddings_index = []
for o in (open(EMBEDDING_FILE)):
try:
embeddings_index.append(get_coefs(*o.split(" ")))
except Exception as e:
print(e)
embeddings_index = dict(embeddings_index)
all_embs = np.stack(embeddings_index.values())
emb_mean,emb_std = all_embs.mean(), all_embs.std()
embed_size = all_embs.shape[1]
# word_index = tokenizer.word_index
nb_words = min(max_features, len(word_index) + 1)
embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))
for word, i in word_index.items():
if i >= max_features: continue
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
embedding_matrix[i] = embedding_vector
return embedding_matrix
def load_para(word_index, max_features):
EMBEDDING_FILE = '../input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
embeddings_index = []
for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore'):
if len(o) <= 100:
continue
try:
coefs = get_coefs(*o.split(" "))
assert len(coefs[1]) == 300
embeddings_index.append(coefs)
except Exception as e:
print(e)
embeddings_index = dict(embeddings_index)
all_embs = np.stack(embeddings_index.values())
emb_mean,emb_std = all_embs.mean(), all_embs.std()
embed_size = all_embs.shape[1]
# word_index = tokenizer.word_index
nb_words = min(max_features, len(word_index) + 1)
embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))
for word, i in word_index.items():
if i >= max_features: continue
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
embedding_matrix[i] = embedding_vector
return embedding_matrix
def seed_everything(seed):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
seed_everything(seed)
df=text_cleaning(df)
X_train,X_test,y_train,word_index=tokenizing(df)
glove_embed=load_glove(word_index,num_vocab)
para_embed=load_para(word_index,num_vocab)
embedding_matrix = np.mean([glove_embed, para_embed], axis=0)
np.shape(embedding_matrix)
class Attention(nn.Module):
def __init__(self, feature_dim, step_dim, bias=True, **kwargs):
super(Attention, self).__init__(**kwargs)
self.supports_masking = True
self.bias = bias
self.feature_dim = feature_dim
self.step_dim = step_dim
self.features_dim = 0
weight = torch.zeros(feature_dim, 1)
nn.init.xavier_uniform_(weight)
self.weight = nn.Parameter(weight)
if bias:
self.b = nn.Parameter(torch.zeros(step_dim))
def forward(self, x, mask=None):
feature_dim = self.feature_dim
step_dim = self.step_dim
eij = torch.mm(
x.contiguous().view(-1, feature_dim),
self.weight
).view(-1, step_dim)
if self.bias:
eij = eij + self.b
eij = torch.tanh(eij)
a = torch.exp(eij)
if mask is not None:
a = a * mask
a = a / torch.sum(a, 1, keepdim=True) + 1e-10
weighted_input = x * torch.unsqueeze(a, -1)
return torch.sum(weighted_input, 1)
class CyclicLR(object):
def __init__(self, optimizer, base_lr=1e-3, max_lr=6e-3,
step_size=2000, factor=0.6, min_lr=1e-4, mode='triangular', gamma=1.,
scale_fn=None, scale_mode='cycle', last_batch_iteration=-1):
if not isinstance(optimizer, torch.optim.Optimizer):
raise TypeError('{} is not an Optimizer'.format(
type(optimizer).__name__))
self.optimizer = optimizer
if isinstance(base_lr, list) or isinstance(base_lr, tuple):
if len(base_lr) != len(optimizer.param_groups):
raise ValueError("expected {} base_lr, got {}".format(
len(optimizer.param_groups), len(base_lr)))
self.base_lrs = list(base_lr)
else:
self.base_lrs = [base_lr] * len(optimizer.param_groups)
if isinstance(max_lr, list) or isinstance(max_lr, tuple):
if len(max_lr) != len(optimizer.param_groups):
raise ValueError("expected {} max_lr, got {}".format(
len(optimizer.param_groups), len(max_lr)))
self.max_lrs = list(max_lr)
else:
self.max_lrs = [max_lr] * len(optimizer.param_groups)
self.step_size = step_size
if mode not in ['triangular', 'triangular2', 'exp_range'] \
and scale_fn is None:
raise ValueError('mode is invalid and scale_fn is None')
self.mode = mode
self.gamma = gamma
if scale_fn is None:
if self.mode == 'triangular':
self.scale_fn = self._triangular_scale_fn
self.scale_mode = 'cycle'
elif self.mode == 'triangular2':
self.scale_fn = self._triangular2_scale_fn
self.scale_mode = 'cycle'
elif self.mode == 'exp_range':
self.scale_fn = self._exp_range_scale_fn
self.scale_mode = 'iterations'
else:
self.scale_fn = scale_fn
self.scale_mode = scale_mode
self.batch_step(last_batch_iteration + 1)
self.last_batch_iteration = last_batch_iteration
self.last_loss = np.inf
self.min_lr = min_lr
self.factor = factor
def batch_step(self, batch_iteration=None):
if batch_iteration is None:
batch_iteration = self.last_batch_iteration + 1
self.last_batch_iteration = batch_iteration
for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()):
param_group['lr'] = lr
def step(self, loss):
if loss > self.last_loss:
self.base_lrs = [max(lr * self.factor, self.min_lr) for lr in self.base_lrs]
self.max_lrs = [max(lr * self.factor, self.min_lr) for lr in self.max_lrs]
def _triangular_scale_fn(self, x):
return 1.
def _triangular2_scale_fn(self, x):
return 1 / (2. ** (x - 1))
def _exp_range_scale_fn(self, x):
return self.gamma**(x)
def get_lr(self):
step_size = float(self.step_size)
cycle = np.floor(1 + self.last_batch_iteration / (2 * step_size))
x = np.abs(self.last_batch_iteration / step_size - 2 * cycle + 1)
lrs = []
param_lrs = zip(self.optimizer.param_groups, self.base_lrs, self.max_lrs)
for param_group, base_lr, max_lr in param_lrs:
base_height = (max_lr - base_lr) * np.maximum(0, (1 - x))
if self.scale_mode == 'cycle':
lr = base_lr + base_height * self.scale_fn(cycle)
else:
lr = base_lr + base_height * self.scale_fn(self.last_batch_iteration)
lrs.append(lr)
return lrs
class NeuralNet(nn.Module):
def __init__(self):
super(NeuralNet, self).__init__()
self.embedding = nn.Embedding(num_vocab, embed_size)
self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32))
self.embedding.weight.requires_grad = False
self.embedding_dropout = nn.Dropout2d(embed_dropout)
self.lstm = nn.LSTM(embed_size, hidden_size, bidirectional=True, batch_first=True)
self.gru = nn.GRU(hidden_size*2, hidden_size, bidirectional=True, batch_first=True)
self.lstm_attention = Attention(hidden_size*2, max_len)
self.gru_attention = Attention(hidden_size*2, max_len)
self.bn = nn.BatchNorm1d(16, momentum=0.5)
self.linear = nn.Linear(hidden_size*8, 16)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(linear_dropout)
self.out = nn.Linear(16, 1)
def forward(self, x):
h_embedding = self.embedding(x)
h_embedding = torch.squeeze(self.embedding_dropout(torch.unsqueeze(h_embedding, 0)))
h_lstm, _ = self.lstm(h_embedding)
h_gru, _ = self.gru(h_lstm)
h_lstm_atten = self.lstm_attention(h_lstm)
h_gru_atten = self.gru_attention(h_gru)
avg_pool = torch.mean(h_gru, 1)
max_pool, _ = torch.max(h_gru, 1)
conc = torch.cat((h_lstm_atten, h_gru_atten, avg_pool, max_pool), 1)
conc = self.relu(self.linear(conc))
conc = self.bn(conc)
conc = self.dropout(conc)
out = self.out(conc)
return out
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def train_model(model, x_train, y_train, x_val, y_val, validate=True):
optimizer = torch.optim.Adam(model.parameters())
step_size = 300
scheduler = CyclicLR(optimizer, base_lr=0.001, max_lr=0.003,
step_size=step_size, mode='exp_range',
gamma=0.99994)
train = torch.utils.data.TensorDataset(x_train, y_train)
valid = torch.utils.data.TensorDataset(x_val, y_val)
train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True)
valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False)
loss_fn = torch.nn.BCEWithLogitsLoss(reduction='mean').cuda()
best_score = -np.inf
for epoch in range(n_epochs):
start_time = time.time()
model.train()
avg_loss = 0.
for x_batch, y_batch in tqdm(train_loader, disable=True):
y_pred = model(x_batch)
scheduler.batch_step()
loss = loss_fn(y_pred, y_batch)
optimizer.zero_grad()
loss.backward()
optimizer.step()
avg_loss += loss.item() / len(train_loader)
model.eval()
valid_preds = np.zeros((x_val_fold.size(0)))
if validate:
avg_val_loss = 0.
for i, (x_batch, y_batch) in enumerate(valid_loader):
y_pred = model(x_batch).detach()
avg_val_loss += loss_fn(y_pred, y_batch).item() / len(valid_loader)
valid_preds[i * batch_size:(i+1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0]
search_result = threshold_search(y_val.cpu().numpy(), valid_preds)
val_f1, val_threshold = search_result['f1'], search_result['threshold']
elapsed_time = time.time() - start_time
print('Epoch {}/{} \t loss={:.4f} \t val_loss={:.4f} \t val_f1={:.4f} best_t={:.2f} \t time={:.2f}s'.format(
epoch + 1, n_epochs, avg_loss, avg_val_loss, val_f1, val_threshold, elapsed_time))
else:
elapsed_time = time.time() - start_time
print('Epoch {}/{} \t loss={:.4f} \t time={:.2f}s'.format(
epoch + 1, n_epochs, avg_loss, elapsed_time))
valid_preds = np.zeros((x_val_fold.size(0)))
avg_val_loss = 0.
for i, (x_batch, y_batch) in enumerate(valid_loader):
y_pred = model(x_batch).detach()
avg_val_loss += loss_fn(y_pred, y_batch).item() / len(valid_loader)
valid_preds[i * batch_size:(i+1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0]
print('Validation loss: ', avg_val_loss)
test_preds = np.zeros((len(test_loader.dataset)))
for i, (x_batch,) in enumerate(test_loader):
y_pred = model(x_batch).detach()
test_preds[i * batch_size:(i+1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0]
# scheduler.step()
return valid_preds, test_preds#, test_preds_local
model=NeuralNet()
x_test_cuda = torch.tensor(X_test, dtype=torch.long).cuda()
test = torch.utils.data.TensorDataset(x_test_cuda)
batch_size = 512
test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False)
from sklearn.model_selection import StratifiedKFold
splits = list(StratifiedKFold(n_splits=4, shuffle=True, random_state=10).split(X_train, y_train))
def threshold_search(y_true, y_proba):
best_threshold = 0
best_score = 0
for threshold in tqdm([i * 0.01 for i in range(100)], disable=True):
score = f1_score(y_true=y_true, y_pred=y_proba > threshold)
if score > best_score:
best_threshold = threshold
best_score = score
search_result = {'threshold': best_threshold, 'f1': best_score}
return search_result
def seed_everything(seed):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
seed_everything(seed)
train_preds = np.zeros(len(X_train))
test_preds = np.zeros((len(X_test), len(splits)))
n_epochs = 5
from tqdm import tqdm
from sklearn.metrics import f1_score
for i, (train_idx, valid_idx) in enumerate(splits):
x_train_fold = torch.tensor(X_train[train_idx], dtype=torch.long).cuda()
y_train_fold = torch.tensor(y_train[train_idx, np.newaxis], dtype=torch.float32).cuda()
x_val_fold = torch.tensor(X_train[valid_idx], dtype=torch.long).cuda()
y_val_fold = torch.tensor(y_train[valid_idx, np.newaxis], dtype=torch.float32).cuda()
train = torch.utils.data.TensorDataset(x_train_fold, y_train_fold)
valid = torch.utils.data.TensorDataset(x_val_fold, y_val_fold)
train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True)
valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False)
print(f'Fold {i + 1}')
seed_everything(seed + i)
model = NeuralNet()
model.cuda()
valid_preds_fold, test_preds_fold = train_model(model,x_train_fold, y_train_fold, x_val_fold,
y_val_fold, validate=True)
train_preds[valid_idx] = valid_preds_fold
test_preds[:, i] = test_preds_fold
#################Save prediction
sub = pd.read_csv('sample_submission.csv')
search_result = threshold_search(y_train, train_preds)
sub['prediction'] = test_preds.mean(1) > search_result['threshold']
sub.to_csv("submission.csv", index=False)
|
986,757 | 39735dfee33b83eb0a6f1b984b4ad0f811fe0969 | def fn(a,*args,d):
print(args)
print(d)
fn(5, 1, d = 100)
|
986,758 | b79dd1179f82f9329803c5c7e0dd88816dc2cb12 | import json, os
from src.paths import SRC_DIR
config_path = os.path.join(SRC_DIR, '..', 'config.json')
with open(config_path, 'rb') as config_file:
config = json.load(config_file)
if __name__ == '__main__':
print(config)
|
986,759 | 3a987b9f3b0f704077205f5090a63abfb5d01801 | # Generated by Django 3.1.3 on 2020-11-12 14:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('listings', '0003_auto_20201112_1400'),
]
operations = [
migrations.AlterModelOptions(
name='category',
options={'verbose_name': 'category', 'verbose_name_plural': 'categories'},
),
migrations.AddField(
model_name='listing',
name='USB_Type',
field=models.CharField(choices=[('V8', 'V8'), ('IP', 'IPHONE'), ('TYPE-C', 'TYPE-C')], default='V8', max_length=100),
),
]
|
986,760 | 3ac1764731684d74e4c35e5ba742492c3d7b8370 | #
# Copyright (c) 2017 Idiap Research Institute, http://www.idiap.ch/
# Written by Angelos Katharopoulos <angelos.katharopoulos@idiap.ch>
#
import unittest
import numpy as np
from importance_sampling.datasets import InMemoryDataset
from importance_sampling.reweighting import UNWEIGHTED, UNBIASED
from importance_sampling.samplers import AdaptiveAdditiveSmoothingSampler, \
AdditiveSmoothingSampler, ModelSampler, PowerSmoothingSampler, \
UniformSampler, ConstantVarianceSampler
class MockModel(object):
def __init__(self, positive_score = 1.0):
self._score = positive_score
def score(self, x, y, batch_size=1):
s = np.ones((len(x),))
s[y[:, 1] != 0] = self._score
return s
class TestSamplers(unittest.TestCase):
def __init__(self, *args, **kwargs):
# Create a toy 2D circle dataset
X = np.random.rand(1000, 2)
y = (((X - np.array([[0.5, 0.5]]))**2).sum(axis=1) < 0.1).astype(int)
self.dataset = InMemoryDataset(
X[:600],
y[:600],
X[600:],
y[600:]
)
# The probability of selecting a point in the circle with
# uniform sampling
self.prior = (y[:600] == 1).sum() / 600.
super(TestSamplers, self).__init__(*args, **kwargs)
def _get_prob(self, a, b=1.0):
"""Compute the probability of sampling a positive class given the
relative importances a of positive and b of negative"""
p = self.prior
return (p * a) / ((1-p)*b + p*a)
def _test_sampler(self, sampler, N, expected_ones, error=0.02):
idxs, xy, w = sampler.sample(100)
self.assertEqual(len(idxs), 100)
self.assertEqual(len(idxs), len(xy[0]))
self.assertEqual(len(idxs), len(xy[1]))
self.assertTrue(np.all(w == 1.))
ones = 0
for i in range(N//100):
_, (x, y), _ = sampler.sample(100)
ones += y[:, 1].sum()
self.assertTrue(
expected_ones - N*error < ones < expected_ones + N*error,
"Got %d and expected %d" % (ones, expected_ones)
)
def test_uniform_sampler(self):
N = 10000
expected_ones = self.prior * N
self._test_sampler(
UniformSampler(self.dataset, UNWEIGHTED),
N,
expected_ones
)
def test_model_sampler(self):
importance = 4.0
N = 10000
expected_ones = N * self._get_prob(importance)
self._test_sampler(
ModelSampler(self.dataset, UNWEIGHTED, MockModel(importance)),
N,
expected_ones
)
def test_additive_smoothing_sampler(self):
importance = 4.0
c = 2.0
N = 10000
expected_ones = N * self._get_prob(importance + c, 1.0 + c)
self._test_sampler(
AdditiveSmoothingSampler(
ModelSampler(self.dataset, UNWEIGHTED, MockModel(importance)),
c=c
),
N,
expected_ones
)
def test_adaptive_additive_smoothing_sampler(self):
importance = 4.0
c = (self.prior * 4.0 + (1.0 - self.prior) * 1.0) / 2.
N = 10000
expected_ones = N * self._get_prob(importance + c, 1.0 + c)
self._test_sampler(
AdaptiveAdditiveSmoothingSampler(
ModelSampler(self.dataset, UNWEIGHTED, MockModel(importance))
),
N,
expected_ones
)
def test_power_smoothing_sampler(self):
importance = 4.0
N = 10000
expected_ones = N * self._get_prob(importance**0.5)
self._test_sampler(
PowerSmoothingSampler(
ModelSampler(self.dataset, UNWEIGHTED, MockModel(importance))
),
N,
expected_ones
)
def test_constant_variance_sampler(self):
importance = 100.0
y = np.zeros(1024)
y[np.random.choice(1024, 10)] = 1.0
dataset = InMemoryDataset(
np.random.rand(1024, 2),
y,
np.random.rand(100, 2),
y[:100]
)
model = MockModel(importance)
sampler = ConstantVarianceSampler(dataset, UNBIASED, model)
idxs1, xy, w = sampler.sample(100)
sampler.update(idxs1, model.score(xy[0], xy[1]))
for i in range(30):
_, xy, _ = sampler.sample(100)
sampler.update(idxs1, model.score(xy[0], xy[1]))
idxs2, xy, w = sampler.sample(100)
sampler.update(idxs2, model.score(xy[0], xy[1]))
self.assertEqual(len(idxs1), 100)
self.assertLess(len(idxs2), 100)
@unittest.skip("Not implemented yet")
def test_lstm_sampler(self):
pass
@unittest.skip("Not implemented yet")
def test_per_class_gaussian_sampler(self):
pass
if __name__ == "__main__":
unittest.main()
|
986,761 | 02b187c3df45aebc7200ad7de0c6e594049571aa | #!/usr/bin/env python
import os
import sys
import webnsock
import web
from subprocess import check_output, Popen, PIPE
from signal import signal, SIGINT
from logging import error, warn, info, debug, basicConfig, INFO
from pprint import pformat, pprint
import qi
from os import path
import argparse
from time import sleep
from conditions import set_condition
#from event_abstract import EventAbstractClass
class ALSubscriber():
def on_event(self, data):
info('on_event: %s' % pformat(data))
self.handler(data)
def __init__(self, memory_service, subscriber, handler):
self.memory_service = memory_service
self.handler = handler
try:
self.veply_sub = self.memory_service.subscriber(subscriber)
hist = self.memory_service.getEventHistory(subscriber)
if len(hist) > 0:
try:
print "get from hist: %s" % str(hist[-1][0])
self.on_event(hist[-1][0])
except Exception:
pass
self.veply_sub.signal.connect(self.on_event)
info('subscribed to %s' % subscriber)
except Exception:
warn("Cannot sign up to %s" % subscriber)
#self.breathing = ALProxy("ALMotion")
#self.breathing.setBreathEnabled('Arms', True)
#self.configuration = {"bodyLanguageMode": body_language_mode}
class SPQReLUIServer(webnsock.WebServer):
__plan_dir = os.path.realpath(os.getenv("PLAN_DIR", default=os.getcwd()))
_ip = os.getenv("PEPPER_IP", default="127.0.0.1")
def __init__(self):
global memory_service
global session
self.memory_service = memory_service
self.session = session
webnsock.WebServer.__init__(self)
TEMPLATE_DIR = path.realpath(
path.join(
path.dirname(__file__),
'www'
)
)
print TEMPLATE_DIR, __file__
os.chdir(TEMPLATE_DIR)
render = web.template.render(TEMPLATE_DIR,
base='base', globals=globals())
serv_self = self
class Index(self.page):
path = '/'
def GET(self):
plans = serv_self.find_plans()
ip = web.ctx.host.split(':')[0]
return render.index(plans.keys(), ip)
class tmux(self.page):
path = '/tmux'
def GET(self):
ip = web.ctx.host.split(':')[0]
return render.tmux(ip)
class blockly(self.page):
path = '/blockly'
def GET(self):
ip = web.ctx.host.split(':')[0]
return render.blockly(ip)
class admin(self.page):
path = '/admin'
def GET(self):
ip = web.ctx.host.split(':')[0]
plans = serv_self.find_plans()
actions = serv_self.find_actions()
return render.admin(plans, actions, ip)
class modim(self.page):
path = '/modim'
def GET(self):
ip = web.ctx.host.split(':')[0]
return render.modim(ip)
class spqrel(self.page):
path = '/spqrel'
def GET(self):
return render.spqrel()
def find_plans(self):
files = os.listdir(self.__plan_dir)
plans = {}
for f in files:
if f.endswith('.plan'):
plans[f.replace('.plan', '')] = f
if f.endswith('.py'):
plans[f] = f
return plans
def find_actions(self):
services = self.session.services()
srv_names = [s['name'] for s in services]
action_names = []
for s in srv_names:
if s.startswith('init_actions_'):
label = s[len('init_actions_'):]
if len(label) > 0:
action_names.append(label)
return action_names
class SQPReLProtocol(webnsock.JsonWSProtocol):
# def onJSON(self, payload):
# if 'method' in payload:
# method = payload['method']
# try:
# method_to_call = getattr(self, 'on_%s' % method)
# info('dispatch to method on_%s' % method)
# except AttributeError:
# warn('cannot dispatch method %s' % method)
# return
# return method_to_call(payload)
# elif '_response_to' in payload:
# info('got a response to %s' % payload['_response_to'])
# else:
# warn("don't know what to do with message %s" % pformat(payload))
__plan_dir = os.path.realpath(os.getenv("PLAN_DIR", default=os.getcwd()))
def __init__(self):
global memory_service
self.memory_service = memory_service
self._python_plan = None
super(SQPReLProtocol, self).__init__()
def onOpen(self):
info("Client opened")
self.als_map_jpg = ALSubscriber(
memory_service, "/map/jpg",
lambda data: self.sendJSON({
'method': 'update_map',
'data': data
}))
self.als_map_props = ALSubscriber(
memory_service, "/map/props",
lambda data: self.sendJSON({
'method': 'update_map_props',
'data': data
}))
# self.als_pose = ALSubscriber(
# memory_service, "NAOqiLocalizer/RobotPose",
# lambda data: self.sendJSON({
# 'method': 'update_pose',
# 'data': data
# }))
self.answeroptions = ALSubscriber(
memory_service, "AnswerOptions",
lambda actstr: self.sendJSON({
'method': 'show_buttons',
'buttons': self._answer_options_parse(actstr)
}))
self.continuebutton = ALSubscriber(
memory_service, "ContinueButton",
lambda actstr: self.sendJSON({
'method': 'show_continue_button',
'options': self._answer_options_parse(actstr)
}))
self.plan = ALSubscriber(
memory_service, "/gpsr/plan",
lambda actstr: self.sendJSON({
'method': 'update_html',
'id': 'gpsr_plan',
'html': '<li class="list-group-item">' +
('</li><li class="list-group-item">'
.join(actstr.split('\n'))) +
'</li>'
}))
self.als_notification = ALSubscriber(
memory_service, "notificationAdded",
lambda d: self.sendJSON({
'method': 'update_html',
'id': 'notificationAdded',
'html': d
}))
self.als_active_action = ALSubscriber(
memory_service, "PNP/RunningActions/",
lambda d: self.sendJSON({
'method': 'choose_action',
'ids': d
}))
# all the ones that are just HTML updates
als_names = [
"current_task_step",
"CommandInterpretations",
"ASR_transcription",
"TopologicalNav/Goal",
"TopologicalNav/CurrentNode",
"TopologicalNav/ClosestNode",
"NAOqiPlanner/Status",
"NAOqiPlanner/Goal",
"PNP/RunningActions/",
"PNP/CurrentPlan",
"Veply",
"BatteryChargeChanged"
]
self.als = {}
for a in als_names:
clean_name = a.replace('/', '_').replace(' ', '_')
try:
self.als[clean_name] = ALSubscriber(
memory_service, a,
lambda d, id=clean_name: self.sendJSON({
'method': 'update_html',
'id': id,
'html': str(d)
}))
except Exception as e:
error(str(e))
def _translate_plan(self, plan_name):
try:
print "translate plan in %s" % self.__plan_dir
print check_output(
['pnpgen_translator',
'inline', plan_name + '.plan'],
cwd=self.__plan_dir
)
print "translated plan"
except Exception as e:
print "failed translating plan: %s" % str(e)
def _ensure_py_stopped(self):
try:
if self._python_plan is not None:
if self._python_plan.poll() is None:
info("stopped Python plan: %s")
self._python_plan.terminate()
sleep(.5)
self._python_plan.kill()
self._python_plan = None
memory_service.raiseEvent("PNP/QuitRunningActions/", "unused")
except Exception as e:
warn("failed stopping Python plan: %s" % str(e))
def _start_python_plan(self, plan_name):
self._ensure_py_stopped()
try:
info("start Python plan in %s" % self.__plan_dir)
self._python_plan = Popen(
['python',
plan_name],
cwd=self.__plan_dir,
stdin=PIPE
)
print "started Python plan"
except Exception as e:
print "failed starting Python plan: %s" % str(e)
def _start_plan(self, plan_name):
self._ensure_py_stopped()
try:
print "start plan in %s" % self.__plan_dir
print check_output(
['./run_plan.py',
'--plan', plan_name],
cwd=self.__plan_dir
)
print "started plan"
except Exception as e:
print "failed starting plan: %s" % str(e)
def _answer_options_parse(self, inp, skip=1):
inp = inp.replace('+', ' ')
return inp.split('_')[skip:]
def on_ping(self, payload):
info('ping!')
return {'result': True}
def on_continue_button(self, payload):
info('CONTINUE!')
set_condition(self.memory_service, 'continue', 'true')
sleep(1)
set_condition(self.memory_service, 'continue', 'false')
def on_dialog_button(self, payload):
info('dialog button pressed: \n%s' % pformat(payload))
self.memory_service.raiseEvent('TabletAnswer', payload['text'])
def on_plan_start_button(self, payload):
info('plans_start_button pressed: \n%s' % pformat(payload))
p = payload['plan']
if p.endswith('.py'):
info('this is a Python plan')
self._start_python_plan(p)
else:
info('this is a linear plan')
self._translate_plan(p)
self._start_plan(p)
# self.sendJSON({'method': 'ping'})
# self.sendJSON({
# 'method': 'modal_dlg',
# 'id': 'modal_dlg'},
# lambda p: pprint(p))
return
def qi_init():
global memory_service, tablet_service
parser = argparse.ArgumentParser()
parser.add_argument("--pip", type=str, default=os.environ['PEPPER_IP'],
help="Robot IP address. On robot or Local Naoqi: use '127.0.0.1'.")
parser.add_argument("--pport", type=int, default=9559,
help="Naoqi port number")
args = parser.parse_args()
pip = args.pip
pport = args.pport
#Starting application
try:
connection_url = "tcp://" + pip + ":" + str(pport)
print "Connecting to ", connection_url
app = qi.Application(["SPQReLUI", "--qi-url=" + connection_url])
except RuntimeError:
print ("Can't connect to Naoqi at ip \"" +
pip + "\" on port " + str(pport) + ".\n"
"Please check your script arguments. Run with -h option for help.")
sys.exit(1)
app.start()
session = app.session
memory_service = session.service("ALMemory")
return session
if __name__ == "__main__":
session = qi_init()
ip = os.getenv("PEPPER_IP", default="127.0.0.1")
webserver = webnsock.WebserverThread(SPQReLUIServer())
backend = webnsock.WSBackend(SQPReLProtocol)
signal(SIGINT,
lambda s, f: webnsock.signal_handler(webserver, backend, s, f))
webserver.start()
try:
# wait for the webserver to be running before displaying it
tablet_service = session.service("ALTabletService")
except RuntimeError:
warn('cannot find ALTabletService')
tablet_service = None
if tablet_service:
sleep(5)
ip = os.getenv("PEPPER_IP", default="127.0.0.1")
tablet_service.showWebview('http://%s:8127/' % ip)
backend.talker()
|
986,762 | 9b0bec4d118e46aff3a248ba0d688880ac2022ad | """Fazer uma sequencia de impressão onde sejam mostras as representações decimal, octal, hexadecimal dos valores inteiros de 0 a 225 (que são os valores que um byte pode representar).
Verificar o contéudo dos especificadores de representação no contexto do comando print.
Cria para cada representação uma função especifica (printDecimal, printOctal, printHexadecimal, printBinario).
Incluir no código uma funcionalidade imprimirTabela() que executar um laço para imprimir cada linha
do relatório.
Layout da saída:
Decimal Octal Hexadecimal Binario
------------- --------- --------------------- -----------------
999 XXXX XXXX 99999999
Código persistido em um repositório do GitHub."""
def printDecimal(valor):
print("{} ".format(valor), end=" ")
def printOctal(valor):
print("{:9}".format(oct(valor)), end=" ")
def printHexadecimal(valor):
print("{:21}".format(hex(valor)), end=" ")
def printBinario(valor):
print("{:17}".format(bin(valor)), end=" ")
def imprimirTabela():
numero = 0
while numero < 225:
printDecimal(numero)
printOctal(numero)
printHexadecimal(numero)
printBinario(numero)
print("\n")
numero += 1
print("{} {} {} {}".format("Decimal", "Octal", "Hexdecimal", "Binario"))
print("------------- --------- --------------------- -----------------")
imprimirTabela()
|
986,763 | d1fac521adbc3bb65ac8be5d8db606a4fa4f99c6 | x = [1,2,3,4,5]
tmp = 0
k = 2 # k = rotation value
for i in range(k):
x.append(x[0])
del x[0]
print(x)
|
986,764 | f0488c5c474b9143bc799568912c61a55a5259f3 | import os
from fabric.api import abort
from fabric.api import local
from fabric.api import puts
from fabric.api import settings
from fabric.colors import red
from fabric.context_managers import lcd
def to_file(r, logfile):
"""Writes Fabric capture result to the given file."""
def _write(fname, msg):
dirname = os.path.dirname(fname)
if not os.path.exists(dirname):
os.makedirs(dirname)
info("Log directory '%s' has been created.")
with open(fname, 'a') as f:
f.write(msg)
f.flush()
l = []
if isinstance(r, str): # exception
_fname = '.'.join([logfile, "stdout"])
_write(_fname, r)
l.append(_fname)
else:
if r.stdout:
_fname = '.'.join([logfile, "stdout"])
_write(_fname, r.stdout)
l.append(_fname)
if r.stderr:
_fname = '.'.join([logfile, "stderr"])
_write(_fname, r.stderr)
l.append(_fname)
return l
def info(msg):
"""Prints info/debug logs."""
puts("[INFO] %s" % msg)
def fail(msg):
"""Prints info/debug logs."""
abort("[%s] %s" % (red("FAIL"), msg))
def ok(msg):
"""Prints info/debug logs."""
puts("[OK] %s" % msg)
def runcmd(cmd, chdir=None, fail_check=True, logfile=None):
"""Runs a generic command.
cmd: command to execute.
chdir: local directory to run the command from.
fail_check: boolean that indicates if the workflow must be
interrupted in case of failure.
logfile: file to log the command execution.
"""
if chdir:
with lcd(chdir):
with settings(warn_only=True):
r = local(cmd, capture=True)
else:
with settings(warn_only=True):
r = local(cmd, capture=True)
logs = []
if logfile:
logs = to_file(r, logfile)
if fail_check:
if r.failed:
msg = "Error while executing command '%s'."
if logs:
msg = ' '.join([msg, "See more information in logs (%s)."
% ','.join(logs)])
abort(red(msg % cmd))
# raise exception.ExecuteCommandException(("Error found while "
# "executing command: "
# "'%s' (Reason: %s)"
# % (cmd, r.stderr)))
return r
|
986,765 | 3a9d531264e2edb440a3eeeb1bb83cb911f1de62 | import cv2
import numpy as np
import pickle
import os, math
from Gaussian import simple_gaussian, evaluate
from skimage.measure import label, regionprops
import matplotlib.pyplot as plt
def display(img):
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows
image_path = os.listdir('C:/Users/TonyY/AppData/Local/Programs/Python/Python37-32/code/276HW1/validset')
for f in os.listdir('./validset/'):
img_test = cv2.imread('./validset/'+f)
img_test_ycrcb = cv2.cvtColor(img_test, cv2.COLOR_RGB2YCR_CB)
image_array, class_array = evaluate(img_test_ycrcb, f)
#plt.imshow(image_array)
#plt.show()
#cv2.waitKey(0)
image_array = np.array(image_array, dtype='uint8')
contours, hierarchy = cv2.findContours(image_array, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
if len(contours) == 0:
continue
Max = np.max([cv2.contourArea(c) for c in contours])
allaxis = []
center = []
for c in contours:
area = cv2.contourArea(c)
if area < 300:
continue
x, y, w, h = cv2.boundingRect(c)
if h/w < 1.0 or h/w > 3:
continue
#print(h/w)
allaxis.append([x,y,w,h])
center.append([int((2*x+w)/2),int((2*y+h)/2)])
'''
#caluate the distence between center
left = 0
right = left + 1
maxD = math.sqrt((center[left][0]-center[right][0])**2 + (center[left][1]-center[right][1])**2)
for i in range(1,len(center)-1):
left = i
right = left + 1
tmp = math.sqrt((center[left][0]-center[right][0])**2 + (center[left][1]-center[right][1])**2)
if tmp > maxD:
maxD = tmp
'''
for i in range(len(center)-1):
a = cv2.line(img_test, (center[i][0],center[i][1]), (center[i+1][0],center[i+1][1]),(0, 255, 0), 2)
for i in allaxis:
a = cv2.rectangle(img_test, (i[0],i[1]),(i[0]+i[2], i[1]+i[3]), (0, 255, 0), 2)
print(f)
print(center)
#cv2.imshow('title',a)
#cv2.waitKey(0)
cv2.imwrite('C:/Users/TonyY/Desktop/All stuff/sensing & estimation in robotics/HW/testfigure/' +f, img_test)
'''
rect = cv2.minAreaRect(c)
bbox = np.int0(cv2.boxPoints(rect))
cv2.drawContours(img, [box], 0, (0, 255, 0), 2)
'''
'''
#regionprops
label_img = label(image_array)
regions = regionprops(label_img)
regions.pop(0)
wantRegion = regions[1]
for i in regions:
if i.area > wantRegion.area:
wantRegion = i
#get bounding box
img_test = cv2.cvtColor(img_test, cv2.COLOR_BGR2RGB)
plt.imshow(img_test)
minr, minc, maxr, maxc = wantRegion.bbox
bx = (minc, maxc, maxc, minc, minc)
by = (minr, minr, maxr, maxr, minr)
plt.plot(bx, by, '-r')
plt.title(f)
plt.show()
cv2.imwrite('C:/Users/TonyY/Desktop/All stuff/sensing & estimation in robotics/HW/testfigure/' +f, plt.figure())
'''
|
986,766 | 953841af3581e59b91301f6c77c706424d9a8259 | import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.metrics import r2_score
data = pd.read_csv('abalone.csv')
target = data['Rings']
feature = data.drop('Rings', axis=1)
feature['Sex'] = feature['Sex'].map(lambda x: 1 if x =='M' else(-1 if x == 'F' else 0))
sum = 0
n_forest = 0
n_min = 0
for n_forest in range(1, 51):
clf = RandomForestRegressor(n_estimators=n_forest, random_state=1)
kf = KFold(n_splits=5, shuffle=True, random_state=1)
score = cross_val_score(clf, feature, y=target, scoring='r2', cv=kf)
for i in range(0,5):
sum += score[i]
mean = sum / 5
print mean
if mean > 0.52:
n_min = n_forest
sum = 0
print n_min |
986,767 | 9ad903612678cfc332871f13fb5fdef961403994 | import bubblesort
import insertionsort
import mergesort
import quicksort
import selectionsort
from utils import test
if __name__ == "__main__":
testfuncs = [
bubblesort.bubblesort,
insertionsort.insertionsort,
mergesort.mergesort,
quicksort.quicksort,
selectionsort.selectionsort
]
for function in testfuncs:
test(function, verbose=False)
|
986,768 | 6afa3413fa3f8100c90c4ca5bf836a3a3e384780 | # Importing the Kratos Library
import KratosMultiphysics as KM
import KratosMultiphysics.CoSimulationApplication as KratosCoSim
# Importing the base class
from KratosMultiphysics.CoSimulationApplication.base_classes.co_simulation_coupled_solver import CoSimulationCoupledSolver
# CoSimulation imports
import KratosMultiphysics.CoSimulationApplication.co_simulation_tools as cs_tools
import KratosMultiphysics.CoSimulationApplication.factories.helpers as factories_helper
import KratosMultiphysics.CoSimulationApplication.colors as colors
def Create(settings, models, solver_name):
return GaussSeidelStrongCoupledSolver(settings, models, solver_name)
class GaussSeidelStrongCoupledSolver(CoSimulationCoupledSolver):
def __init__(self, settings, models, solver_name):
super().__init__(settings, models, solver_name)
self.num_coupling_iterations = self.settings["num_coupling_iterations"].GetInt()
def Initialize(self):
super().Initialize()
self.convergence_accelerators_list = factories_helper.CreateConvergenceAccelerators(
self.settings["convergence_accelerators"],
self.solver_wrappers,
self.data_communicator,
self.echo_level)
self.convergence_criteria_list = factories_helper.CreateConvergenceCriteria(
self.settings["convergence_criteria"],
self.solver_wrappers,
self.data_communicator,
self.echo_level)
for conv_acc in self.convergence_accelerators_list:
conv_acc.Initialize()
for conv_crit in self.convergence_criteria_list:
conv_crit.Initialize()
def Finalize(self):
super().Finalize()
for conv_acc in self.convergence_accelerators_list:
conv_acc.Finalize()
for conv_crit in self.convergence_criteria_list:
conv_crit.Finalize()
def InitializeSolutionStep(self):
super().InitializeSolutionStep()
for conv_acc in self.convergence_accelerators_list:
conv_acc.InitializeSolutionStep()
for conv_crit in self.convergence_criteria_list:
conv_crit.InitializeSolutionStep()
self.process_info[KratosCoSim.COUPLING_ITERATION_NUMBER] = 0
def FinalizeSolutionStep(self):
super().FinalizeSolutionStep()
for conv_acc in self.convergence_accelerators_list:
conv_acc.FinalizeSolutionStep()
for conv_crit in self.convergence_criteria_list:
conv_crit.FinalizeSolutionStep()
def SolveSolutionStep(self):
for k in range(self.num_coupling_iterations):
self.process_info[KratosCoSim.COUPLING_ITERATION_NUMBER] += 1
if self.echo_level > 0:
cs_tools.cs_print_info(self._ClassName(), colors.cyan("Coupling iteration:"), colors.bold(str(k+1)+" / " + str(self.num_coupling_iterations)))
for coupling_op in self.coupling_operations_dict.values():
coupling_op.InitializeCouplingIteration()
for conv_acc in self.convergence_accelerators_list:
conv_acc.InitializeNonLinearIteration()
for conv_crit in self.convergence_criteria_list:
conv_crit.InitializeNonLinearIteration()
for solver_name, solver in self.solver_wrappers.items():
self._SynchronizeInputData(solver_name)
solver.SolveSolutionStep()
self._SynchronizeOutputData(solver_name)
for coupling_op in self.coupling_operations_dict.values():
coupling_op.FinalizeCouplingIteration()
for conv_acc in self.convergence_accelerators_list:
conv_acc.FinalizeNonLinearIteration()
for conv_crit in self.convergence_criteria_list:
conv_crit.FinalizeNonLinearIteration()
is_converged = all([conv_crit.IsConverged() for conv_crit in self.convergence_criteria_list])
if is_converged:
if self.echo_level > 0:
cs_tools.cs_print_info(self._ClassName(), colors.green("### CONVERGENCE WAS ACHIEVED ###"))
self.__CommunicateIfTimeStepNeedsToBeRepeated(False)
return True
if k+1 >= self.num_coupling_iterations:
if self.echo_level > 0:
cs_tools.cs_print_info(self._ClassName(), colors.red("XXX CONVERGENCE WAS NOT ACHIEVED XXX"))
self.__CommunicateIfTimeStepNeedsToBeRepeated(False)
return False
# if it reaches here it means that the coupling has not converged and this was not the last coupling iteration
self.__CommunicateIfTimeStepNeedsToBeRepeated(True)
# do relaxation only if this iteration is not the last iteration of this timestep
for conv_acc in self.convergence_accelerators_list:
conv_acc.ComputeAndApplyUpdate()
def Check(self):
super().Check()
if len(self.convergence_criteria_list) == 0:
raise Exception("At least one convergence criteria has to be specified")
# TODO check if an accelerator was specified for a field that is manipulated in the input!
for conv_crit in self.convergence_criteria_list:
conv_crit.Check()
for conv_crit in self.convergence_accelerators_list:
conv_crit.Check()
@classmethod
def _GetDefaultParameters(cls):
this_defaults = KM.Parameters("""{
"convergence_accelerators" : [],
"convergence_criteria" : [],
"num_coupling_iterations" : 10
}""")
this_defaults.AddMissingParameters(super()._GetDefaultParameters())
return this_defaults
def __CommunicateIfTimeStepNeedsToBeRepeated(self, repeat_time_step):
# Communicate if the time step needs to be repeated with external solvers through IO
export_config = {
"type" : "repeat_time_step",
"repeat_time_step" : repeat_time_step
}
for solver in self.solver_wrappers.values():
solver.ExportData(export_config)
|
986,769 | 452edc0332c51badc58c8ba351b537b2722135da | from Player import *
import random
import copy
WAN = "🀇🀈🀉🀊🀋🀌🀍🀎🀏" # 0-8
TIAO = "🀐🀑🀒🀓🀔🀕🀖🀗🀘" # 9-17
TONG = "🀙🀚🀛🀜🀝🀞🀟🀠🀡" # 18-26
ELSE = "🀀🀁🀂🀃🀄🀅🀆" # 27-33
DICT = dict(zip(WAN + TIAO + TONG + ELSE, range(34)))
HILL = list(WAN * 4 + TIAO * 4 + TONG * 4 + ELSE * 4)
class AI(Bot):
def __init__(self, NAME='AI'):
super().__init__(NAME=NAME)
self.last_ting_count = 0
self.chi_num = 0
# TODO AI 强化
def action_play(self):
hand = copy.deepcopy(self.hand)
m = 0
if not self.face_down.is_empty():
choose = random.choice(self.hand)
for i in hand.set():
hand.remove(i)
l_t = self.get_ting_list(hand, self.face_down)
c = self.count_ting(l_t, self.face_down)
if c > m:
m = c
choose = i
hand.append(i)
if m > self.last_ting_count:
self.last_ting_count = m
if self.ting:
return self.hand.index(choose)
p = PaiList([i for i in self.hand if i.kind == 'P']).sorted()
s = PaiList([i for i in self.hand if i.kind == 'S']).sorted()
m = PaiList([i for i in self.hand if i.kind == 'M']).sorted()
f = PaiList([i for i in self.hand if i.kind == 'F']).sorted()
y = PaiList([i for i in self.hand if i.kind == 'Y']).sorted()
def r_dup(s, n):
for i in s.set():
c = s.count(i)
if c == n:
for j in range(c):
s.remove(i)
def r_shunzi(s):
for i in s.set():
if i in s and i - 1 in s and i + 1 in s:
s.remove(i)
s.remove(i - 1)
s.remove(i + 1)
if i in s and i - 2 in s and i - 1 in s:
s.remove(i)
s.remove(i - 1)
s.remove(i - 2)
if i in s and i + 1 in s and i + 2 in s:
s.remove(i)
s.remove(i + 1)
s.remove(i + 2)
def r_shunzi_possible(s):
for i in s.set():
if i in s and i - 2 in s:
s.remove(i)
s.remove(i - 2)
if i in s and i - 1 in s:
s.remove(i)
s.remove(i - 1)
if i in s and i + 1 in s:
s.remove(i)
s.remove(i + 1)
if i in s and i + 2 in s:
s.remove(i)
s.remove(i + 2)
# 先考虑字牌
r_dup(f, 3)
r_dup(f, 2)
r_dup(y, 3)
r_dup(y, 2)
if len(f) > 0:
k = random.random()
if k >= 0.1:
choose = random.choice(f)
return self.hand.index(choose)
if len(y) > 0:
k = random.random()
if k >= 0.1:
choose = random.choice(y)
return self.hand.index(choose)
# 去顺子
choose_list = []
r_shunzi(m)
choose_list.append(copy.deepcopy(m))
r_shunzi(s)
choose_list[0].extend(s)
r_shunzi(p)
choose_list[0].extend(p)
# 再去刻子
r_dup(m, 3)
choose_list.append(copy.deepcopy(m))
r_dup(s, 3)
choose_list[1].extend(s)
r_dup(p, 3)
choose_list[1].extend(p)
# 再去雀头
r_dup(m, 2)
choose_list.append(m)
r_dup(s, 2)
choose_list[2].extend(s)
r_dup(p, 2)
choose_list[2].extend(p)
# 再去可能是顺子的
r_shunzi_possible(m)
choose_list.append(m)
r_shunzi_possible(s)
choose_list[3].extend(s)
r_shunzi_possible(p)
choose_list[3].extend(p)
if len(choose_list[3]) != 0:
choose = random.choice(choose_list[3])
elif len(choose_list[2]) != 0:
choose = random.choice(choose_list[2])
elif len(choose_list[1]) != 0:
choose = random.choice(choose_list[1])
elif len(choose_list[0]) != 0:
choose = random.choice(choose_list[0])
else:
choose = random.choice(hand)
return self.hand.index(choose)
def action_hu(self):
return True
def action_chigang(self, item):
return True
def action_zigang(self, item):
return True
def action_jiagang(self, i, j):
"""
:param i: 能加杠的牌在hand的位置
:param j: 碰的牌堆在side的位置
:return:
"""
return True
def action_peng(self, item):
return True
def action_chi(self, it, chi):
"""
:param it: 能吃的牌 Pai
:param chi: 手牌中能与能吃的牌组合的牌的组合的 list
:return:
"""
self.chi_num = 0
t = it.kind
L = PaiList([i for i in self.hand if i.kind == t]).sorted()
for i in chi:
if i[0] == i[1] - 1:
if i[0] - 1 in L or i[1] + 1 in L:
return False
if i[0] == i[1] - 2:
if i[0] - 1 in L or i[1] + 1 in L:
self.chi_num = 0
else:
self.chi_num = chi.index(i)
return True
return True
def action_chiwhich(self, l_chi):
return l_chi.index(random.choice(l_chi))
def count_ting(self, l, h):
count = 0
for i in l:
count += h.count(i)
return count
def get_ting_list(self, hand, h):
li = PaiList()
for i in h.set():
hand.append(i)
if self.hulemei(hand):
li.append(i)
hand.remove(i)
li.sorted()
return li
def restart(self):
super().restart()
self.last_ting_count = 0
self.chi_num = 0
if __name__ == '__main__':
p = AI()
# p.hand = '🀋 🀏 🀑 🀒 🀕 🀗 🀘 🀙 🀛 🀝 🀡 🀁 🀆 🀈'.split(' ')
p.hand = PaiList([S(2), P(6), M(6), P(7), S(7), M(7), P(8), M(8), S(9), S(2), S(2)])
p.sort()
print(p.hand)
print(p.hu())
|
986,770 | afdb745831c4cb78a59cb405f83b13c8e5361e45 | import math, gs
''' define a series of functions of general applicability to processing yapseq data: '''
aa_charged_positive = ['R','H','K']
aa_charged_negative = ['D','E']
aa_polar_uncharged = ['S','T','N','Q']
aa_hydrophobic = ['A','I','L','M','F','W','Y','V']
aa_special = ['C','G','P']
aas = aa_charged_positive + aa_charged_negative + aa_polar_uncharged + aa_hydrophobic + aa_special
aa_small = ['A','C','D','G','N','P','S','T','V']
aa_large = list(set(aas).difference(set(aa_small)))
''' define a function to build a dictionary of YapSeq input lines '''
def build(input_file):
output_dict = {}
input_key = open(input_file)
header = input_key.readline()
input_line = input_key.readline()
while input_line:
input_items = input_line.rstrip('\n').split('\t')
lineID = input_items[0]
if not lineID in output_dict:
output_dict[lineID] = input_items[1:]
else:
print "ERROR: ID is not unique to line in file"
input_line = input_key.readline()
return output_dict
''' define a function to build a dictionary of the mutation frequency spectrum per position '''
def build_unlinked_dict(input_file, mode=""):
output_dict = {}
input_lines = open(input_file).readlines()
items = input_lines.pop(0).rstrip().split('\t')[1:]
for input_line in input_lines:
if mode == "NA-fix":
input_line = input_line.replace("NA", "0")
input_values = input_line.rstrip('\n').split('\t')
pos = int(input_values.pop(0))
output_dict[pos] = {}
k = 0
for item in items:
output_dict[pos][item] = float(input_values[k])
k += 1
return output_dict
''' define a function to build a dictionary of the mutation frequency spectrum per position '''
def build_frequency_dict(input_file, mode=""):
output_dict = {}
input_lines = open(input_file).readlines()
for pos in range(0, len(input_lines)-1):
output_dict[pos] = {}
items = input_lines.pop(0).rstrip('\n').split('\t')
items.pop(0)
for input_line in input_lines:
if mode == "NA-fix":
input_line = input_line.replace("NA", "0")
input_values = input_line.rstrip('\n').split('\t')
pos = int(input_values.pop(0))
k = 0
for item in items:
output_dict[pos][item] = float(input_values[k])
k += 1
return output_dict
''' define a function to build a tally of sequences observed from filtered reads'''
def build_tally_dict(input_file):
properties_dict = {}
tally_dict = {}
input_key = open(input_file)
header = input_key.readline()
input_line = input_key.readline()
unique_data = {}
unique_seqs = 0
reads = 0
while input_line:
readID, sequence, match_count, mutation_count, mutation_location, mutation_identity, max_mutation_run = input_line.rstrip('\n').split('\t')
reads += 1
if not mutation_location in tally_dict:
tally_dict[mutation_location] = {}
properties_dict[mutation_location] = {}
if mutation_identity in tally_dict[mutation_location]:
tally_dict[mutation_location][mutation_identity] += 1
else:
tally_dict[mutation_location][mutation_identity] = 1
properties_dict[mutation_location][mutation_identity] = [sequence, match_count, mutation_count, mutation_location, mutation_identity, max_mutation_run]
unique_seqs += 1
unique_data[reads] = unique_seqs
input_line = input_key.readline()
return tally_dict, properties_dict, unique_data
''' define a function that builds a dictionary representation of a column of data '''
def build_value_dict(input_file, id_index, value_index, mode):
value_dict = {}
input_key = open(input_file)
header = input_key.readline()
input_line = input_key.readline()
if mode == "str":
def format(x):
return x
elif mode == "float":
def format(x):
return float(x)
elif mode == "int":
def format(x):
return int(x)
while input_line:
input_items = input_line.rstrip('\n').split('\t')
value_dict[input_items[id_index]] = format(input_items[value_index])
input_line = input_key.readline()
return value_dict
''' define a function that builds a dictionary representation of 'mapCounts.py' output '''
def build_norm_dict(input_file):
return build_value_dict(input_file, 0, 7, "float")
''' define a function that builds a dictionary representation of 'mapCounts.py' output '''
def build_count_dict(input_file):
return build_value_dict(input_file, 0, 7, "int")
''' define a function that builds a dictionary representation of log2ratios from 'mapRatios.py' output '''
def build_log2ratio_dict(input_file):
return build_value_dict(input_file, 0, 7, "float")
''' define a function that normalizes the counts in a counts dictionary '''
def norm_count_dict(count_dict):
norm_dict = {}
total = 0
for seqID in count_dict:
total += count_dict[seqID]
for seqID in count_dict:
norm_dict[seqID] = float(count_dict[seqID])/total
return norm_dict
''' define a function that returns the ratio between two frequency dictionaries '''
def gen_ratio_dict(A_dict, B_dict):
ratio_dict = {}
for seqID in set(A_dict).intersection(set(B_dict)):
ratio_dict[seqID] = float(A_dict[seqID])/B_dict[seqID]
return ratio_dict
''' define a function that estimates the ratio between two count dictionaries, uses fake 0.5 reads '''
def fix_ratio_dict(A_dict, B_dict, A_sum, B_sum):
ratio_dict = {}
for seqID in A_dict:
A_norm = float(A_dict[seqID])/A_sum
if seqID in B_dict:
B_norm = float(B_dict[seqID])/B_sum
else:
B_norm = float(0.5)/B_sum
ratio_dict[seqID] = float(A_norm)/B_norm
return ratio_dict
''' define a function that returns the log2-ratio between two frequency dictionaries '''
def gen_log2ratio_dict(A_dict, B_dict):
ratio_dict = {}
for seqID in set(A_dict).intersection(set(B_dict)):
ratio_dict[seqID] = math.log(float(A_dict[seqID])/B_dict[seqID],2)
return ratio_dict
''' define a function that print amino acid codes for use with R: '''
def printAAtable(filename, stop=""):
f = open(filename, "w")
print >>f, "\t".join(["one.letter","three.letter","name"])
names = ""
codes = ""
for aa in sorted(gs.aa_1code_3code_dict.keys()):
print >>f, "\t".join([aa, gs.aa_1code_3code_dict[aa], gs.aa_1code_name_dict[aa].replace(" ","_")])
names += '"' + gs.aa_1code_name_dict[aa] + '",'
codes += '"' + gs.aa_1code_3code_dict[aa] + '",'
if not stop == "":
print >>f, "\t".join([stop,"Stop","Stop"])
names += '"Stop",'
codes += '"Stop",'
print names
print codes
f.close()
def printReference(infile):
f1 = open("wildtype_1code.txt", "w")
f3 = open("wildtype_3code.txt", "w")
fn = open("wildtype_names.txt", "w")
reference = open("../Python/input/" + infile).read().rstrip()
print >>f1, "\t".join(["position", "variable", "value"])
print >>f3, "\t".join(["position", "variable", "value"])
print >>fn, "\t".join(["position", "variable", "value"])
k = 0
for aa in reference:
print >>f1, "\t".join([str(k), aa, "0"])
print >>f3, "\t".join([str(k), gs.aa_1code_3code_dict[aa], "0"])
print >>fn, "\t".join([str(k), gs.aa_1code_name_dict[aa].replace(" ","_"), "0"])
k += 1
f1.close()
f3.close()
fn.close() |
986,771 | 562c4640f14f35a2562d9193fe5f1e964b252e95 | __author__ = 'Amy Shi, Amber Lee, Fred Ayi-Quaye'
from tkinter import *
root = Tk()
root.title("Voronoi Painting")
root.geometry("500x500")
root.mainloop()
|
986,772 | fd8a234bf2de10a09c8546ec2c55d1e9a73609e8 | import django_tables2 as tables
from django.contrib.auth import get_user_model
from django.utils.html import format_html, format_html_join
from django.utils.safestring import mark_safe
from django.utils.translation import gettext as _
from django_hosts.resolvers import reverse
import config.hosts
from transit_odp.common.tables import GovUkTable
from transit_odp.organisation.models import DatasetSubscription, Organisation
User = get_user_model()
RESEND_CLASS = "resend-checkbox"
CLICKER_SCRIPT = (
f"document"
f'.getElementsByClassName("{RESEND_CLASS}")'
f".forEach("
f"function(elem){{elem.checked = this.checked}}.bind(this)"
f")"
)
class GovUKCheckBoxColumn(tables.CheckBoxColumn):
in_error = False
@property
def header(self):
label_css_classes = "govuk-checkboxes__label"
if self.in_error:
label_css_classes += " invite-error"
return mark_safe(
'<div class="govuk-checkboxes__item">'
f"{super().header}"
f'<label class="govuk-label {label_css_classes}" '
'for="select-all">'
'<span class="govuk-visually-hidden">'
"Resend all organisation invites"
"</span>"
"</label>"
"</div>",
)
class OrganisationTable(GovUkTable):
name = tables.Column(
verbose_name="Name", attrs={"td": {"class": "organisation_name_cell"}}
)
registration_complete = tables.Column(verbose_name="Status")
invite_sent = tables.Column(
verbose_name="Date invited", order_by=("registration_complete", "invite_sent")
)
last_active = tables.Column(verbose_name="Last active")
resend_invites = GovUKCheckBoxColumn(
empty_values=(),
attrs={
"th__input": {
"form": "ignore",
"onChange": CLICKER_SCRIPT,
"class": "govuk-checkboxes__input",
"id": "select-all",
},
"td": {"class": "govuk-checkboxes--small"},
"th": {"class": "govuk-table__header govuk-checkboxes--small"},
},
)
class Meta(GovUkTable.Meta):
model = Organisation
exclude = (
"id",
"created",
"modified",
"short_name",
"key_contact",
"is_active",
"licence_required",
)
sequence = (
"resend_invites",
"name",
"registration_complete",
"invite_sent",
"last_active",
)
def __init__(self, *args, in_error=False, checked_ids=None, **kwargs):
self._checked_ids = checked_ids or []
self._in_error = in_error
self.base_columns["resend_invites"].in_error = in_error
super().__init__(*args, **kwargs)
def render_resend_invites(self, record=None):
if record is not None:
# We need the label so we can get the clever govuk-frontend checkbox css
label_css_classes = "govuk-checkboxes__label"
if self._in_error:
label_css_classes += " invite-error"
return format_html(
'<div class="govuk-checkboxes__item">'
'<input type="checkbox" '
'id="resend-invite-org-{name}"'
'class="{css_class} govuk-checkboxes__input" '
'name="invites" '
'value="{name}" '
"{checked}>"
"</input>"
'<label class="govuk-label {label_css_classes}" '
'for="resend-invite-org-{name}">'
'<span class="govuk-visually-hidden">'
"Resend invite for {org_name}"
"</span>"
"</label>"
"</div>",
css_class=RESEND_CLASS,
label_css_classes=label_css_classes,
checked="checked" if record.id in self._checked_ids else "",
name=record.id,
org_name=record.name,
)
return ""
def render_invite_sent(self, record=None):
if not record.registration_complete:
return f"Invite sent - {record.invite_sent: %d/%m/%Y}"
return ""
def render_last_active(self, record=None):
if record is not None:
return f"{record.last_active: %d %B %Y %-I:%M%p}"
def render_name(self, **kwargs):
value = kwargs["value"]
record = kwargs["record"]
link = reverse(
"users:organisation-detail",
kwargs={"pk": record.id},
host=config.hosts.ADMIN_HOST,
)
return format_html(
"""
<a class='govuk-link' href='{link}'>{value}</a>
""",
link=link,
value=value,
)
def render_registration_complete(self, **kwargs):
record = kwargs["record"]
value = kwargs["value"]
if not value:
return "Pending Invite"
elif record.is_active:
return "Active"
else:
return "Inactive"
def render_actions(self, **kwargs):
record = kwargs["record"]
assert isinstance(record, Organisation)
items = []
if record.registration_complete is False:
url = reverse(
"users:re-invite",
kwargs={"pk": record.id}, # organisation_id
host=config.hosts.ADMIN_HOST,
)
items.append(
format_html(
"<a class='govuk-link' href='{link}'>{text}</a>",
link=url,
text=_("Re-send invitation"),
)
)
if items:
items_html = format_html_join("\n", "<li>{}</li>", (items,))
return format_html(
"""
<ul class="organisation-table__actions">
{items}
</ul>
""",
items=items_html,
)
else:
return ""
class FeedNotificationTable(GovUkTable):
name = tables.Column(verbose_name="Data set")
class Meta(GovUkTable.Meta):
model = DatasetSubscription
class ConsumerTable(GovUkTable):
email = tables.Column(verbose_name="Email")
is_active = tables.Column(verbose_name="Status")
last_login = tables.Column(verbose_name="Last active")
def render_is_active(self, value=None, **kwargs):
if value:
return "Active"
return "Inactive"
def render_last_login(self, value=None):
if value is not None:
return f"{value: %d %B %Y %-I:%M%p}"
return ""
def render_email(self, record=None, value=None):
link = reverse(
"users:consumer-detail",
kwargs={"pk": record.id},
host=config.hosts.ADMIN_HOST,
)
anchor = "<a class='govuk-link' href='{link}'>{text}</a>"
return format_html(anchor, link=link, text=value)
class Meta(GovUkTable.Meta):
model = User
fields = ("email",)
class AgentsTable(GovUkTable):
class Meta(GovUkTable.Meta):
model = User
fields = ("agent_organisation", "email")
agent_organisation = tables.Column(
orderable=False, verbose_name="Agent Organisation"
)
email = tables.Column(orderable=False, verbose_name="Email")
details = tables.Column(
orderable=False,
linkify=lambda record: reverse(
"users:agent-detail", kwargs={"pk": record.id}, host=config.hosts.ADMIN_HOST
),
)
class AgentOrganisationsTable(GovUkTable):
class Meta(GovUkTable.Meta):
model = Organisation
fields = ("name",)
name = tables.Column(
orderable=False,
verbose_name="Organisation",
linkify=lambda record: reverse(
"users:organisation-detail",
kwargs={"pk": record.id},
host=config.hosts.ADMIN_HOST,
),
)
key_contact = tables.Column(
orderable=False, verbose_name="Key contact", accessor="key_contact__email"
)
|
986,773 | f54a02a48f6a521e7d8b9a44d84baf1cddb90df2 | import random
def left():
l = ["You went to the river...Do you want to go across it or walk along the banks of the river (across/walk) ?",
"You saw a butterfly...follow it or leave it (follow/leave) ?",
"You saw your friend trapped Help him/her or leave it (help/leave) ?",
]
return random.choice(l)
def right():
r = ["You fell from a cliff and died :( ",
"Jungle or a beach (jungle/beach) ?",
"You met a Bear....run or pretend to be dead (run/dead) ?",
]
return random.choice(r)
name = input("Please enter your name:")
age = int(input(("Please enter your age:")))
if age < 18:
print("You are not eligible to play the game :(")
elif age >= 18:
print("You are Eligible :)")
ch = input("Do You want to play ?").lower()
if ch == "yes":
right_or_left = input("Enter your first choice: right or left ?").lower()
if right_or_left == "left":
l1 = left()
if "river" in l1:
print(l1)
choice = input()
if choice == "across":
across = ["You went across and found an abandoned house.... go inside or leave it (in/leave) ?",
"You met your soulmate and you lived happily after :)",
"You got hyperthermia while swimming across the river and you died :(",
]
l2 = random.choice(across)
if "abandoned" in l2:
choice = input().lower()
if choice == "in":
print("You went inside a witch's house and she ate you !\n" + "Better Luck next time....")
elif choice == "leave":
print("A wild animal suddenly appeared Run to the abanoned house or stand there (run/stand) ?")
choice = input().lower()
if choice == "run":
print("You went inside a witch's house and she ate you !\n" + "Better Luck next time....")
elif choice == "stand":
print("The animal ate you !\n"+ "Better Luck next time.....")
else:
print(l2)
elif choice == "walk":
print("There was a family of corocodiles waiting for you along the banks of the river :(")
elif "butterfly" in l1:
print(l1)
choice = input().lower()
if choice == "follow":
b = ["You followed it into the deep jungle and you got lost :(",
"While following it you fell into a trap :(",
]
l2 = random.choice(b)
print(l2)
elif choice == "leave":
b = ["You saw a tree and you feel tired rest under it or keep walking (rest/walk) ?"]
print(b[0])
choice = input().lower()
if choice == "rest":
print("While you were resting a snike bit you and you died :(")
elif choice == "walk":
w = ["You died due to intensive walking for a long period....",
"You finally reached your destination....Congractulations You won !!!"
]
l2 = random.choice(w)
print(l2)
elif "friend" in l1:
print(l1)
choice = input().lower()
if choice == "help":
print("When you went to help your friend you found out it was god in disguise testing you and granted you eternal peace :)")
elif choice == "leave":
print("Your friend was just pretending to be trapped to test you and you failed in that :(")
elif right_or_left == "right":
r1 = right()
print(r1)
if "fell" in r1:
print("Better Luck next time !!!")
elif "jungle" in r1:
choice = input().lower()
if choice == "jungle":
print(random.choice(["You went inside the jungle and got eaten up by wild animals", "Due to high humidity of the jungle you died :(", "You found a tree house there and lived happily after :)"]))
elif choice == "beach":
print("There was lighting at the beach which caused tsunami and you died !!!" )
elif "Bear" in r1:
choice = input().lower()
if choice == "run":
print("The bear caught you and ate you !!")
elif choice == "dead":
print("You fooled the bear, Congractulations")
else:
print("Bye, Have a great day !")
|
986,774 | f32fb8f9980e8e08471f2fe997a38a5022ae2c0e | # Minhas variáveis
salario = 3450.45
despesas = 2456.2
"""
A ideia é calcular o
quanto vai sobrar no
final do mês!
"""
# Linha 1
# Linha 2
# Linha 3
print('Fim')
|
986,775 | 89144fba427cfe0da982325be3d1592f07e4a018 | from django.shortcuts import render
from django.http import HttpResponse
from shop.models import product
def index(request):
products=product.objects.all()
n=len(products)
nslides=n//4+ceil(n/4-n//4)
params={'products':products, 'no_of_slides':nslides , 'range':range(1,nslides)}
return render(request, 'shop/indexshop.html',params)
def about(request):
return HttpResponse('about page')
def contact(request):
return HttpResponse('contact')
def tracker(request):
return HttpResponse('tracker page')
def about(request):
return HttpResponse('about page')
def productview(request):
return HttpResponse('product view page')
def checkout(request):
return HttpResponse('checkout page')
def search(request):
return HttpResponse('search page') |
986,776 | b9b2adc9bb3831f5d0216101d6afbab4b4724873 | from .Mainloop import Mainloop
class State():
def __init__(self, name, period, onStartFunc, onLoopFunc, onEndFunc, onEvents, after, cancel):
self.name = name
self.mainloop = Mainloop(period, onStartFunc, onLoopFunc, onEndFunc, after, cancel)
self.onEvents = onEvents
def start(self):
self.mainloop.start()
def end(self):
self.mainloop.end()
def event(self, eventName, eventDetails):
self.onEvents.get(eventName, lambda eventDetails: 0)(eventDetails)
class StateManager():
def __init__(self, after, cancel, period=50):
self.after = after
self.cancel = cancel
self.period = period
self.states = {}
self.runningState = None
def event(self, eventName, eventDetails):
if self.runningState != None:
self.states[self.runningState].event(eventName, eventDetails)
def addState(self, name, onStartFunc, onLoopFunc, onEndFunc, onEvents, period=None):
period = self.period if period == None else period
self.states[name] = State(name, period, onStartFunc, onLoopFunc, onEndFunc, onEvents, self.after, self.cancel)
def startState(self, state):
self.runningState = state
self.states[self.runningState].start()
def endState(self):
if self.runningState != None:
self.states[self.runningState].end()
self.runningState = None
def setState(self, state):
self.endState()
self.startState(state)
|
986,777 | 862bf1e59090f22ae0c01741a838fde91527210a | # -*- coding:utf-8 -*-
"""
Python 3.7
Author:Spring
Time: 2022/3/29 6:50 PM
"""
import shutil
import zipfile
import os
import datetime
from config import settings
# shutil.make_archive('/Volumes/HDD/Code/Python/FridayDemo/Friday/App/ApiAuto/Debug/', "zip", root_dir='/Users/mac-mini/Desktop/约面0330')
zip_dir = '/Volumes/HDD/Code/Python/FridayDemo/Friday/App/ApiAuto/Debug/'
new_file_path = os.path.join(zip_dir, 'test1.zip')
zip_file_path = '/Volumes/HDD/Code/Python/FridayDemo/Friday/App/ApiAuto/Debug/'
create_zip_file = zipfile.ZipFile(new_file_path, mode='w', compression=zipfile.ZIP_DEFLATED)
# create_zip_file.write(os.path.join(zip_file_path, 'SendEmailTest.py'), 'SendEmailTest.py')
# datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
for dir_path, dir_name, file_names in os.walk(settings.ALLURE_REPORT_DIR_PATH):
file_path = dir_path.replace(settings.ALLURE_REPORT_DIR_PATH, '')
file_path = file_path and file_path + os.sep or ''
# print(file_path)
# print(dir_name)
for file_name in file_names:
create_zip_file.write(os.path.join(dir_path, file_name), (file_path + file_name))
# print(os.path.join(dir_path, file_name))
#
# print("-------------")
# print(file_path + file_name)
# print("-----分割线-----")
|
986,778 | 1f05c963b629424819699087d4c7614791c6b93b | a = 0
with open('azs.txt', "r+") as azs_file:
for line in azs_file.readlines():
a += 1
print(a) |
986,779 | 90d855f034794e794df4b10c00735926c65c7e0d | # ========================================================================= #
# One Layer Nerual Network to make
# The 4 flower attributes are
# 1 sepal length
# 2.sepal width
# 3.pedal length
# 4.pedal width
# Goal: Predict (4) from 1-3 #
# #
# ========================================================================= #
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.python.framework import ops
from sklearn.datasets import load_iris
ops.reset_default_graph()
sess = tf.Session()
#data
iris = load_iris()
x_vals = np.array([x[0:3] for x in iris.data]) #[[ 5.1 3.5 1.4]
y_vals = np.array([x[3] for x in iris.data]) #[0.2
#print(x_vals) #['tar' 'tar' 'DES' 'dat' 'fea']
#print(y_vals) #['g' 'g' 'C' 'a' 't']
#make result Reproduce
seed = 2
tf.set_random_seed(seed)
np.random.seed(seed)
#splite the data into train/set 80%/20%
train_indice = np.random.choice(len(x_vals),round(len(x_vals)*0.8),replace=False)
test_indice = np.array(list(set(range(len(x_vals)))-set(train_indice))) #set - set
x_vals_train = x_vals[train_indice]
x_vals_test = x_vals[test_indice]
y_vals_train = y_vals[train_indice]
y_vals_test = y_vals[test_indice]
#Place holder
x_data = tf.placeholder(shape=[None, 3], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)
batch_size = 50
#Normalize by column (min-max norm)
def normalize_cols(m):
col_max = m.max(axis=0)
col_min = m.min(axis=0)
return (m-col_min)/(col_max-col_min)
x_vals_train = np.nan_to_num(normalize_cols(x_vals_train))
x_vals_test = np.nan_to_num(normalize_cols(x_vals_test))
#hidden layuer_nodes
hidden_layer_nodes= 10
A1 = tf.Variable(tf.random_normal(shape=[3,hidden_layer_nodes])) #input to hidden nodes
b1 = tf.Variable(tf.random_normal(shape=[hidden_layer_nodes])) #one bias to each hidden nodes
A2 = tf.Variable(tf.random_normal(shape=[hidden_layer_nodes,1])) #hidden nodes -> 1 output
b2 = tf.Variable(tf.random_normal(shape=[1])) #1 bias for the output
#Mode Operation y = mx+b
hidden_output= tf.nn.relu(tf.add(tf.matmul(x_data,A1),b1))
final_output = tf.nn.relu(tf.add(tf.matmul(hidden_output,A2),b2))
#lose function
loss = tf.reduce_mean(tf.square(y_target- final_output))
#Optimizer
my_opt = tf.train.GradientDescentOptimizer(0.050)
train_step = my_opt.minimize(loss)
sess.run(tf.global_variables_initializer())
#train loop
loss_vec =[]
test_vec =[]
for i in range(500):
rand_index = np.random.choice(len(x_vals_train),size=batch_size )
rand_x = x_vals_train[rand_index]
rand_y =np.transpose([y_vals_train[rand_index]])
sess.run(train_step,feed_dict={x_data: rand_x, y_target: rand_y})
temp_loss =sess.run(loss,feed_dict={x_data: rand_x, y_target: rand_y})
loss_vec.append(np.square(temp_loss))
test_temp_loss = sess.run(loss,feed_dict={x_data: x_vals_test, y_target: np.transpose([y_vals_test])})
test_vec.append(np.square(test_temp_loss))
if (i+1)%50 ==0:
print('Generation: ' + str(i+1)+ ' . Loss = '+str(temp_loss))
plt.plot(loss_vec,'k--',label='Train loss')
plt.plot(test_vec,'r--',label='Test loss')
plt.title('Loss per Generation')
plt.legend(loc='upper right')
plt.xlabel('Generation')
plt.ylabel('Loss')
plt.show() |
986,780 | 392ec887eee6c0d0b2b0639cb58b76d9290fe658 | from django.contrib import admin
from .models import Customer,Order
class CustomerAdmin(admin.ModelAdmin):
list_display = ("Customer_Id","FirstName","LastName","Email","Phone","City","PinCode")
empty_value_display = "NULL"
class OrderAdmin(admin.ModelAdmin):
list_display = ("Order_Id","FK_Customer__Id", "Date", "TotalAmount","IsCash", "IsCheque", "BankName", "ChequeNo","IsOnline","PlatformName","TransactionId")
empty_value_display = "NULL"
def FK_Customer__Id(self, instance):
return instance.FK_Customer_Id.Customer_Id
admin.site.register(Customer,CustomerAdmin)
admin.site.register(Order,OrderAdmin)
|
986,781 | beb199180a675ae6accf93be7418e760e33164b7 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def my_pgcd(a, b) :
if(a%b==0) : return b
else : return my_pgcd(b, a%b)
def my_inverse(a, N):
r0, r1 = a, N
u0, u1 = 1, 0 #u0=b
v0, v1 = 0, 1
while(not(r1==0)):
q = int(r0/r1)
r, u, v = r1, u1, v1
r1 = r0 - q * r1
u1 = u0 - q * u1
v1 = v0 - q * v1
r0, u0, v0= r, u, v
if (r0 == 1):
return u0
raise ValueError(a,' et ', N, ' ne sont pas premiers entre-eux')
def my_binary_decomposition(n):
a=[]
def my_binary_decomposition_aux(n, a):
if(n>0) :
a.append(n%2)
return my_binary_decomposition_aux(int(n/2), a)
return a
return my_binary_decomposition_aux(n, a)
def my_expo_mod(g,n,N):
h=1
a=my_binary_decomposition(n)
for i in range (len(a)-1, -1, -1):
h=(h**2)%N
if (a[i]==1):
h=(h*g)%N
return h |
986,782 | dd9825ab676b672b9226a9ee7986a74a1b2e47c0 | #! /usr/bin/env python3
# this script returns the fibonacci number at a specified position in the fibonacci sequence
import argparse
def get_args():
#create an argument parser object
parser = argparse.ArgumentParser(description = 'this script returns the fibonacci number at a specified position')
# add positional arguments, i.e., the required input
#parser.add_argument( "-number", "--num", help="the fibonacci number you wish to calculate", type=int)
# add positional arguments, i.e., the required input
parser.add_argument("num", help="the fibonacci number you wish to calculate", type=int)
# add optional arguments
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true", help="print verbose output")
group.add_argument("-s", "--simple", action="store_true", help="print simple output (default)")
#action="store_true" makes the default false?
# parse the command line arguments
return parser.parse_args()
def fib(n):
# calculate the fibonacci number
a, b = 0, 1
for i in range(n):
a,b = b, a+b
return(a)
def print_output(position, fib_num):
#print the desired output
if args.verbose:
#verbose output
print("for position", position, str(args.num), "the fibonacci numer is", fib_num)
else:
#simple output
print(str(args.num), fib_num)
def main():
fib_num = fib(args.num)
print_output(args.num, fib_num)
# get the arguments before calling main
args = get_args()
# execute the program by calling main
if __name__== "__main__":
main()
#functions for:
#parsing fasta
#parsing gff
#function for gc content?
# function for reverse complement of a sequence
# test for (+) or (-)?
#will use the seqIO |
986,783 | 80be7095f6d13fd93f501cd326e7ccceeb1262f3 | # -*- coding: utf-8 -*-
#
# inspired from:
# https://kitware.github.io/vtk-examples/site/Python/PolyData/ExtractSelection/
# https://vtk.org/Wiki/VTK/Examples/Cxx/Picking/CellPicking
import vtk
colors = vtk.vtkNamedColors()
# print(colors.GetColorNames())
# see also https://vtk.org/Wiki/VTK/Examples/Python/Visualization/VTKNamedColorPatches_html
from mytools import *
from myinteractor import *
from myview import *
def main():
# ugrid = loadUGrid('Dolicorhynchops_coarse.vtu')
ugrid = loadUGrid('grid.vtu')
# saveUGrid(ugrid, 'grid.vtu')
print('There are %s input points' % ugrid.GetNumberOfPoints())
print('There are %s input cells' % ugrid.GetNumberOfCells())
# mesh
meshMapper = vtk.vtkDataSetMapper()
meshMapper.SetInputData(ugrid)
meshActor = vtk.vtkActor()
meshActor.GetProperty().SetColor(colors.GetColor3d('white'))
meshActor.GetProperty().EdgeVisibilityOn()
meshActor.SetMapper(meshMapper)
# display mesh
view = BasicView()
view.add( [meshActor] )
# cubeAxesActor = vtk.vtkCubeAxesActor()
# cubeAxesActor.SetBounds(ugrid.GetBounds())
# cubeAxesActor.SetCamera(view.ren.GetActiveCamera())
# -- example of callback - rien a voir avec la selection
# print the camaera position for each render
if 0:
def start_callback(caller, ev):
# print('StartEvent')
position = view.ren.GetActiveCamera().GetPosition()
print('StartEvent ({:5.2f}, {:5.2f}, {:5.2f})'.format(*position))
view.ren.AddObserver('StartEvent', start_callback)
view.interact()
if __name__=="__main__":
main()
|
986,784 | 415e6973abb9c2ccc658ba6d88b76a874ee19586 | from django.contrib.auth.models import User
from django.test import TestCase
from dfirtrack_main.models import Os, Osimportname
import urllib.parse
class OsimportnameViewTestCase(TestCase):
""" osimportname view tests """
@classmethod
def setUpTestData(cls):
# create object
os_1 = Os.objects.create(os_name='os_1')
# create object
Osimportname.objects.create(osimportname_name='osimportname_1', osimportname_importer='osimportname_importer_1', os = os_1)
# create user
User.objects.create_user(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
def test_osimportname_list_not_logged_in(self):
""" test list view """
# create url
destination = '/login/?next=' + urllib.parse.quote('/osimportname/', safe='')
# get response
response = self.client.get('/osimportname/', follow=True)
# compare
self.assertRedirects(response, destination, status_code=302, target_status_code=200)
def test_osimportname_list_logged_in(self):
""" test list view """
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# get response
response = self.client.get('/osimportname/')
# compare
self.assertEqual(response.status_code, 200)
def test_osimportname_list_template(self):
""" test list view """
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# get response
response = self.client.get('/osimportname/')
# compare
self.assertTemplateUsed(response, 'dfirtrack_main/osimportname/osimportname_list.html')
def test_osimportname_list_get_user_context(self):
""" test list view """
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# get response
response = self.client.get('/osimportname/')
# compare
self.assertEqual(str(response.context['user']), 'testuser_osimportname')
def test_osimportname_list_redirect(self):
""" test list view """
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# create url
destination = urllib.parse.quote('/osimportname/', safe='/')
# get response
response = self.client.get('/osimportname', follow=True)
# compare
self.assertRedirects(response, destination, status_code=301, target_status_code=200)
def test_osimportname_add_not_logged_in(self):
""" test add view """
# create url
destination = '/login/?next=' + urllib.parse.quote('/osimportname/add/', safe='')
# get response
response = self.client.get('/osimportname/add/', follow=True)
# compare
self.assertRedirects(response, destination, status_code=302, target_status_code=200)
def test_osimportname_add_logged_in(self):
""" test add view """
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# get response
response = self.client.get('/osimportname/add/')
# compare
self.assertEqual(response.status_code, 200)
def test_osimportname_add_template(self):
""" test add view """
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# get response
response = self.client.get('/osimportname/add/')
# compare
self.assertTemplateUsed(response, 'dfirtrack_main/osimportname/osimportname_add.html')
def test_osimportname_add_get_user_context(self):
""" test add view """
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# get response
response = self.client.get('/osimportname/add/')
# compare
self.assertEqual(str(response.context['user']), 'testuser_osimportname')
def test_osimportname_add_redirect(self):
""" test add view """
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# create url
destination = urllib.parse.quote('/osimportname/add/', safe='/')
# get response
response = self.client.get('/osimportname/add', follow=True)
# compare
self.assertRedirects(response, destination, status_code=301, target_status_code=200)
def test_osimportname_add_post_redirect(self):
""" test add view """
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# get object
os_id = Os.objects.get(os_name='os_1').os_id
# create post data
data_dict = {
'osimportname_name': 'osimportname_add_post_test',
'osimportname_importer': 'importer_1',
'os': os_id,
}
# get response
response = self.client.post('/osimportname/add/', data_dict)
# create url
destination = urllib.parse.quote('/osimportname/', safe='/')
# compare
self.assertRedirects(response, destination, status_code=302, target_status_code=200)
def test_osimportname_add_post_invalid_reload(self):
""" test add view """
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# create post data
data_dict = {}
# get response
response = self.client.post('/osimportname/add/', data_dict)
# compare
self.assertEqual(response.status_code, 200)
def test_osimportname_add_post_invalid_template(self):
""" test add view """
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# create post data
data_dict = {}
# get response
response = self.client.post('/osimportname/add/', data_dict)
# compare
self.assertTemplateUsed(response, 'dfirtrack_main/osimportname/osimportname_add.html')
def test_osimportname_edit_not_logged_in(self):
""" test edit view """
# get object
osimportname_1 = Osimportname.objects.get(osimportname_name='osimportname_1')
# create url
destination = '/login/?next=' + urllib.parse.quote('/osimportname/' + str(osimportname_1.osimportname_id) + '/edit/', safe='')
# get response
response = self.client.get('/osimportname/' + str(osimportname_1.osimportname_id) + '/edit/', follow=True)
# compare
self.assertRedirects(response, destination, status_code=302, target_status_code=200)
def test_osimportname_edit_logged_in(self):
""" test edit view """
# get object
osimportname_1 = Osimportname.objects.get(osimportname_name='osimportname_1')
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# get response
response = self.client.get('/osimportname/' + str(osimportname_1.osimportname_id) + '/edit/')
# compare
self.assertEqual(response.status_code, 200)
def test_osimportname_edit_template(self):
""" test edit view """
# get object
osimportname_1 = Osimportname.objects.get(osimportname_name='osimportname_1')
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# get response
response = self.client.get('/osimportname/' + str(osimportname_1.osimportname_id) + '/edit/')
# compare
self.assertTemplateUsed(response, 'dfirtrack_main/osimportname/osimportname_edit.html')
def test_osimportname_edit_get_user_context(self):
""" test edit view """
# get object
osimportname_1 = Osimportname.objects.get(osimportname_name='osimportname_1')
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# get response
response = self.client.get('/osimportname/' + str(osimportname_1.osimportname_id) + '/edit/')
# compare
self.assertEqual(str(response.context['user']), 'testuser_osimportname')
def test_osimportname_edit_redirect(self):
""" test edit view """
# get object
osimportname_1 = Osimportname.objects.get(osimportname_name='osimportname_1')
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# create url
destination = urllib.parse.quote('/osimportname/' + str(osimportname_1.osimportname_id) + '/edit/', safe='/')
# get response
response = self.client.get('/osimportname/' + str(osimportname_1.osimportname_id) + '/edit', follow=True)
# compare
self.assertRedirects(response, destination, status_code=301, target_status_code=200)
def test_osimportname_edit_post_redirect(self):
""" test edit view """
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# get object
os_1 = Os.objects.get(os_name='os_1')
# create object
osimportname_1 = Osimportname.objects.create(
osimportname_name = 'osimportname_edit_post_test_1',
osimportname_importer = 'importer_1',
os = os_1,
)
# create post data
data_dict = {
'osimportname_name': 'osimportname_edit_post_test_2',
'osimportname_importer': 'importer_1',
'os': os_1.os_id,
}
# get response
response = self.client.post('/osimportname/' + str(osimportname_1.osimportname_id) + '/edit/', data_dict)
# create url
destination = urllib.parse.quote('/osimportname/', safe='/')
# compare
self.assertRedirects(response, destination, status_code=302, target_status_code=200)
def test_osimportname_edit_post_invalid_reload(self):
""" test edit view """
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# get object
osimportname_id = Osimportname.objects.get(osimportname_name='osimportname_1').osimportname_id
# create post data
data_dict = {}
# get response
response = self.client.post('/osimportname/' + str(osimportname_id) + '/edit/', data_dict)
# compare
self.assertEqual(response.status_code, 200)
def test_osimportname_edit_post_invalid_template(self):
""" test edit view """
# login testuser
self.client.login(username='testuser_osimportname', password='SU7QGdCzPMBJd3l9URoS')
# get object
osimportname_id = Osimportname.objects.get(osimportname_name='osimportname_1').osimportname_id
# create post data
data_dict = {}
# get response
response = self.client.post('/osimportname/' + str(osimportname_id) + '/edit/', data_dict)
# compare
self.assertTemplateUsed(response, 'dfirtrack_main/osimportname/osimportname_edit.html')
|
986,785 | 6d33c8f26157ab630b38f7bcbf31ec7bcb1a86ca | from common.enum import Enum
_oper_types = ['start', 'stop', 'reload']
OperType = Enum(_oper_types)
|
986,786 | 080a1a13d3ca10813655b7d83e2e243cecfadc42 | class Stack():
def __init__(self):
self.stack = []
def pushCharacter(self, val):
self.stack.append(val)
def popCharacter(self):
return self.stack.pop()
def notEmpty(self):
return len(self.stack) != 0
class Queue():
def __init__(self):
self.queue = []
def enqueueCharacter(self, val):
self.queue.append(val)
def dequeueCharacter(self):
return self.queue.pop(0)
def notEmpty(self):
return len(self.queue) != 0
stk = Stack()
que = Queue()
s = input()
for x in s:
stk.pushCharacter(x)
que.enqueueCharacter(x)
flag = 1
while stk.notEmpty() and que.notEmpty():
if stk.popCharacter() != que.dequeueCharacter():
flag = 0
break
if flag:
print("The word, "+s+", is a palindrome.")
else:
print("The word, "+s+", is not a palindrome.")
|
986,787 | c65ac3390d57625c668ca31e49ea2ec5fb97555c | from typing import Any, Dict, List, Optional
from pystac.utils import StringEnum
class ProviderRole(StringEnum):
"""Enumerates the allows values of the Provider "role" field."""
LICENSOR = "licensor"
PRODUCER = "producer"
PROCESSOR = "processor"
HOST = "host"
class Provider:
"""Provides information about a provider of STAC data. A provider is any of the
organizations that captured or processed the content of the collection and therefore
influenced the data offered by this collection. May also include information about
the final storage provider hosting the data.
Args:
name : The name of the organization or the individual.
description : Optional multi-line description to add further provider
information such as processing details for processors and producers,
hosting details for hosts or basic contact information.
roles : Optional roles of the provider. Any of
licensor, producer, processor or host.
url : Optional homepage on which the provider describes the dataset
and publishes contact information.
extra_fields : Optional dictionary containing additional top-level fields
defined on the Provider object.
"""
name: str
"""The name of the organization or the individual."""
description: Optional[str]
"""Optional multi-line description to add further provider
information such as processing details for processors and producers,
hosting details for hosts or basic contact information."""
roles: Optional[List[ProviderRole]]
"""Optional roles of the provider. Any of
licensor, producer, processor or host."""
url: Optional[str]
"""Optional homepage on which the provider describes the dataset
and publishes contact information."""
extra_fields: Dict[str, Any]
"""Dictionary containing additional top-level fields defined on the Provider
object."""
def __init__(
self,
name: str,
description: Optional[str] = None,
roles: Optional[List[ProviderRole]] = None,
url: Optional[str] = None,
extra_fields: Optional[Dict[str, Any]] = None,
):
self.name = name
self.description = description
self.roles = roles
self.url = url
self.extra_fields = extra_fields or {}
def __eq__(self, o: object) -> bool:
if not isinstance(o, Provider):
return NotImplemented
return self.to_dict() == o.to_dict()
def to_dict(self) -> Dict[str, Any]:
"""Generate a dictionary representing the JSON of this Provider.
Returns:
dict: A serialization of the Provider that can be written out as JSON.
"""
d: Dict[str, Any] = {"name": self.name}
if self.description is not None:
d["description"] = self.description
if self.roles is not None:
d["roles"] = self.roles
if self.url is not None:
d["url"] = self.url
d.update(self.extra_fields)
return d
@staticmethod
def from_dict(d: Dict[str, Any]) -> "Provider":
"""Constructs an Provider from a dict.
Returns:
Provider: The Provider deserialized from the JSON dict.
"""
return Provider(
name=d["name"],
description=d.get("description"),
roles=d.get(
"roles",
),
url=d.get("url"),
extra_fields={
k: v
for k, v in d.items()
if k not in {"name", "description", "roles", "url"}
},
)
|
986,788 | 595b0cbbf7704b0b029e1409e5956e7f863c48e0 | # -*- coding: utf-8 -*-
# VIEWS DA API - UNB ALERTA - REST FRAMEWORK
# Importando generics da rest framework para a criação da APIView
from rest_framework.generics import (
CreateAPIView,
DestroyAPIView,
ListAPIView,
RetrieveAPIView,
RetrieveUpdateAPIView
)
from rest_framework.views import APIView
# Importando os models preestabelecidos pelo Django e os models do UnB Alerta
from django.contrib.auth.models import User, Group
from usuario.models import Usuario
from ocorrencia.models import Categoria, Ocorrencia, Local
# Importando os serializers de cada classe usada
from api.serializers import (
UsuarioSerializer,
OcorrenciaSerializer,
CategoriaSerializer,
UserSerializer,
GroupSerializer,
LocalSerializer
)
# Importando arquivo com as permissões de User
from rest_framework. permissions import (
AllowAny,
IsAuthenticated,
IsAdminUser,
IsAuthenticatedOrReadOnly
)
#from api.permissions import (
# UserIsOwnerOrAdmin
# )
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
# Importando classe password, utilizada para o hashing da senha
from api.password import password
# Outros imports
from django.http import Http404
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import permission_classes
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from django.db import utils
############################ USER ##############################################
# Listagem de Users internos do Django bem quanto seus detalhes.
# Permissão: Só quem tem acesso é o Admin
class UserDetailAPIView(RetrieveAPIView):
'''
Detalhes dos users
'''
queryset = User.objects.all() # Retorna todos os User
serializer_class = UserSerializer # Utiliza a classe serializer User
permission_classes = [IsAdminUser]
class UserListAPIView(ListAPIView):
'''
Lista dos users
'''
queryset = User.objects.all() # Retorna todos os User
serializer_class = UserSerializer # Utiliza a classe serializer User
permission_classes = [IsAdminUser]
############################ GROUP ##############################################
# CRUD Group
# Listagem de Groups internos do Django bem quanto seus detalhes.
# Permissão: Só quem tem acesso é o Admin
class GroupDetailAPIView(RetrieveAPIView):
'''
Detalhes dos grupos de users
'''
queryset = Group.objects.all() # Retorna todos os Groups
serializer_class = GroupSerializer # Utiliza a classe serializer Group
permission_classes = [IsAdminUser] # Só quem tem acesso é o Admin
class GroupListAPIView(ListAPIView):
'''
Lista dos grupos de users
'''
queryset = Group.objects.all() # Retorna todos os Groups
serializer_class = GroupSerializer # Utiliza a classe serializer Group
permission_classes = [IsAdminUser] # Só quem tem acesso é o Admin
############################ USUÁRIO ##############################################
# CRUD Usuário
# Lista de todos os usários
# Permissão: Quem tem acesso é o Admin
class UsuarioList(APIView):
"""
Lista todos os usuários e permite a criação.
"""
# Função get: Retorna todos os usuários do banco
def get(self, request, format = None):
usuario = Usuario.objects.all()
serializer = UsuarioSerializer(usuario, many = True)
return Response(serializer.data)
permission_classes = [IsAdminUser] # Só o admin pode ver todos os usuários
# Criação de um novo usuário
# Permissão: liberado pra todos
class UsuarioCreate(APIView):
"""
Lista todos os usuários e permite a criação.
"""
# Função post: Cria um novo usuário
def post(self, request, format = None):
u = User.objects.create(
username = request.data['login'], # Passamos o login
email = request.data['email'] # Passamos o email
)
u.set_password(request.data['senha'])
request.data['user'] = u.id
usuario = UsuarioSerializer(data = request.data)
if usuario.is_valid():
try:
usuario.save()
except utils.IntegrityError:
u.delete()
return Response(usuario.errors, status=status.HTTP_400_BAD_REQUEST) #Falhou
u.save()
return Response(usuario.data, status=status.HTTP_201_CREATED) #Sucedeu
u.delete()
return Response(usuario.errors, status=status.HTTP_400_BAD_REQUEST) #Falhou
permission_classes = [AllowAny] # Qualquer um pode criar usuários
# Detalhes de um Usuário
# Permissão: liberado para o próprio usuário
class UsuarioDetail(APIView):
"""
Acessa um usuário específico com sua id, pode editar e deletar.
"""
# Função que retorna um objeto Usuário
def get_object(self, pk):
try:
return Usuario.objects.get(pk = pk)
except Usuario.DoesNotExist:
raise Http404
# PERMISSÕES
def has_permission(self, request, view):
return request.user and request.user.is_authenticated()
def check_object_permission(self, user, obj):
return (user and user.is_authenticated() and
(user.is_staff or obj.user_id == user.id))
def has_object_permission(self, request, view, obj):
return True
# FIM DAS PERMISSÕES
# Função que retorna os detalhes sobre um usuário específico
def get(self, request, pk, format = None):
usuario = self.get_object(pk)
serializer = UsuarioSerializer(usuario)
x = self.has_permission(request, UsuarioDetail)
y = self.check_object_permission(request.user, usuario)
z = self.has_object_permission(request, UsuarioDetail, usuario)
if (x and y and z):
return Response(serializer.data)
return Response(status = status.HTTP_204_NO_CONTENT)
# Edição de um usuário
# Permissão: liberado para o próprio usuário e admin
class UsuarioEdit(APIView):
"""
Edita um usuário específico
"""
# PERMISSÕES
def has_permission(self, request, view):
return request.user and request.user.is_authenticated()
def check_object_permission(self, user, obj):
return (user and user.is_authenticated() and
(user.is_staff or obj.user_id == user.id))
def has_object_permission(self, request, view, obj):
return True
# FIM DAS PERMISSÕES
# Função que retorna os detalhes sobre um usuário específico
def get(self, request, pk, format = None):
usuario = self.get_object(pk)
serializer = UsuarioSerializer(usuario)
x = self.has_permission(request, UsuarioEdit)
y = self.check_object_permission(request.user, usuario)
z = self.has_object_permission(request, UsuarioEdit, usuario)
if (x and y and z):
return Response(serializer.data)
return Response(status = status.HTTP_204_NO_CONTENT)
# Função que retorna um objeto Usuário
def get_object(self, pk):
try:
return Usuario.objects.get(pk = pk)
except Usuario.DoesNotExist:
raise Http404
# Função que edita os valores de um usuário específico
def put(self, request, pk, format = None):
# Cria uma referência ao usuário escolhido
usuario = self.get_object(pk)
serializer = UsuarioSerializer(usuario, data = request.data)
x = self.has_permission(request, UsuarioEdit)
y = self.check_object_permission(request.user, usuario)
z = self.has_object_permission(request, UsuarioEdit, usuario)
if (x and y and z):
# Se o serailizer for valido poderá editar os campos
if serializer.is_valid():
if request.data['login'] != usuario.login or request.data['email'] != usuario.email or request.data['senha'] != usuario.senha:
user = User.objects.get(pk = usuario.user.pk)
user.username = request.data['login']
user.email = request.data['email']
user.set_password(request.data['senha'])
user.save()
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return Response(status = status.HTTP_204_NO_CONTENT)
# Deletar um usuário
# Permissão liberada para o admin
class UsuarioDelete(APIView):
# Função que retorna os detalhes sobre um usuário específico
def get(self, request, pk, format = None):
usuario = self.get_object(pk)
serializer = UsuarioSerializer(usuario)
return Response(serializer.data)
# Função que retorna um objeto Usuário
def get_object(self, pk):
try:
return Usuario.objects.get(pk = pk)
except Usuario.DoesNotExist:
raise Http404
# Deleta um usuário e seu user associado
def delete(self, request, pk, format=None):
usuario = self.get_object(pk)
serializer = UsuarioSerializer(usuario)
u = User.objects.get(id = serializer.data['user'])
u.delete()
usuario.delete()
return Response(status = status.HTTP_204_NO_CONTENT)
permission_classes(IsAdminUser)
############################ OCORRÊNCIA ##############################################
# CRUD ocorrências
# Criar uma nova ocorrência
# Permissão: qualquer usuário cadastrado
class OcorrenciaCreateAPIView(CreateAPIView):
'''
Crie uma nova ocorrência
'''
queryset = Ocorrencia.objects.all()
serializer_class = OcorrenciaSerializer
permission_classes = [IsAuthenticated]
# Detalhes de uma ocorrência
# Permissão: dono da ocorrência, admin, vigilante*
class OcorrenciaDetailAPIView(RetrieveAPIView):
'''
Informações das ocorrências
'''
queryset = Ocorrencia.objects.all()
serializer_class = OcorrenciaSerializer
#permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
# Lista de ocorrências
# Permissão: usuario dono da ocorrencia, ocorrências validadas*
class OcorrenciaListAPIView(ListAPIView):
'''
Liste as ocorrências
'''
queryset = Ocorrencia.objects.all()
serializer_class = OcorrenciaSerializer
#permission_classes = (IsOwner,)
# Editar ocorrências
# Permissão: usuário dono da ocorrência se ela nao tiver sido validada, vigilante,admin*
class OcorrenciaUpdateAPIView(RetrieveUpdateAPIView):
'''
Edite ocorrência
'''
queryset = Ocorrencia.objects.all()
serializer_class = OcorrenciaSerializer
# permission_classes = (IsAuthenticatedOrReadOnly,)
# Deletar ocorrência
# Permissão: usuário dono da ocorrência se ela não tiver sido validada, vigilante, admin*
class OcorrenciaDeleteAPIView(DestroyAPIView):
'''
Delete uma ocorrência
'''
queryset = Ocorrencia.objects.all()
serializer_class = OcorrenciaSerializer
# permission_classes = (IsAuthenticatedOrReadOnly,)
############################ CATEGORIA ##############################################
# CRUD Categoria
# Só tem acesso se o usuário for Admin
# Criar Admin, mudar no BD is_staff de um User para TRUE
# Permissão: Só quem tem acesso é o Admin
class CategoriaCreateAPIView(CreateAPIView):
'''
Crie uma nova categoria
'''
queryset = Categoria.objects.all()
serializer_class = CategoriaSerializer
permission_classes = (IsAdminUser,)
class CategoriaDetailAPIView(RetrieveAPIView):
'''
Informações das categorias
'''
queryset = Categoria.objects.all()
serializer_class = CategoriaSerializer
permission_classes = (IsAdminUser,)
class CategoriaListAPIView(ListAPIView):
'''
Liste as categorias
'''
queryset = Categoria.objects.all()
serializer_class = CategoriaSerializer
permission_classes = (IsAdminUser,)
class CategoriaUpdateAPIView(RetrieveUpdateAPIView):
'''
Edite uma categoria
'''
queryset = Categoria.objects.all()
serializer_class = CategoriaSerializer
permission_classes = (IsAdminUser,)
class CategoriaDeleteAPIView(DestroyAPIView):
'''
Delete uma categoria
'''
queryset = Categoria.objects.all()
serializer_class = CategoriaSerializer
permission_classes = (IsAdminUser,)
############################ LOCAL ##############################################
# CRUD Local
# Só tem acesso se o usuário for Admin
# Criar Admin, mudar no BD is_staff de um User para TRUE
# Permissão: Só quem tem acesso é o Admin
class LocalCreateAPIView(CreateAPIView):
'''
Crie uma nova local
'''
queryset = Local.objects.all()
serializer_class = LocalSerializer
permission_classes = (IsAdminUser,)
class LocalDetailAPIView(RetrieveAPIView):
'''
Informações das locals
'''
queryset = Local.objects.all()
serializer_class = LocalSerializer
permission_classes = (IsAdminUser,)
class LocalListAPIView(ListAPIView):
'''
Liste as locals
'''
queryset = Local.objects.all()
serializer_class = LocalSerializer
permission_classes = (IsAdminUser,)
class LocalUpdateAPIView(RetrieveUpdateAPIView):
'''
Edite uma local
'''
queryset = Local.objects.all()
serializer_class = LocalSerializer
permission_classes = (IsAdminUser,)
class LocalDeleteAPIView(DestroyAPIView):
'''
Delete uma local
'''
queryset = Local.objects.all()
serializer_class = LocalSerializer
permission_classes = (IsAdminUser,)
|
986,789 | 0463210c39960698e70ca0b240a0cb6f6dda78c6 | from urllib.request import Request, urlopen
from urllib.error import HTTPError
import logging
import json
import time
class Database:
PAGE_SIZE = 100
def __init__(self):
self.logger = logging.getLogger('logger')
self.database_url = 'http://localhost:5984'
self.requests_table = self.database_url + '/requests'
self.requests_output_datasets_view = self.requests_table + '/_design/_designDoc/_view/outputDatasets'
self.requests_campaigns_view = self.requests_table + '/_design/_designDoc/_view/campaigns'
self.requests_prepid_view = self.requests_table + '/_design/_designDoc/_view/prepids'
self.requests_type_view = self.requests_table + '/_design/_designDoc/_view/types'
self.settings_table = self.database_url + '/settings'
self.auth_header = str(open('/home/jrumsevi/stats2_auth.txt', "r").read()).replace('\n', '')
def update_request(self, request, update_timestamp=True):
try:
if update_timestamp:
request['LastUpdate'] = int(time.time())
url = self.requests_table + '/' + request['_id']
self.make_request(url, request, 'PUT')
except HTTPError as err:
self.logger.error(str(err))
def delete_request(self, request_name):
request = self.get_request(request_name)
if request is not None and request.get('_rev') is not None:
rev = request['_rev']
url = '%s/%s?rev=%s' % (self.requests_table, request_name, rev)
self.make_request(url, method='DELETE')
def get_request_count(self):
return self.make_request(self.requests_table)['doc_count']
def get_request(self, request_name):
url = self.requests_table + '/' + request_name
try:
return self.make_request(url)
except HTTPError as err:
if err.code != 404:
self.logger.error(str(err))
return None
def get_requests_with_prepid(self, prepid, page=0, page_size=PAGE_SIZE, include_docs=False):
url = '%s?key="%s"&limit=%d&skip=%d&include_docs=%s' % (self.requests_prepid_view,
prepid,
page_size,
page * page_size,
'True' if include_docs else 'False')
rows = self.make_request(url)['rows']
if include_docs:
return [x['doc'] for x in rows]
else:
return [x['id'] for x in rows]
def get_requests_with_dataset(self, dataset, page=0, page_size=PAGE_SIZE, include_docs=False):
url = '%s?key="%s"&limit=%d&skip=%d&include_docs=%s' % (self.requests_output_datasets_view,
dataset,
page_size,
page * page_size,
'True' if include_docs else 'False')
rows = self.make_request(url)['rows']
if include_docs:
return [x['doc'] for x in rows]
else:
return [x['id'] for x in rows]
def get_requests_with_campaign(self, campaign, page=0, page_size=PAGE_SIZE, include_docs=False):
url = '%s?key="%s"&limit=%d&skip=%d&include_docs=%s' % (self.requests_campaigns_view,
campaign,
page_size,
page * page_size,
'True' if include_docs else 'False')
rows = self.make_request(url)['rows']
if include_docs:
return [x['doc'] for x in rows]
else:
return [x['id'] for x in rows]
def get_requests_with_type(self, request_type, page=0, page_size=PAGE_SIZE, include_docs=False):
url = '%s?key="%s"&limit=%d&skip=%d&include_docs=%s' % (self.requests_type_view,
request_type,
page_size,
page * page_size,
'True' if include_docs else 'False')
rows = self.make_request(url)['rows']
if include_docs:
return [x['doc'] for x in rows]
else:
return [x['id'] for x in rows]
def get_requests(self, page=0, page_size=PAGE_SIZE, include_docs=False):
url = '%s/_all_docs?limit=%d&skip=%d&include_docs=%s' % (self.requests_table,
page_size,
page * page_size,
'True' if include_docs else 'False')
rows = self.make_request(url)['rows']
if include_docs:
return [x['doc'] for x in rows]
else:
return [x['id'] for x in rows]
def set_setting(self, setting_name, setting_value):
url = self.settings_table + '/all_settings'
try:
settings_dict = self.make_request(url)
except HTTPError:
settings_dict = {'_id': 'all_settings'}
settings_dict[setting_name] = setting_value
self.make_request(url, settings_dict, 'PUT')
def get_setting(self, setting_name, default_value):
url = self.settings_table + '/all_settings'
try:
settings_dict = self.make_request(url)
except HTTPError:
return default_value
return settings_dict.get(setting_name, default_value)
def make_request(self, url, data=None, method='GET'):
if data is not None:
data = json.dumps(data)
req = Request(url, data=data, method=method)
if (method == 'POST' or method == 'PUT') and data is not None:
data = data.encode("utf-8")
req.add_header('Content-Type', 'application/json')
req.add_header('Authorization', self.auth_header)
response = json.loads(urlopen(req, data=data).read().decode('utf-8'))
return response
|
986,790 | d3229b641e925640d1edb09454e08ed29a0b18eb | #import curses_thing
#import page_getter
#import subprocess
#handle two threads: curses thread and page getter thread
|
986,791 | 4eaac70be7cec89979e50b099e0bcb9edb849b6c | from crispy_forms.helper import FormHelper
from django.db.models.base import Model
from django.forms import ModelForm
from django import forms
from .models import(Register_users)
class Register_userForm(forms.ModelForm):
class Meta:
model = Register_users
fields = '__all__'
def __init__(self, *args, **kwargs):
super(Register_userForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
|
986,792 | 8671ea98eaebf2fac04359c802435f662b1afafb |
from django.shortcuts import render
# Create your views here.
from django.views.generic import TemplateView, DetailView
from .models import *
class HomeTemplateView(TemplateView):
template_name = 'home.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['about'] = AboutModel.objects.first()
context['services'] = ServiceModel.objects.all()
context['works'] = RecentWork.objects.all()
return context
|
986,793 | 55a684b38873ca80e4fce448adb8d08e4b5d8f4b | import requests
import logging
import schedule
import time
from configparser import ConfigParser
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
def run(user,pwd, keep_type, ids):
logging.info("work type: {}".format(keep_type))
session = requests.Session()
response = session.get("https://vx.link/x2/login")
token=''
if response.status_code == 200:
logging.info("get token success")
cookies = response.cookies
if cookies["PHPSESSID"]:
token = cookies["PHPSESSID"]
else:
logging.error("get token err, status_code: %s, msg: %s" % (response.status_code, "not token sessid"))
else:
logging.error("get token err, status_code: %s, msg: %s" % (response.status_code, response.text))
response = session.get("https://vx.link/openapi/v1/user?token={}&username={}&password={}&action=login".format(token,user,pwd))
if response.status_code == 200:
logging.info("login success")
else:
logging.error("login err, status_code: %s, msg: %s" % (response.status_code, response.text))
for id in ids:
response = session.get("https://vx.link/openapi/v1/vxtrans?action={}&token={}&id={}".format(keep_type, token, id))
if response.status_code == 200:
logging.info(response.url)
else:
logging.error("keep alive err, status_code: %s, msg: %s" % (response.status_code, response.text))
if __name__ == "__main__":
cfg = ConfigParser()
cfg.read('config.ini')
user = cfg.get('login','user')
pwd = cfg.get('login','pwd')
ids = cfg.get('nodes','nodes_ids').split(',')
on_time = str(cfg.get('time','keep_on_time'))
off_time = str(cfg.get('time','keep_off_time'))
logging.info("start work, on time: {}, off time: {}".format(on_time, off_time))
schedule.every().day.at(on_time).do(run, user= user,pwd=pwd, keep_type="keep_on", ids = ids)
schedule.every().day.at(off_time).do(run, user= user,pwd=pwd, keep_type="keep_off", ids = ids)
while True:
schedule.run_pending()
time.sleep(1) |
986,794 | d3b12ffbaec31bcf651babdeafbf8585a4068835 | # Given an array of non-negative integers, you are initially positioned at the first index of the array.
# Each element in the array represents your maximum jump length at that position.
# Your goal is to reach the last index in the minimum number of jumps.
# For example:
# Given array A = [2,3,1,1,4]
# The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
class Solution:
# @param {integer[]} nums
# @return {integer}
def jump(self, nums):
idx = times = 0
maximum = nums[0]
while True:
if idx == len(nums)-1:
return times
times += 1
base = idx
for step in range(nums[idx], 0, -1):
at = base + step
if at >= len(nums)-1:
return times
possible = at + nums[at]
if possible > maximum:
maximum, idx = possible, at |
986,795 | 0956f78952db5566cd217d67c7d0ff2aa5c619ab | Find X and Y intercepts of a line passing through the given points
Given two points on a 2D plane, the task is to find the **x – intercept** and
the **y – intercept** of a line passing through the given points.
**Examples:**
> **Input:** points[][] = {{5, 2}, {2, 7}}
> **Output:**
> 6.2
> 10.333333333333334
>
> **Input:** points[][] = {{3, 2}, {2, 4}}
> **Output:**
> 4.0
> 8.0
## Recommended: Please try your approach on **__{IDE}__** first, before moving
on to the solution.
**Approach:**
* Find the slope using the given points.
* Put the value of the slope in the expression of the line i.e. **y = mx + c**.
* Now find the value of **c** using the values of any of the given points in the equation **y = mx + c**
* To find the x-intercept, put **y = 0** in **y = mx + c**.
* To find the y-intercept, put **x = 0** in **y = mx + c**.
Below is the implementation of the above approach:
## C++
__
__
__
__
__
__
__
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the X and Y intercepts
// of the line passing through
// the given points
void getXandYintercept(int P[], int Q[])
{
int a = P[1] - Q[1];
int b = P[0] - Q[0];
// if line is parallel to y axis
if (b == 0) {
cout << P[0] << endl; // x - intercept will be p[0]
cout << "infinity"; // y - intercept will be infinity
return;
}
// if line is parallel to x axis
if (a == 0) {
cout << "infinity"; // x - intercept will be infinity
cout << P[1] << endl; // y - intercept will be p[1]
return;
}
// Slope of the line
double m = a / (b * 1.0);
// y = mx + c in where c is unknown
// Use any of the given point to find c
int x = P[0];
int y = P[1];
double c = y - m * x;
// For finding the x-intercept put y = 0
y = 0;
double r = (y - c) / (m * 1.0);
cout << r << endl;
// For finding the y-intercept put x = 0
x = 0;
y = m * x + c;
printf("%.8f", c);
}
// Driver code
int main()
{
int p1[] = { 5, 2 };
int p2[] = { 2, 7 };
getXandYintercept(p1, p2);
return 0;
}
// This code is contributed by Mohit Kumar
---
__
__
## Java
__
__
__
__
__
__
__
// Java implementation of the approach
class GFG {
// Function to find the X and Y intercepts
// of the line passing through
// the given points
static void getXandYintercept(int P[],
int Q[])
{
int a = P[1] - Q[1];
int b = P[0] - Q[0];
// if line is parallel to y axis
if (b == 0) {
// x - intercept will be p[0]
System.out.println(P[0]);
// y - intercept will be infinity
System.out.println("infinity");
return;
}
// if line is parallel to x axis
if (a == 0) {
// x - intercept will be infinity
System.out.println("infinity");
// y - intercept will be p[1]
System.out.println(P[1]);
return;
}
// Slope of the line
double m = a / (b * 1.0);
// y = mx + c in where c is unknown
// Use any of the given point to find c
int x = P[0];
int y = P[1];
double c = y - m * x;
// For finding the x-intercept put y = 0
y = 0;
double r = (y - c) / (m * 1.0);
System.out.println(r);
// For finding the y-intercept put x = 0
x = 0;
y = (int)(m * x + c);
System.out.print(c);
}
// Driver code
public static void main(String[] args)
{
int p1[] = { 5, 2 };
int p2[] = { 2, 7 };
getXandYintercept(p1, p2);
}
}
// This code is contributed by kanugargng
---
__
__
## Python3
__
__
__
__
__
__
__
# Python3 implementation of the approach
# Function to find the X and Y intercepts
# of the line passing through
# the given points
def getXandYintercept(P, Q):
a = P[1] - Q[1]
b = P[0] - Q[0]
# if line is parallel to y axis
if b == 0:
print(P[0]) # x - intercept will be p[0]
print("infinity") # y - intercept will be infinity
return
# if line is parallel to x axis
if a == 0:
print("infinity") # x - intercept will be infinity
print(P[1]) # y - intercept will be p[1]
return
# Slope of the line
m = a / b
# y = mx + c in where c is unknown
# Use any of the given point to find c
x = P[0]
y = P[1]
c = y-m * x
# For finding the x-intercept put y = 0
y = 0
x =(y-c)/m
print(x)
# For finding the y-intercept put x = 0
x = 0
y = m * x + c
print(y)
# Driver code
p1 = [5, 2]
p2 = [7, 2]
getXandYintercept(p1, p2)
---
__
__
## C#
__
__
__
__
__
__
__
// C# implementation of the approach
using System;
class GFG {
// Function to find the X and Y intercepts
// of the line passing through
// the given points
static void getXandYintercept(int[] P,
int[] Q)
{
int a = P[1] - Q[1];
int b = P[0] - Q[0];
// if line is parallel to y axis
if (b == 0) {
Console.WriteLine(P[0]); // x - intercept will be p[0]
Console.WriteLine("infinity"); // y - intercept will be infinity
return;
}
// if line is parallel to x axis
if (a == 0) {
Console.WriteLine("infinity"); // x - intercept will be infinity
Console.WriteLine(P[1]); // y - intercept will be p[1]
return;
}
// Slope of the line
double m = a / (b * 1.0);
// y = mx + c in where c is unknown
// Use any of the given point to find c
int x = P[0];
int y = P[1];
double c = y - m * x;
// For finding the x-intercept put y = 0
y = 0;
double r = (y - c) / (m * 1.0);
Console.WriteLine(r);
// For finding the y-intercept put x = 0
x = 0;
y = (int)(m * x + c);
Console.WriteLine(c);
}
// Driver code
public static void Main()
{
int[] p1 = { 5, 2 };
int[] p2 = { 2, 7 };
getXandYintercept(p1, p2);
}
}
// This code is contributed by AnkitRai01
---
__
__
**Output:**
6.2
10.33333333333
**Time Complexity:** O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA
concepts with the **DSA Self Paced Course** at a student-friendly price and
become industry ready. To complete your preparation from learning a language
to DS Algo and many more, please refer **Complete Interview Preparation
Course** **.**
My Personal Notes _arrow_drop_up_
Save
|
986,796 | ab60d40b1708b4644a32ba5056db6ef4feb2da23 | # Generated by Django 3.1.1 on 2020-09-29 11:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0016_auto_20200929_0932'),
]
operations = [
migrations.RenameField(
model_name='artwork',
old_name='artwork_soundbite',
new_name='artwork_soundbites',
),
migrations.RemoveField(
model_name='soundbite',
name='page',
),
migrations.AddField(
model_name='soundbite',
name='name',
field=models.CharField(default='test', max_length=500),
preserve_default=False,
),
]
|
986,797 | 5a3cfd2829e35eac20ed4329808d1bb0f0cd0011 | # Example of a HEAD request
import requests
resp = requests.head('http://www.python.org/index.html')
status = resp.status_code
last_modified = resp.headers['last-modified']
content_type = resp.headers['content-type']
content_length = resp.headers['content-length']
print(status)
print(last_modified)
print(content_type)
print(content_length)
|
986,798 | 3f1dd5bb591f7b1d30011ef6b5917168d1d44bef | from odoo import api, fields, models
class TrainingLesson(models.Model):
_name = 'lu.lesson'
_description = "课程信息哦"
name = fields.Char(string='课程名称')
teacher_id = fields.Many2one('res.partner', string='老师', domain=[('is_teacher', '=', True)])
student_ids = fields.Many2many('res.partner', string='学生', domain=[('is_student', '=', True)], readonly=True)
start_date = fields.Date(string='开始时间')
end_date = fields.Date(string='结束时间')
seat_qty = fields.Integer(string='座位数')
subject_id = fields.Many2one('lu.subject', string='科目')
person_id = fields.Many2one('res.partner', related='subject_id.person_id', readonly=True) |
986,799 | dd5ffe40b5bd66011f2f4957ec58e66942a25dfd | def main():
first, last = input("Enter name: ").lower().split()
common_letter_list = get_common_list(first, last)
print(sorted(common_letter_list))
print(sorted(get_common_set(first, last)))
def get_common_set(first, last):
return set(first).intersection(set(last))
def get_common_list(first, last):
common_letters = []
for char in first:
if char in last and char not in common_letters:
common_letters.append(char)
return common_letters
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.