blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 69 | license_type stringclasses 2 values | repo_name stringlengths 5 118 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 63 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 2.91k 686M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 213 values | src_encoding stringclasses 30 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 2 10.3M | extension stringclasses 246 values | content stringlengths 2 10.3M | authors listlengths 1 1 | author_id stringlengths 0 212 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7a9c2a6a14bd879555bb2a0a59dd99834c73ebe6 | ac43c0aeae3d86018272f8cbbaca1c1a5a6f2ed6 | /tcp_logic.py | 7b23e4401b33243a91af87a4a60e47b9682a17f2 | [] | no_license | jeekMic/tcp_udp | b15ce1d1621bd52752ed7e5f01efb881b78cc38c | e76fa616bc638bc51ee961b948eeb771503206fb | refs/heads/master | 2020-03-22T00:19:10.170361 | 2018-09-08T00:51:16 | 2018-09-08T00:51:16 | 139,237,437 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 20,337 | py | import codecs
import os
from typing import Union
from PyQt5 import QtWidgets
from PyQt5.QtCore import QDir, Qt, QObject
from PyQt5.QtWidgets import QFileDialog
import tcp_udp_web_ui
import socket
import threading
import sys
import stopThreading
from callscan import MyDialog
from constant import Constant
import binascii
import struct
from scan import Ui_Dialog
class TcpLogic(tcp_udp_web_ui.ToolsUi):
def __init__(self, num):
super(TcpLogic, self).__init__(num)
self.finish_all = None
self.total = None
self.send_socket = None
self.tcp_socket = None
self.sever_th = None
self.client_th = None
self.flag = 0
self.arrs = []
self.temm = 1
self.client_socket_list = list()
self.client_socket_lists = list()
self.link = False # 用于标记是否开启了连接
self.limit = 0
self.need_packet_id = 0
self.pushButton_backup.clicked.connect(self.send_backup)
self.pushButton_restart_remote.clicked.connect(self.restart)
# 初始化的时候加载bin文件 存储在这个数组里面
self.pushButton_make_ip.clicked.connect(self.make_ip)
def make_ip(self):
btnDemo.show()
def restart(self):
self.tcp_send(init_code=Constant.remote_restart)
def send_backup(self):
self.tcp_send(init_code=self.backup())
# 选择bin文件
def getfiles(self):
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.AnyFile)
dlg.setFilter(QDir.Files)
if dlg.exec_():
filenames = dlg.selectedFiles()
print(filenames)
f = open(filenames[0], 'r')
with f:
data = f.read()
self.contents.setText(data)
def tcp_server_start(self):
print("开启服务器...............")
if len(self.arrs) == 0:
self.signal_write_msg.emit("【请加载bin文件,以免引起不必要的异常】\n")
self.signal_write_msg.emit("【请加载bin文件,以免引起不必要的异常】\n")
return
"""
功能函数,TCP服务端开启的方法
:return: None
"""
self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# # 取消主动断开连接四次握手后的TIME_WAIT状态
# self.tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 50)
# # 设定套接字为非阻塞式
# self.tcp_socket.setblocking(False)
try:
port = int(self.lineEdit_port.text())
self.tcp_socket.bind(('', port)) # 监测本地IP地址 和指定的端口号
except Exception as ret:
msg = '请检查端口号\n'
self.signal_write_msg.emit(msg)
else:
print("服务器正在监听---------")
self.link = True
self.pushButton_unlink.setEnabled(True)
self.pushButton_link.setEnabled(False)
self.tcp_socket.listen()
self.sever_th = threading.Thread(target=self.tcp_server_concurrency)
self.sever_th.start()
msg = 'TCP服务端正在监听端口:%s\n' % str(port)
self.signal_write_msg.emit(msg)
def tcp_server_concurrency(self):
while True:
clientsock, clientaddress = self.tcp_socket.accept()
print('connect from:', clientaddress)
msg = "【检测到 客户端 :" + str(clientaddress) + "已经连接】\n"
self.set_port(clientaddress[1])
self.signal_write_msg.emit(msg)
self.client_socket_list.append(clientaddress)
self.client_socket_lists.append((clientsock, clientaddress))
self.detect_is_alive()
# 传输数据都利用clientsock,和s无关
t = threading.Thread(target=self.tcplink, args=(clientsock, clientaddress)) # t为新创建的线程
t.start()
def set_port(self, port):
"""
:param port: 连接上的端口号
:return: null
"""
id = self.combox_port_select.count()
self.combox_port_select.insertItem(id, str(port))
def tcplink(self, sock, addr):
result = []
index = 0
while True:
if self.combox_port_select.currentText() == "all connections":
index = 5000
else:
index = int(self.combox_port_select.currentText())
if addr[1] == index:
self.send_socket = sock
try:
recvdata = sock.recv(2048)
except:
print("socket 出现异常数据")
sock.close()
self.send_socket = None
break
result = []
for i in recvdata:
result.append(hex(i))
if len(result) < 5:
return
self.signal_send_msg.emit(str(result) + "\n")
self.signal_send_msg.emit("----------------------\n")
code, res = Constant.parse_receive(result)
msg = "收到远程发过来的数据,代号:"+str(code)+"\n"
self.signal_write_msg.emit(msg)
self.parse_code(code, res)
if recvdata == 'exit' or not recvdata:
break
# clientsock.send(b' ')
sock.close()
self.send_socket = None
def detect_is_alive(self):
current = self.combox_port_select.currentText()
temp = []
temp_1 = []
temp_num = []
self.combox_port_select.clear()
self.combox_port_select.insertItem(0, "all connections")
for client, address in self.client_socket_lists:
try:
print("连接状态")
temp.append((client, address))
temp_1.append(address)
temp_num.append(address[1])
except:
self.combox_port_select.clearEditText()
self.client_socket_lists = []
self.client_socket_lists = list(set(temp))
temp_num = list(set(temp_num))
for strss in temp_num:
self.combox_port_select.insertItem(1, str(strss))
self.combox_port_select.setCurrentText(current)
def parse_code(self, code, res):
if code == 12:
# if self.flag >= self.total:
# self.tcp_send(data = str(Constant.finish))
# return
self.tcp_send(data=''.join(self.arrs[self.flag]))
num_str = "\n【已经发送第" + str(self.flag+1)+"包数据】\n"
self.signal_write_msg.emit(num_str)
self.flag += 1
# if self.flag == self.total:
# # 所有的包发送完毕并且成功发送需要发送一条告诉设备已经发送完毕的指令
# self.tcp_send(data=str(Constant.finish))
elif code == 14:
print("-------------", self.flag, "-------", self.total)
#self.progressBar.setValue((100 / 35) * self.flag)
self.signal_progress_msg.emit((100 /(self.total+1)) * self.flag)
if self.flag >= self.total:
self.signal_write_msg.emit("【结束包正在发送......】\n")
print("结束包正在发送---------\n")
print(''.join(self.finish_all))
self.tcp_send(data=''.join(self.finish_all))
self.signal_write_msg.emit("【结束包发送成功---------】\n")
print("结束包发送成功---------\n")
return
self.tcp_send(data=''.join(self.arrs[self.flag]))
num_str = "\n【已经发送第" + str(self.flag+1)+"包数据】\n"
self.signal_write_msg.emit(num_str)
self.flag += 1
# if self.flag == self.total:
# # 所有的包发送完毕并且成功发送需要发送一条告诉设备已经发送完毕的指令
# self.tcp_send(data = str(Constant.finish))
elif code == 13:
self.signal_write_msg.emit("【第%d包数据发送错误,正在重新发送....】\n" % (res + 1))
self.tcp_send(data=''.join(self.arrs[res]))
elif code == 33:
self.signal_write_msg.emit('【写入错误】\n')
# self.get_error(self.flag-1)
elif code == 39:
if res >= self.total - 1:
self.signal_write_msg.emit("【远程程序发送命令错误,没有下一包数据可以发送了】")
return
if len(self.arrs) == 0:
self.signal_write_msg.emit("【请先加载文件】")
return
self.flag = res + 1
self.need_packet_id = self.flag
if self.limit > 5:
self.limit = 0
self.signal_write_msg.emit('【我已经尽力了,更新失败】\n')
else:
print("发送的包序号", self.flag)
self.tcp_send(data=''.join(self.arrs[self.flag]))
self.limit += 1
elif code == 15:
self.signal_write_msg.emit('【更新失败】\n')
elif code == 40:
self.signal_write_msg.emit('【app源代码损坏,软件更新失败,请重置数据,或者选择恢复方式恢复】\n')
self.set_visiable()
elif code == 41:
self.signal_write_msg.emit('【恢复成功】\n')
self.set_visiable(is_visiable=1)
elif code == 35:
# 返回更新成功后需要初始化一些基本参数
self.flag = 0
self.limit = 0
self.need_packet_id = 0
self.flag = 0
self.temm = 1
self.signal_write_msg.emit(self.show_message_error(code))
self.signal_progress_msg.emit(100)
else:
print("【位置异常,代号{}】".format(code))
def tcp_client_start(self):
"""
功能函数,TCP客户端连接其他服务端的方法
:return:
"""
self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
address = (str(self.lineEdit_ip_send.text()), int(self.lineEdit_port.text()))
except Exception as ret:
msg = '请检查目标IP,目标端口\n'
self.signal_write_msg.emit(msg)
else:
try:
msg = '正在连接目标服务器\n'
self.signal_write_msg.emit(msg)
self.tcp_socket.connect(address)
except Exception as ret:
msg = '无法连接目标服务器\n'
self.signal_write_msg.emit(msg)
else:
self.client_th = threading.Thread(target=self.tcp_client_concurrency, args=(address,))
self.client_th.start()
msg = '【TCP客户端已连接IP:%s端口:%s】\n' % address
self.signal_write_msg.emit(msg)
def get_error(self, error_id):
if error_id < 100 and error_id > 0:
return "更新数据第{}包发送有误".format(error_id + 1)
if error_id == 0:
return "初始请求更新数据失败"
if error_id == 102:
return "结束命令发送有误"
if error_id >= self.total - 1:
return "结束包发送有误"
def tcp_client_concurrency(self, address):
"""
功能函数,用于TCP客户端创建子线程的方法,阻塞式接收
:return:
"""
while True:
recv_msg = self.tcp_socket.recv(1024)
if recv_msg:
msg = recv_msg.decode('utf-8')
msg = '\n【来自IP:{}端口:{}:】\n'.format(address[0], address[1])
self.signal_write_msg.emit(msg)
else:
self.tcp_socket.close()
self.reset()
msg = '【从服务器断开连接】\n'
self.signal_write_msg.emit(msg)
break
# 重置界面上的数据文件,重新加载文件
def reset_data(self):
self.arrs = []
self.finish_all = None
self.flag = 0
self.total = None
self.signal_write_msg.emit("【恭喜您,数据已重置】\n")
self.progressBar.setValue(0)
temp = self.combox_port_select.currentText()
self.combox_port_select.clear()
self.combox_port_select.insertItem(0, temp)
def tcp_send(self, data=None, init_code=None):
arras = ''
"""
功能函数,用于TCP服务端和TCP客户端发送消息
:return: None
"""
send_msg = None
if self.link is False:
msg = '【请选择服务,并点击连接网络】\n'
self.signal_write_msg.emit(msg)
elif len(self.arrs) == 0:
self.signal_write_msg.emit("没有加载文件")
self.show_error_for_loadfile()
else:
try:
if init_code is not None:
send_msg = init_code
print("-------------------需要的发送格式要求-----------------------")
print(send_msg)
print(type(send_msg))
elif data is None:
send_msg = (str(self.textEdit_send.toPlainText())).encode('utf-8')
else:
# send_msg = bytes(data, encoding="utf8")
# print("--------------2数据的长度为:", len(data))
if len(data) == 2065:
arras = data[:2064] + '0' + data[-1]
send_msg = codecs.decode(arras, 'hex_codec')
else:
send_msg = codecs.decode(data, 'hex_codec')
# temp_send = b""
# for i in send_msg:
# temp_send +=i
# send_msg = temp_send
print("--------------------发出的数据-----------------")
print(send_msg)
if self.comboBox_tcp.currentIndex() == 0:
# 向所有连接的客户端发送消息
# for client, address in self.client_socket_list:
# if init_code == None:
# update = b'\xFF\xFF\x00\x27\x00\x00\x00\x00\x00\x00\x00\x00\x00\xEE\xEE\x28'
if self.flag > 1:
print(send_msg)
print("正在发送----------", self.flag)
self.send_socket.send(send_msg)
print("发送完成----------", self.flag)
msg = 'TCP服务端已发送\n'
self.signal_write_msg.emit(msg)
if self.comboBox_tcp.currentIndex() == 1:
self.send_socket.send(send_msg)
print("-----发送")
msg = 'TCP客户端已发送\n'
self.signal_write_msg.emit(msg)
except Exception as ret:
msg = '发送失败\n'
self.signal_write_msg.emit(msg)
def tcp_close(self):
"""
功能函数,关闭网络连接的方法
:return:
"""
if self.comboBox_tcp.currentIndex() == 0:
self.combox_port_select.clear()
self.combox_port_select.insertItem(0, "all connections")
try:
for client, address in self.client_socket_lists:
client.close()
self.tcp_socket.close()
if self.link is True:
msg = '已断开网络\n'
self.signal_write_msg.emit(msg)
self.combox_port_select.clear()
self.combox_port_select.insertItem(0, "all connections")
except Exception as ret:
pass
if self.comboBox_tcp.currentIndex() == 1:
try:
self.tcp_socket.close()
if self.link is True:
msg = '已断开网络\n'
self.signal_write_msg.emit(msg)
except Exception as ret:
pass
try:
stopThreading.stop_thread(self.sever_th)
except Exception:
pass
try:
stopThreading.stop_thread(self.client_th)
except Exception:
pass
# ------------------------bin文件解析--------------------
def dec2hexstr(self, n):
ss = str(hex(n))
ss = ss[2:]
if n <= 15:
ss = '0' + ss
return ss
# crc校验
def uchar_checksum(self, data, byteorder='little'):
'''
char_checksum 按字节计算校验和。每个字节被翻译为无符号整数
@param data: 字节串
@param byteorder: 大/小端
'''
length = len(data)
checksum = 0
for i in range(0, length):
checksum += int(data[i], 16)
checksum &= 0xFF # 强制截断
return checksum
def read_bin(self, filename):
self.reset_data()
length = int(os.path.getsize(filename) / 1024)
if os.path.getsize(filename)/1024>length:
length = length+1
print("一共多少包:", length)
file = open(filename, 'rb')
i = 0
arr = []
m = 0
# 初始结束命令
zero = Constant.get_finish0('a')
self.finish_all = self.get_str(zero)
while 1:
if i >= 1024:
print(length)
print(m)
arr.insert(0, 'aa')
arr.insert(0, 'aa')
arr.insert(0, 'aa')
arr.insert(3, '27')
arr.insert(4, self.dec2hexstr(m))
arr.append('ee')
arr.append('ee')
arr.append('ee')
result = Constant.checkout_custom_long(arr[3:1029])
arr.append(result[2:4])
self.arrs.append(arr)
print(arr)
arr = []
m = m + 1
i = 0
if m == length:
self.show_message()
break
c = file.read(1)
ssss = str(binascii.b2a_hex(c))[2:-1]
if ssss == '':
ssss = 'FF'
arr.append(ssss)
i += 1
self.total = m
print("总共有多少数据:----------")
print(self.total)
file.close()
def get_str(self, arrss):
arrss.insert(0, 'aa')
arrss.insert(0, 'aa')
arrss.insert(0, 'aa')
arrss.insert(3, '28')
arrss.insert(4, self.dec2hexstr(0))
arrss.append('ee')
arrss.append('ee')
arrss.append('ee')
result = Constant.checkout_custom_long(arrss[3:1029])
arrss.append(result[2:4])
print(arrss)
print("*" * 50)
return arrss
def set_visiable(self, is_visiable=0):
if is_visiable == 0:
self.combobox_backup.setDisabled(False)
self.pushButton_backup.setDisabled(False)
self.pushButton_restart_remote.setDisabled(False)
else:
self.combobox_backup.setDisabled(True)
self.pushButton_backup.setDisabled(True)
self.pushButton_restart_remote.setDisabled(True)
# 3A当写入失败的时候开启是从更新区恢复还是从备份区恢复
def backup(self):
init_code = None
if self.combobox_backup.currentIndex() == 0:
print("从更新区恢复命令已经发送")
# 从更新区恢复
init_code = Constant.from_update_recover
elif self.combobox_backup.currentIndex() == 1:
print("从备份区恢复命令已经发送")
# 从备份区恢复
init_code = Constant.update_from_backup
else:
self.signal_write_msg.emit("【调试助手出现异常】")
return ""
# self.combobox_backup.setDisabled(False)
# self.pushButton_backup.setDisabled(False)
return init_code
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ui = TcpLogic(1)
btnDemo = MyDialog()
ui.show()
sys.exit(app.exec_())
| [
"hongb@suchness.cn"
] | hongb@suchness.cn |
1b2e41d605317135cb1b0f6791105af3b45236f1 | f9334d8747001e2cd0dcbd7b4f91da862ac0972c | /hints/parameters.py | 64d351c1f3922957f2f2ea79481b941b07744d52 | [] | no_license | hassanshamim/PyCon2018-Luigi | b93c79d0458e15bfd74b46c8a70aa0fd079ca77a | 1808f82bc541ab32cfa5fadd015e79d0cae8a0cf | refs/heads/master | 2020-03-16T21:21:43.587186 | 2018-05-12T04:41:39 | 2018-05-12T04:41:39 | 132,995,693 | 0 | 0 | null | 2018-05-11T05:57:00 | 2018-05-11T05:57:00 | null | UTF-8 | Python | false | false | 581 | py | import datetime
import luigi
# check out all the parameters: http://luigi.readthedocs.io/en/stable/api/luigi.parameter.html
class ParameterizedTask(luigi.Task):
example_str = luigi.Parameter(default='foo')
example_bool = luigi.BoolParameter(default=True)
example_int = luigi.IntParameter(default=0)
example_float = luigi.FloatParameter(default=10.5)
example_dict = luigi.DictParameter(default={'fizz': 'buzz'})
example_date = luigi.DateParameter(default=datetime.date.today())
example_choice = luigi.ChoiceParameter(choices=[1, 2, 3], var_type=int)
| [
"aehacker@us.ibm.com"
] | aehacker@us.ibm.com |
e9be9725fc7b0b9fa3f7aa5a0ec8cd44eea5c3eb | fbbe424559f64e9a94116a07eaaa555a01b0a7bb | /Keras_tensorflow_nightly/source2.7/tensorflow/contrib/model_pruning/python/layers/layers.py | 466daf204a1ae86a7f37107342046305ea7249fc | [
"MIT"
] | permissive | ryfeus/lambda-packs | 6544adb4dec19b8e71d75c24d8ed789b785b0369 | cabf6e4f1970dc14302f87414f170de19944bac2 | refs/heads/master | 2022-12-07T16:18:52.475504 | 2022-11-29T13:35:35 | 2022-11-29T13:35:35 | 71,386,735 | 1,283 | 263 | MIT | 2022-11-26T05:02:14 | 2016-10-19T18:22:39 | Python | UTF-8 | Python | false | false | 15,360 | py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tensorflow layers with added variables for parameter masking.
Branched from tensorflow/contrib/layers/python/layers/layers.py
"""
# pylint: disable=missing-docstring
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from tensorflow.contrib.framework.python.ops import add_arg_scope
from tensorflow.contrib.framework.python.ops import variables
from tensorflow.contrib.layers.python.layers import initializers
from tensorflow.contrib.layers.python.layers import utils
from tensorflow.contrib.model_pruning.python.layers import core_layers as core
from tensorflow.python.framework import ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables as tf_variables
def _model_variable_getter(getter,
name,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=True,
collections=None,
caching_device=None,
partitioner=None,
rename=None,
use_resource=None,
**_):
"""Getter that uses model_variable for compatibility with core layers."""
short_name = name.split('/')[-1]
if rename and short_name in rename:
name_components = name.split('/')
name_components[-1] = rename[short_name]
name = '/'.join(name_components)
return variables.model_variable(
name,
shape=shape,
dtype=dtype,
initializer=initializer,
regularizer=regularizer,
collections=collections,
trainable=trainable,
caching_device=caching_device,
partitioner=partitioner,
custom_getter=getter,
use_resource=use_resource)
def _build_variable_getter(rename=None):
"""Build a model variable getter that respects scope getter and renames."""
# VariableScope will nest the getters
def layer_variable_getter(getter, *args, **kwargs):
kwargs['rename'] = rename
return _model_variable_getter(getter, *args, **kwargs)
return layer_variable_getter
def _add_variable_to_collections(variable, collections_set, collections_name):
"""Adds variable (or all its parts) to all collections with that name."""
collections = utils.get_variable_collections(collections_set,
collections_name) or []
variables_list = [variable]
if isinstance(variable, tf_variables.PartitionedVariable):
variables_list = [v for v in variable]
for collection in collections:
for var in variables_list:
if var not in ops.get_collection(collection):
ops.add_to_collection(collection, var)
@add_arg_scope
def masked_convolution(inputs,
num_outputs,
kernel_size,
stride=1,
padding='SAME',
data_format=None,
rate=1,
activation_fn=nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=init_ops.zeros_initializer(),
biases_regularizer=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None):
"""Adds an 2D convolution followed by an optional batch_norm layer.
The layer creates a mask variable on top of the weight variable. The input to
the convolution operation is the elementwise multiplication of the mask
variable and the weigh
It is required that 1 <= N <= 3.
`convolution` creates a variable called `weights`, representing the
convolutional kernel, that is convolved (actually cross-correlated) with the
`inputs` to produce a `Tensor` of activations. If a `normalizer_fn` is
provided (such as `batch_norm`), it is then applied. Otherwise, if
`normalizer_fn` is None and a `biases_initializer` is provided then a `biases`
variable would be created and added the activations. Finally, if
`activation_fn` is not `None`, it is applied to the activations as well.
Performs atrous convolution with input stride/dilation rate equal to `rate`
if a value > 1 for any dimension of `rate` is specified. In this case
`stride` values != 1 are not supported.
Args:
inputs: A Tensor of rank N+2 of shape
`[batch_size] + input_spatial_shape + [in_channels]` if data_format does
not start with "NC" (default), or
`[batch_size, in_channels] + input_spatial_shape` if data_format starts
with "NC".
num_outputs: Integer, the number of output filters.
kernel_size: A sequence of N positive integers specifying the spatial
dimensions of of the filters. Can be a single integer to specify the same
value for all spatial dimensions.
stride: A sequence of N positive integers specifying the stride at which to
compute output. Can be a single integer to specify the same value for all
spatial dimensions. Specifying any `stride` value != 1 is incompatible
with specifying any `rate` value != 1.
padding: One of `"VALID"` or `"SAME"`.
data_format: A string or None. Specifies whether the channel dimension of
the `input` and output is the last dimension (default, or if `data_format`
does not start with "NC"), or the second dimension (if `data_format`
starts with "NC"). For N=1, the valid values are "NWC" (default) and
"NCW". For N=2, the valid values are "NHWC" (default) and "NCHW".
For N=3, the valid values are "NDHWC" (default) and "NCDHW".
rate: A sequence of N positive integers specifying the dilation rate to use
for atrous convolution. Can be a single integer to specify the same
value for all spatial dimensions. Specifying any `rate` value != 1 is
incompatible with specifying any `stride` value != 1.
activation_fn: Activation function. The default value is a ReLU function.
Explicitly set it to None to skip it and maintain a linear activation.
normalizer_fn: Normalization function to use instead of `biases`. If
`normalizer_fn` is provided then `biases_initializer` and
`biases_regularizer` are ignored and `biases` are not created nor added.
default set to None for no normalizer function
normalizer_params: Normalization function parameters.
weights_initializer: An initializer for the weights.
weights_regularizer: Optional regularizer for the weights.
biases_initializer: An initializer for the biases. If None skip biases.
biases_regularizer: Optional regularizer for the biases.
reuse: Whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
variables_collections: Optional list of collections for all the variables or
a dictionary containing a different list of collection per variable.
outputs_collections: Collection to add the outputs.
trainable: If `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).
scope: Optional scope for `variable_scope`.
Returns:
A tensor representing the output of the operation.
Raises:
ValueError: If `data_format` is invalid.
ValueError: Both 'rate' and `stride` are not uniformly 1.
"""
if data_format not in [None, 'NWC', 'NCW', 'NHWC', 'NCHW', 'NDHWC', 'NCDHW']:
raise ValueError('Invalid data_format: %r' % (data_format,))
layer_variable_getter = _build_variable_getter({
'bias': 'biases',
'kernel': 'weights'
})
with variable_scope.variable_scope(
scope, 'Conv', [inputs], reuse=reuse,
custom_getter=layer_variable_getter) as sc:
inputs = ops.convert_to_tensor(inputs)
input_rank = inputs.get_shape().ndims
if input_rank == 3:
raise ValueError('Sparse Convolution not supported for input with rank',
input_rank)
elif input_rank == 4:
layer_class = core.MaskedConv2D
elif input_rank == 5:
raise ValueError('Sparse Convolution not supported for input with rank',
input_rank)
else:
raise ValueError('Sparse Convolution not supported for input with rank',
input_rank)
if data_format is None or data_format == 'NHWC':
df = 'channels_last'
elif data_format == 'NCHW':
df = 'channels_first'
else:
raise ValueError('Unsupported data format', data_format)
layer = layer_class(
filters=num_outputs,
kernel_size=kernel_size,
strides=stride,
padding=padding,
data_format=df,
dilation_rate=rate,
activation=None,
use_bias=not normalizer_fn and biases_initializer,
kernel_initializer=weights_initializer,
bias_initializer=biases_initializer,
kernel_regularizer=weights_regularizer,
bias_regularizer=biases_regularizer,
activity_regularizer=None,
trainable=trainable,
name=sc.name,
dtype=inputs.dtype.base_dtype,
_scope=sc,
_reuse=reuse)
outputs = layer.apply(inputs)
# Add variables to collections.
_add_variable_to_collections(layer.kernel, variables_collections, 'weights')
if layer.use_bias:
_add_variable_to_collections(layer.bias, variables_collections, 'biases')
if normalizer_fn is not None:
normalizer_params = normalizer_params or {}
outputs = normalizer_fn(outputs, **normalizer_params)
if activation_fn is not None:
outputs = activation_fn(outputs)
return utils.collect_named_outputs(outputs_collections,
sc.original_name_scope, outputs)
masked_conv2d = masked_convolution
@add_arg_scope
def masked_fully_connected(
inputs,
num_outputs,
activation_fn=nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=init_ops.zeros_initializer(),
biases_regularizer=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None):
"""Adds a sparse fully connected layer. The weight matrix is masked.
`fully_connected` creates a variable called `weights`, representing a fully
connected weight matrix, which is multiplied by the `inputs` to produce a
`Tensor` of hidden units. If a `normalizer_fn` is provided (such as
`batch_norm`), it is then applied. Otherwise, if `normalizer_fn` is
None and a `biases_initializer` is provided then a `biases` variable would be
created and added the hidden units. Finally, if `activation_fn` is not `None`,
it is applied to the hidden units as well.
Note: that if `inputs` have a rank greater than 2, then `inputs` is flattened
prior to the initial matrix multiply by `weights`.
Args:
inputs: A tensor of at least rank 2 and static value for the last dimension;
i.e. `[batch_size, depth]`, `[None, None, None, channels]`.
num_outputs: Integer or long, the number of output units in the layer.
activation_fn: Activation function. The default value is a ReLU function.
Explicitly set it to None to skip it and maintain a linear activation.
normalizer_fn: Normalization function to use instead of `biases`. If
`normalizer_fn` is provided then `biases_initializer` and
`biases_regularizer` are ignored and `biases` are not created nor added.
default set to None for no normalizer function
normalizer_params: Normalization function parameters.
weights_initializer: An initializer for the weights.
weights_regularizer: Optional regularizer for the weights.
biases_initializer: An initializer for the biases. If None skip biases.
biases_regularizer: Optional regularizer for the biases.
reuse: Whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
variables_collections: Optional list of collections for all the variables or
a dictionary containing a different list of collections per variable.
outputs_collections: Collection to add the outputs.
trainable: If `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).
scope: Optional scope for variable_scope.
Returns:
The tensor variable representing the result of the series of operations.
Raises:
ValueError: If x has rank less than 2 or if its last dimension is not set.
"""
if not isinstance(num_outputs, six.integer_types):
raise ValueError('num_outputs should be int or long, got %s.' %
(num_outputs,))
layer_variable_getter = _build_variable_getter({
'bias': 'biases',
'kernel': 'weights'
})
with variable_scope.variable_scope(
scope,
'fully_connected', [inputs],
reuse=reuse,
custom_getter=layer_variable_getter) as sc:
inputs = ops.convert_to_tensor(inputs)
layer = core.MaskedFullyConnected(
units=num_outputs,
activation=None,
use_bias=not normalizer_fn and biases_initializer,
kernel_initializer=weights_initializer,
bias_initializer=biases_initializer,
kernel_regularizer=weights_regularizer,
bias_regularizer=biases_regularizer,
activity_regularizer=None,
trainable=trainable,
name=sc.name,
dtype=inputs.dtype.base_dtype,
_scope=sc,
_reuse=reuse)
outputs = layer.apply(inputs)
# Add variables to collections.
_add_variable_to_collections(layer.kernel, variables_collections, 'weights')
if layer.bias is not None:
_add_variable_to_collections(layer.bias, variables_collections, 'biases')
# Apply normalizer function / layer.
if normalizer_fn is not None:
if not normalizer_params:
normalizer_params = {}
outputs = normalizer_fn(outputs, **normalizer_params)
if activation_fn is not None:
outputs = activation_fn(outputs)
return utils.collect_named_outputs(outputs_collections,
sc.original_name_scope, outputs)
| [
"ryfeus@gmail.com"
] | ryfeus@gmail.com |
fe6a4f75903b214d2729c47e622c6bb31e86b8e4 | 10165fce7cd9ee32a488c1fbf36b17b4951bc6f6 | /form_template/migrations/0002_alter_template_created.py | 4ca195858c13f124e750dee248c7cf52e2d36e59 | [] | no_license | silvareal/formplus_backend_test | 3a08839f6f35dabcffba5683fb3f606b344d0999 | 2df537462abcead48591737cae1b833fa4011b56 | refs/heads/master | 2023-07-21T04:49:30.004838 | 2021-09-05T12:55:48 | 2021-09-05T12:55:48 | 399,594,639 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 375 | py | # Generated by Django 3.2.6 on 2021-08-28 08:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('form_template', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='template',
name='created',
field=models.DateTimeField(),
),
]
| [
"sylvernus@glade.ng"
] | sylvernus@glade.ng |
2832317445d8bab858ee91119facaec6ec590920 | 0ed7c1e25a7fbaadcfb92a265319aabe24a6a13b | /qualitative2.py | 79074b14a223b087627a11ecaff2246127b2ca5b | [] | no_license | Charles1104/General_Assembly | af9d59b720b3914706d04789ca0bee20fb31eb1f | 50e7f389440d3e3914a885c833bce0a8131f51d0 | refs/heads/master | 2021-01-01T04:04:24.460197 | 2017-07-14T13:23:41 | 2017-07-14T13:23:41 | 97,118,214 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 772 | py | import pandas as pd
import numpy as np
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
import matplotlib.pyplot as plt
import thinkplot
import thinkstats2
from scipy import stats
# Read the data file
data = pd.read_csv('dataset.csv', encoding="ISO-8859-1")
data['status_binary'] = data.status.apply(lambda x: 1 if x == "successful" else 0)
# histogram of goal for successful and live projects
succ = data[data.status_binary == 1]
print(min(succ.goal), max(succ.goal), stats.mode(succ.goal))
bins = np.linspace(0, 100000, 100)
digitized = np.digitize(succ.goal, bins)
print(digitized)
hist1, bin_edges = np.histogram(digitized, bins=range(100))
plt.bar(bin_edges[:-1], hist1, width=0.9)
plt.xlim(min(bin_edges), max(bin_edges))
plt.show() | [
"charles.xavier.verleyen@gmail.com"
] | charles.xavier.verleyen@gmail.com |
327f2f2026f9430ca3193723156557269c394afc | 5829832fde945839791862325ba65f5dcf572bf1 | /lib/api_lib/teacher/teacher_zsq_urls.py | 16e5d8ef21dcd50968f7d20e4043b1fb7c34ded5 | [] | no_license | tianyantao/utm | 3a8d177918611f8084cfca28073e59b59607b949 | fd10f371a6aeb3699876fb823e6f705ab24110e4 | refs/heads/master | 2023-01-19T09:53:26.735929 | 2020-11-23T12:52:18 | 2020-11-23T12:52:18 | 315,312,748 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,730 | py | from config.config_case import ConfigCase
class TeacherZsqUrls:
def init_zsq_urls(self):
configcase = ConfigCase()
baseurl = "{}://{}".format(configcase.PROTOCOL, configcase.HOST_WEB)
edu_baseurl = "{}://{}".format(configcase.PROTOCOL, configcase.HOST_TEACHER)
'''新高一'''
self.answer_getAnswerCountsState = baseurl + '/api/holidayprod/answer/getAnswerCountsState'
self.student_getTextbookVersion = baseurl + '/api/holidayprod/student/getTextbookVersion'
self.student_getNotice = baseurl + '/api/holidayprod/student/getNotice'
self.student_getMemberDetailsPage = baseurl + '/api/holidayprod/student/getMemberDetailsPage'
self.meal_getMealDetail = baseurl + '/api/holidayprod/meal/getMealDetail'
self.meal_getWeaknessMealDetail = baseurl + '/api/holidayprod/meal/getWeaknessMealDetail'
self.meal_getInterestMealDetail = baseurl + '/api/holidayprod/meal/getInterestMealDetail'
self.reward_rewardPopup = baseurl + '/api/holidayprod/reward/rewardPopup'
self.reward_seriesPartakeRewardPopup = baseurl + '/api/holidayprod/reward/seriesPartakeRewardPopup'
self.reward_seriesChallengeRewardPopup = baseurl + '/api/holidayprod/reward/seriesChallengeRewardPopup'
self.answer_getAnswerCountsState = baseurl + '/api/holidayprod/answer/getAnswerCountsState'
self.answer_beginAnswer = baseurl + '/api/holidayprod/answer/beginAnswer'
self.answer_getTodayAnswerRank = baseurl + '/api/holidayprod/answer/getTodayAnswerRank'
self.answer_getHistoryAnswerRank = baseurl + '/api/holidayprod/answer/getHistoryAnswerRank'
self.read_getPcTuoZhanTiSheng = baseurl + '/api/holidayprod/read/getPcTuoZhanTiSheng'
self.read_getAppTuoZhanTiSheng = baseurl + '/api/holidayprod/read/getAppTuoZhanTiSheng'
self.read_getMasterpiece = baseurl + '/api/holidayprod/read/getMasterpiece'
self.read_getRecommend = baseurl + '/api/holidayprod/read/getRecommend'
self.read_getBanner = baseurl + '/api/holidayprod/read/getBanner'
self.read_getStudentPcBanner = baseurl + '/api/holidayprod/read/getStudentPcBanner'
self.read_getStudentAppBanner = baseurl + '/api/holidayprod/read/getStudentAppBanner'
self.newStudent_getHomeworkState = baseurl + '/api/holidayprod/newStudent/getHomeworkState'
self.live_getSingleLive = baseurl + '/api/holidayprod/live/getSingleLive'
self.newTeacher_getCategoryTree = baseurl + '/api/holidayprod/newTeacher/getCategoryTree'
self.newTeacher_getStandardResource = baseurl + '/api/holidayprod/newTeacher/getStandardResource'
self.newStudent_getSchoolVideoInfo = baseurl + '/api/holidayprod/newStudent/getSchoolVideoInfo'
self.newStudent_getHomeworkProgress = baseurl + '/api/holidayprod/newStudent/getHomeworkProgress'
self.newTeacher_getState = baseurl + '/api/holidayprod/newTeacher/getState'
self.newTeacher_listLessonSchedule = baseurl + '/api/holidayprod/newTeacher/listLessonSchedule'
self.newTeacher_listSubjectVersion = baseurl + '/api/holidayprod/newTeacher/listSubjectVersion'
self.newTeacher_getTeacherCustom = baseurl + '/api/holidayprod/newTeacher/getTeacherCustom'
self.newTeacher_getAssignedHomeworkMaterial = baseurl + '/api/holidayprod/newTeacher/getAssignedHomeworkMaterial'
self.newStudent_getHomeworkInfo = baseurl + '/api/holidayprod/newStudent/getHomeworkInfo'
self.newStudent_listJoinClass = baseurl + '/api/holidayprod/newStudent/listJoinClass'
'''德育中心'''
self.moralEdu_homepageStatistics = edu_baseurl + '/api/eteacherproduct/moralEdu/homepageStatistics'
self.moralEdu_listGrades = edu_baseurl + '/api/eteacherproduct/moralEdu/listGrades'
self.moralEdu_getClassMeetingStatistics = edu_baseurl + '/api/eteacherproduct/moralEdu/getClassMeetingStatistics'
self.moralEdu_getClassMeetingList = edu_baseurl + '/api/eteacherproduct/moralEdu/getClassMeetingList'
self.moralEdu_getClassMeetingDetail = edu_baseurl + '/api/eteacherproduct/moralEdu/getClassMeetingDetail'
self.moralEdu_getGetEvaluationList = edu_baseurl + '/api/eteacherproduct/moralEdu/getGetEvaluationList'
self.moralEdu_getGetEvaluationDetail = edu_baseurl + '/api/eteacherproduct/moralEdu/getGetEvaluationDetail'
self.moralEdu_getTeacherClassRoomList = edu_baseurl + '/api/eteacherproduct/moralEdu/getTeacherClassRoomList'
self.moralEdu_getMoralEduCourseList = edu_baseurl + '/api/eteacherproduct/moralEdu/getMoralEduCourseList'
self.moralEdu_getStudentProblemManual = edu_baseurl + '/api/eteacherproduct/moralEdu/getStudentProblemManual'
self.moralEdu_report_parentsCourseViews = edu_baseurl + '/api/eteacherproduct/moralEdu/report/parentsCourseViews'
self.moralEdu_report_parentsCourseViewDetail = edu_baseurl + '/api/eteacherproduct/moralEdu/report/parentsCourseViewDetail'
self.moralEdu_report_parentsCourseViewDetail_export = edu_baseurl + '/api/eteacherproduct/moralEdu/report/parentsCourseViewDetail/export'
self.moralEdu_report_schoolCourseInfo = edu_baseurl + '/api/eteacherproduct/moralEdu/report/schoolCourseInfo'
self.moralEdu_report_schoolCourseInfo_export = edu_baseurl + '/api/eteacherproduct/moralEdu/report/schoolCourseInfo/export'
self.moralEdu_report_teacherView = edu_baseurl + '/api/eteacherproduct/moralEdu/report/teacherView'
self.moralEdu_report_teacherView_export = edu_baseurl + '/api/eteacherproduct/moralEdu/report/teacherView/export'
self.moralEdu_report_resourceRank = edu_baseurl + '/api/eteacherproduct/moralEdu/report/resourceRank'
self.moralEdu_report_teacherView_export = edu_baseurl + '/api/eteacherproduct/moralEdu/report/teacherView/export'
self.moralEdu_gradeClassList = edu_baseurl + '/api/eteacherproduct/moralEdu/gradeClassList'
self.moralEdu_getCategory = edu_baseurl + '/api/eteacherproduct/moralEdu/getCategory'
self.moralEdu_parentsEdu_list = edu_baseurl + '/api/eteacherproduct/moralEdu/parentsEdu/list'
self.moralEdu_report_teacherView = edu_baseurl + '/api/eteacherproduct/moralEdu/report/teacherView'
self.moralEdu_report_resourceRank_export = edu_baseurl + '/api/eteacherproduct/moralEdu/report/resourceRank/export'
self.moralEdu_report_parentsCourseViews_export = edu_baseurl + '/api/eteacherproduct/moralEdu/report/parentsCourseViews/export'
self.moralEdu_getMoralResource_list = edu_baseurl + '/api/eteacherproduct/moralEdu/getMoralResource/list'
self.eteacherproduct_school_getSchoolUserInfo = edu_baseurl + '/api/eteacherproduct/school/getSchoolUserInfo'
| [
"tianyantao@mistong.com"
] | tianyantao@mistong.com |
feb9633db3d20c6b74ee61d787c50bb6d7521d87 | 55e414fe2c3c89bc6c9eae702ff8fb6373d5fad8 | /tests/source_test.py | 6a94d8e8d90c35697ca82e61bad45e0f2675cf8b | [
"MIT"
] | permissive | rashidaysher/news-app | ab7ae5e9d474ec9cac1b135a742ec151997a5800 | 9e63fb2308f11d119631cfeaec1720fb25928f7c | refs/heads/master | 2023-08-10T21:49:19.299945 | 2021-09-20T06:43:34 | 2021-09-20T06:43:34 | 405,065,066 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 421 | py | import unittest
from app.models import Sources
class SourceTest(unittest.TestCase):
"""
Test class to test the behaviour of the news class
"""
def setUp(self):
"""
"""
self.new_source = Sources('Test id','Test name','Test description','Test author', 'Test publishedAt', 'Test title')
def test_instance(self):
self.assertTrue(isinstance(self.new_source,Sources))
| [
"aisha.ahmed@student.moringaschool.com"
] | aisha.ahmed@student.moringaschool.com |
89a79c876ce5c4c0c52c8afbef6bf3a4c8319b64 | 8f38ebd83a5d4f6c5c6355e0f93628ae24ae14e1 | /pdf_image1.py | 5b809324196af5db7c872fba643d7cb92c83dfc9 | [] | no_license | muhammedhassanm/Deep_Learning | e05df2389f62a99295b146dc605d8380e007cf2a | bae9d17ed60ad184687e032744c723cb7af7dcdc | refs/heads/master | 2022-11-12T02:32:31.901599 | 2020-10-22T10:42:35 | 2020-10-22T10:42:35 | 222,718,082 | 0 | 0 | null | 2022-11-04T19:08:53 | 2019-11-19T14:42:03 | Jupyter Notebook | UTF-8 | Python | false | false | 879 | py | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 13 17:22:13 2019
@author: 100119
"""
import os
import time
import uuid
#import tempfile
from pdf2image import convert_from_path
start = time.time()
PDF_DIR = 'C:/Users/100119/Desktop/PRUDENTIAL/CREDIT_CARD_NO_MASKING/data/Forms'
save_dir ='C:/Users/100119/Desktop/PRUDENTIAL/CREDIT_CARD_NO_MASKING/data/images'
for pdf in os.listdir(PDF_DIR):
filename = os.path.join(PDF_DIR,pdf)
print(filename)
pages = convert_from_path(filename, dpi=200,fmt="jpg", output_file=str(uuid.uuid4()),\
output_folder=save_dir,thread_count=2)
# base_filename = os.path.splitext(os.path.basename(filename))[0]
# count = 1
# for page in pages:
# page.save(save_dir + '/' + base_filename + '_'+ str(count) + '.jpg')
# count += 1
print("Time:\t", round(time.time()-start,3),"\nDone") | [
"31989237+muhammedhassanm@users.noreply.github.com"
] | 31989237+muhammedhassanm@users.noreply.github.com |
a7bde11c9a4a828fb8f86b1dac174e06132e0a01 | acd374bef15b7f826a2407bb7e7093967a48abda | /nsl/ast/__init__.py | f8acba9af38f3f7fc27a3e46350bd8a1e6196a7b | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | Anteru/nsl | 7402e8fe747a27c3cc564b86317ed9a92c61cc3a | a8c8ca793087c4bd33a6bc640ec58ee3f0a6ba12 | refs/heads/main | 2022-10-08T12:50:10.237980 | 2022-09-18T11:52:13 | 2022-09-18T11:52:13 | 134,078,943 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 22,816 | py | import collections
import collections.abc
from nsl import op, types, Visitor
from enum import Enum
import bisect
from typing import List
class SourceMapping:
def __init__(self, source, sourceName = '<unknown>'):
self.__sourceName = sourceName
self.__lineOffsets = []
currentOffset = 0
for line in source.split ('\n'):
self.__lineOffsets.append(currentOffset)
currentOffset += len (line) + 1 # trailing \n
def GetLineFromOffset(self, offset):
return bisect.bisect_right(self.__lineOffsets, offset) - 1
def GetLineStartOffset(self, line):
return self.__lineOffsets[line]
def GetSourceName(self):
return self.__sourceName
class Location:
def __init__(self, span, sourceMapping = None):
assert span[1] >= span [0]
self.__span = span
self.__sourceMapping = sourceMapping
@classmethod
def Merge (cls, *args):
assert len(args) > 0
result = args[0].__span
mapping = args[0].__sourceMapping
for arg in args [1:]:
assert isinstance (arg, Location)
end = max (result [1], arg.GetEnd ())
start = min (result [0], arg.GetBegin ())
result = (start, end, )
return cls(result, mapping)
def GetBegin(self):
return self.__span [0]
def GetEnd(self):
return self.__span [1]
@property
def IsUnknown(self):
return self.__span == (-1, -1)
def __str__(self):
if self.IsUnknown:
return '<unknown>'
if self.__sourceMapping:
# Lines are 0 based (as are columns), and we need to offset
# with +1 for display
startLine = self.__sourceMapping.GetLineFromOffset (self.GetBegin ())
endLine = self.__sourceMapping.GetLineFromOffset (self.GetEnd ())
if startLine == endLine:
startOffset = self.__sourceMapping.GetLineStartOffset(startLine)
return '{}:{}-{}'.format (
startLine + 1,
self.GetBegin () - startOffset + 1,
self.GetEnd () - startOffset + 1)
else:
startOffset = self.__sourceMapping.GetLineStartOffset (startLine)
endOffset = self.__sourceMapping.GetLineStartOffset(endLine)
return '{}:{}-{}:{}'.format (
startLine + 1,
self.GetBegin () - startOffset + 1,
endLine + 1,
self.GetEnd () - endOffset + 1)
else:
return '[{},{})'.format (self.GetBegin (), self.GetEnd ())
def __repr__(self):
return 'Location({})'.format (repr(self.__span))
class Node(Visitor.Node):
def __init__(self):
self.__location = Location((-1, -1))
def Clone(self):
import copy
return copy.deepcopy(self)
def SetLocation(self, location):
assert isinstance(location, Location)
self.__location = location
def GetLocation(self):
return self.__location
class Module (Node):
'''A single translation module.
A module consists of types, variables and functions.'''
def __init__(self):
super().__init__()
self.__variables = list ()
self.__functions = list ()
# Types may depend on types which are previously defined
# Ensure ordering by using an ordered dict
self.__types = collections.OrderedDict ()
self.__imports = set()
def _Traverse (self, function):
self.__types = function(self.__types)
self.__variables = function(self.__variables)
self.__functions = function(self.__functions)
def AddDeclaration (self, variable):
self.__variables.append (variable)
def AddFunction(self, func):
self.__functions.append (func)
def AddType (self, decl):
self.__types [decl.GetName ()] = decl
def AddImport(self, name):
self.__imports.add((name))
def GetDeclarations (self):
return self.__variables
def GetTypes(self):
return self.__types.values ()
def GetFunctions(self):
return self.__functions
def GetImports(self):
return self.__imports
def __str__(self):
return '''Module ({0} variable(s), {1} function(s), {2} type(s))'''.format(
len(self.__variables), len(self.__functions), len (self.__types))
class Expression(Node):
def __init__(self, children=[]):
super().__init__()
self.children = children
self.__type = None
def GetType(self):
return self.__type
def SetType(self, nslType):
'''The type of this expression. This depends on the specific expression type,
for instance, for a call expression this will be a function type, while for
an unary expression it will be a primitive or structure type.'''
assert not isinstance(nslType, types.UnresolvedType)
self.__type = nslType
def _Traverse(self, function):
self.children = function(self.children)
def __iter__(self):
return self.children.__iter__()
class UnaryExpression(Expression):
pass
class EmptyExpression(Expression):
def __init__(self):
super().__init__()
class CastExpression(UnaryExpression):
def __init__(self, expr, targetType, implicit = False):
super().__init__([expr])
assert isinstance (targetType, types.PrimitiveType)
self.SetType (targetType)
self.__implicit = implicit
def IsImplicit(self):
return self.__implicit
def GetArgument(self):
return self.children[0]
def __str__(self):
return '{} ({})'.format (self.GetType(), self.GetArgument())
def __repr__(self):
return 'CastExpression ({}, {}, {})'.format (
repr(self.GetArgument()),
repr (self.GetType ()), self.IsImplicit ())
class ConstructPrimitiveExpression(UnaryExpression):
'''Expression of the type primitive_type (expr, ...).'''
def __init__(self, targetType, expressions):
super().__init__(expressions)
assert isinstance (targetType, types.PrimitiveType)
self.SetType (targetType)
def __str__(self):
return '{} ({})'.format (self.GetType ().GetName (),
', '.join ([str(expr) for expr in self.children]))
def GetArguments(self):
return self.children
def SetArguments(self, args):
self.children = args
class CallExpression(UnaryExpression):
"""A function call of the form ID ([expr], ...). ID references
an unresolved function type at first."""
def __init__(self, function: types.Type, expressions: List[Expression]):
super().__init__(expressions)
self.function = function
def __str__(self):
r = self.function.GetName () + ' ('
r += ', '.join(['{0}'.format(str(expr)) for expr in self.children])
return r + ')'
def GetArguments(self):
return self.children
def SetArguments(self, arguments: List[Expression]):
self.children = arguments
def GetFunction(self) -> types.Type:
return self.function
def ResolveType(self, scope):
self.function = types.ResolveFunction(self.function,
scope, [expr.GetType() for expr in self.GetArguments ()])
assert isinstance(self.function, types.Function)
class VariableAccessExpression(UnaryExpression):
pass
class ArrayExpression(VariableAccessExpression):
'''Expression of the form 'id[expr]', where id can be a nested
access expression itself.'''
def __init__(self, identifier, expression):
super().__init__()
self.id = identifier
self._expression = expression
def GetParent(self):
return self.id
def GetExpression(self):
return self._expression
def SetExpression(self, expr):
self._expression = expr
def _Traverse(self, function):
self.id = function(self.id)
self._expression = function(self._expression)
def __str__(self):
return str(self.id) + ' [' + str(self._expression) + ']'
class MemberAccessExpression(VariableAccessExpression):
'''Expression of the form 'id.member', where id can be a
access nested expression itself.
A member access expression can be a swizzle. If so, ``isSwizzle`` should be
set to ``True``.'''
def __init__(self, identifier, member):
super().__init__()
self.id = identifier
self.member = member
self.isSwizzle = False
def GetMember(self):
return self.member
def GetParent(self):
return self.id
def _Traverse(self, function):
self.id = function(self.id)
self.member = function(self.member)
def SetSwizzle(self, isSwizzle: bool) -> None:
self.isSwizzle = isSwizzle
def __str__(self):
return str(self.id) + '.' + str(self.member)
class BinaryExpression(Expression):
def __init__(self, op, left, right):
super().__init__([left, right])
self.op = op
self._operator = None
def GetLeft(self):
return self.children [0]
def GetRight(self):
return self.children [1]
def SetLeft(self, left):
self.children [0] = left
def SetRight(self, right):
self.children [1] = right
def GetOperation(self):
'''The the operation.'''
return self.op
def GetOperator(self):
'''Get the used operator. This is an instance of ExpressionType.'''
return self._operator
def ResolveType (self, left, right):
self._operator = types.ResolveBinaryExpressionType (self.op, left, right)
def __str__(self):
r = ''
if (isinstance (self.GetLeft (), BinaryExpression)):
r += '(' + str (self.GetLeft ()) + ')'
else:
r += str (self.GetLeft ())
r += ' ' + op.OpToStr(self.op) + ' '
if (isinstance (self.GetRight (), BinaryExpression)):
r += '(' + str (self.GetRight ()) + ')'
else:
r += str (self.GetRight ())
return r
class AssignmentExpression(BinaryExpression):
def __init__(self, left, right, *, operation=op.Operation.ASSIGN):
super().__init__(operation, left, right)
def ResolveType(self, left, right):
self._operator = types.ExpressionType (self.GetLeft().GetType (),
[self.GetLeft ().GetType(),
self.GetRight ().GetType ()])
class Affix:
PRE = 1
POST = 2
class AffixExpression(UnaryExpression):
def __init__(self, op, expr, affix):
super().__init__([expr])
self.op = op
self.affix = affix
def IsPostfix (self):
return self.affix == Affix.POST
def IsPrefix (self):
return self.affix == Affix.PRE
def GetOperation (self):
return self.op
def GetExpression(self):
return self.children[0]
def __str__(self):
if self.affix == Affix.PRE:
if self.op == op.Operation.ADD:
return f'++{self.children[0]}'
elif self.op == op.Operation.SUB:
return f'--{self.children[0]}'
elif self.affix == Affix.POST:
if self.op == op.Operation.ADD:
return f'{self.children[0]}++'
elif self.op == op.Operation.SUB:
return f'{self.children[0]}--'
class LiteralExpression(UnaryExpression):
def __init__(self, value, literalType):
super().__init__()
self.value = value
self.SetType (literalType)
def GetValue(self):
return self.value
def __str__(self):
return str (self.value)
class PrimaryExpression(UnaryExpression):
def __init__(self, identifier):
super().__init__()
self.identifier = identifier
def GetName(self):
return self.identifier
def __str__(self):
return self.identifier
class InvalidStructureDefinitionException(Exception):
def __init__(self, structName: str, memberName: str):
self.structName = structName
self.memberName = memberName
class StructureDefinition(Node):
def __init__(self, name, fields = list()):
super().__init__()
self.__name = name
self.__fields = fields
self.__type = types.UnresolvedType (name)
# Check that all element names are unique
fieldNames = set()
for field in fields:
if field.GetName () in fieldNames:
raise InvalidStructureDefinitionException(name, field.GetName())
fieldNames.add (field.GetName ())
self.__annotations = []
def _Traverse(self, function):
self.__fields = function(self.__fields)
def AddAnnotation (self, annotation):
assert isinstance(annotation, Annotation)
self.__annotations.append (annotation)
def GetAnnotations(self):
return self.__annotations
def GetName(self):
return self.__name
def __str__(self):
return 'struct {0} ({1} field(s))'.format (self.GetName (), len (self.GetFields()))
def GetFields (self):
return self.__fields
def SetType(self, structType):
assert isinstance (structType, types.StructType)
self.__type = structType
def GetType(self):
return self.__type
class InterfaceDefinition(Node):
def __init__(self, name, methods = list ()):
super().__init__()
self.__name = name
self.__methods = methods
self.__type = types.UnresolvedType (name)
def _Traverse(self, function):
self.__methods = function(self.__methods)
def GetMethods (self):
return self.__methods
def GetName (self):
return self.__name
def SetType(self, interfaceType):
assert isinstance (interfaceType, types.ClassType)
self.__type = interfaceType
def GetType(self):
return self.__type
class VariableDeclaration(Node):
def __init__(self, variableType, symbol,
initExpression = None):
super().__init__()
self.__symbol = symbol
self.__initializer = initExpression
self.__type = variableType
def ResolveType(self, scope):
self.__type = types.ResolveType(self.__type, scope)
return self.__type
def _Traverse(self, function):
self.__initializer = function(self.__initializer)
def __str__(self):
if not self.__type.NeedsResolve ():
if self.__type.IsArray ():
result = str(self.__type.GetComponentType ()) + ' ' + str(self.GetName ()) + '[' + ', '.join(map(str, self.__type.GetSize())) + ']'
else:
result = str(self.__type) + ' ' + str(self.GetName ())
else:
result = self.GetName ()
if (self.HasInitializerExpression ()):
result += '= ' + str(self.__initializer)
return result
def GetType(self):
return self.__type
def GetName(self):
return self.__symbol
def HasInitializerExpression(self):
return self.__initializer is not None
def GetInitializerExpression(self):
return self.__initializer
class ArgumentModifier(Enum):
Optional = 1
class Argument(Node):
'''Function argument. Captures the type (potentially a Type or
UnresolvedType) and the name of the argument.'''
def __init__(self, argumentType, name = None, modifiers = set()):
super().__init__()
self.__type = argumentType
self.__name = name
self.__modifiers = modifiers
def ResolveType(self, scope):
self.__type = types.ResolveType(self.__type, scope)
return self.__type
def GetType(self):
return self.__type
def GetName(self):
return self.__name
def HasName (self):
return self.__name is not None
def GetModifiers(self):
return self.__modifiers
def IsOptional(self):
return ArgumentModifier.Optional in self.__modifiers
def __str__(self):
if self.__name is not None:
return '{} {}'.format (self.__type.GetName (), self.__name)
else:
return '{} <unnamed>'.format (self.__type.GetName ())
class Function(Node):
def __init__(self, name, arguments = list (),
returnType = types.Void (), body = None,
*,
isForwardDeclaration = False,
isExported = False):
super().__init__()
self.name = name
self.__body = body
self.__type = types.Function (name, returnType, arguments, isExported)
self.arguments = arguments
self.isForwardDeclaration = isForwardDeclaration
self.isExported = isExported
def ResolveType(self, scope):
for arg in self.arguments:
arg.ResolveType (scope)
def _Traverse(self, function):
self.arguments = function(self.arguments)
if not self.isForwardDeclaration:
self.__body = function(self.__body)
def GetName(self):
return self.name
def GetType(self):
return self.__type
def GetArguments(self):
return self.arguments
def GetBody(self):
return self.__body
def __str__(self):
return '{} ({} argument(s))'.format (self.GetName (), len (self.GetArguments()))
class Statement(Node):
pass
class BranchControl(Enum):
Default = 0
Branch = 1
class FlowStatement(Statement):
pass
class EmptyStatement(Statement):
pass
class ExpressionStatement(Statement):
def __init__(self, expr):
super().__init__()
self.__expression = expr
def _Traverse(self, function):
self.__expression = function(self.__expression)
def GetExpression(self):
return self.__expression
def __str__(self):
return 'Expression'
class CompoundStatement(Statement):
'''Compound statement consisting of zero or more statements.
Compound statements also create a new visibility block.'''
def __init__(self, stmts):
super().__init__()
self.__statements = stmts
def GetStatements(self):
return self.__statements
def SetStatements(self, statements):
self.__statements = statements
def _Traverse(self, function):
self.__statements = function(self.__statements)
def __len__(self):
return len(self.__statements)
def __iter__(self):
'''Iterate over the statements.'''
return self.__statements.__iter__()
def __str__(self):
return '{0} statement(s)'.format (len(self))
class ReturnStatement(FlowStatement):
def __init__(self, expression = None):
super().__init__()
self.__expression = expression
def _Traverse(self, function):
if self.__expression:
self.__expression = function(self.__expression)
def GetExpression(self):
return self.__expression
def __str__(self):
if self.__expression:
return 'return ' + str(self.__expression)
else:
return 'return'
class DeclarationStatement(Statement):
def __init__(self, variableDeclarations):
super().__init__()
self.declarations = variableDeclarations
def GetDeclarations(self):
return self.declarations
def _Traverse(self, function):
self.declarations = function(self.declarations)
def __str__(self):
return '{0} declaration(s)'.format(len(self.declarations))
class IfStatement(FlowStatement):
def __init__(self, cond, true_path, else_path=None,
*, branch_control=BranchControl.Default):
super().__init__()
self.__condition = cond
self.__trueBlock = true_path
self.__elseBlock = else_path
self.__branchControl = branch_control
def _Traverse(self, function):
self.__condition = function(self.__condition)
self.__trueBlock = function(self.__trueBlock)
self.__elseBlock = function(self.__elseBlock)
def GetCondition(self):
return self.__condition
def GetTruePath(self):
return self.__trueBlock
def GetElsePath(self):
return self.__elseBlock
def HasElsePath(self):
return self.__elseBlock is not None
def __str__(self):
return str(self.__condition)
class ContinueStatement(FlowStatement):
def __init__(self):
super().__init__()
class BreakStatement(FlowStatement):
def __init__(self):
super().__init__()
class ForStatement(FlowStatement):
def __init__(self, init, cond, increment, body):
super().__init__()
self.__initializer = init
self.__condition = cond
self.__next = increment
self.__body = body
def GetBody (self):
return self.__body
def GetInitialization (self):
return self.__initializer
def GetCondition(self):
return self.__condition
def GetNext (self):
return self.__next
def _Traverse(self, function):
self.__initializer = function(self.__initializer)
self.__condition = function(self.__condition)
self.__next = function(self.__next)
self.__body = function(self.__body)
def __str__(self):
return 'ForStatement'
class DoStatement(FlowStatement):
def __init__(self, cond, body):
super().__init__()
self.__condition = cond
self.__body = body
def _Traverse(self, function):
self.__body = function(self.__body)
self.__condition = function(self.__condition)
def GetCondition(self):
return self.__condition
def GetBody (self):
return self.__body
class WhileStatement(FlowStatement):
def __init__(self, cond, body):
super().__init__()
self.__condition = cond
self.__body = body
def _Traverse(self, function):
self.__body = function(self.__body)
self.__condition = function(self.__condition)
def GetCondition(self):
return self.__condition
def GetBody (self):
return self.__body
class Annotation(Node):
def __init__(self, value):
super().__init__()
self.__value = value
def GetValue(self):
return self.__value
def __str__(self):
return '[{}]'.format (self.__value)
def __repr__(self):
return 'Annotation({})'.format (repr(self.__value))
| [
"dev@anteru.net"
] | dev@anteru.net |
891b7f7087e5314bc894f00b4cca3d76f14503f0 | fcefc860dea5db4d1023779012fa8f598186cd63 | /MBIT/BACK-END/MBIT/settings.py | 0d19f3972ee31783f43746a124f0c8aea36f4932 | [] | no_license | POPCORN-DOG/web_project | 59a47c1e079e2be4c28d486305788391bb42c502 | 606e30d0ea47fcba291f3b1c6fe496eb2d89522e | refs/heads/main | 2023-04-09T16:18:02.369107 | 2021-04-28T18:04:50 | 2021-04-28T18:04:50 | 345,257,667 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,070 | py | """
Django settings for MBIT project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_(d1z_ffuck4b=p=6jo6-2(17fg)p7l7c*#e#ocg2rxv*fh28('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'MBIT.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'MBIT.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
| [
"dudwlsrla21@gmail.com"
] | dudwlsrla21@gmail.com |
b74c0bc34641278eb029a1c82ac27043e45d22a1 | 248a02bdf0b1d16c5edf98614f23c843efd78bed | /HW2/DecisionTreeClassifier.py | 5b6b70f06c87d518c9c992578657b59815e35649 | [] | no_license | kapilmulchandani/DataMining-CMPE255 | 24f0834c463799592295c96313323c9de2c2a2a9 | 7726cb77de8b2390180c1e6609011f8cf015899a | refs/heads/master | 2020-07-25T06:04:48.497675 | 2020-01-23T15:18:33 | 2020-01-23T15:18:33 | 208,190,249 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,280 | py | from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.tree import export_graphviz
from sklearn.externals.six import StringIO
from IPython.display import Image
from pydot import graph_from_dot_data
import pandas as pd
import numpy as np
dtData = pd.read_csv('DecisionTree.csv')
print(dtData)
dtData['Windy'] = dtData['Windy'].map({'No': 0, 'Yes': 1})
dtData['Air Quality Good'] = dtData['Air Quality Good'].map({'No': 0, 'Yes': 1})
dtData['Hot'] = dtData['Hot'].map({'No': 0, 'Yes': 1})
dtData['Play Tennis'] = dtData['Play Tennis'].map({'No': 0, 'Yes': 1})
X = dtData.drop(['Play Tennis'], axis=1)
Y = dtData['Play Tennis']
# Train Test Split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=20)
decisionTree = DecisionTreeClassifier()
decisionTree.fit(X_train, Y_train)
# (graph, ) = graph_from_dot_data(dot_data.getvalue())
# Image(graph.create_png())
y_pred = decisionTree.predict(X_test)
dot_data = StringIO()
export_graphviz(decisionTree, out_file=dot_data)
(graph, ) = graph_from_dot_data(dot_data.getvalue())
Image(graph.create_png())
graph.write_pdf("dtree.pdf")
species = np.array(Y_test)
predictions = np.array(y_pred)
| [
"kapilchandralal.mulchandani@sjsu.edu"
] | kapilchandralal.mulchandani@sjsu.edu |
c37df82c03d8c388b9e3db8a43f0734c9ab53a55 | ce8afb1017926dda12fa9b586e0288886f9722a4 | /blog/decorators.py | 3e799c88871cd0dbc80f296963a0d8eb7e318750 | [] | no_license | Mortrest/Django-polls | fdfa3efc2a6ef902bbdd3a8a6e338af7d058fcd4 | c1986fa4125b7da829580e29ed8b5c34f6275996 | refs/heads/master | 2022-12-24T22:43:18.059860 | 2020-10-01T08:23:27 | 2020-10-01T08:23:27 | 299,570,189 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 325 | py | from django.http import HttpResponse
from django.shortcuts import redirect
def unauth_user(view_func):
def wrapper_func(request, *args, **kwargs):
if request.user.is_authenticated:
return redirect ('home')
else:
return view_func(request, *args, **kwargs)
return wrapper_func
| [
"ali80af@gmail.com"
] | ali80af@gmail.com |
9caf74e90af18319d33cec357cfbb4d17d4c4b7d | 20650b5dcfa43f28fa475738af62e74970836151 | /bulk_populate_profiles.py | f0bbefe1fb65c675c12098d5a3d23953d388ea19 | [] | no_license | lmachadopolettivalle/camels-database-schemas | 6fe6c0cb89cf8ca5388f8d38aaf1476a68f16d9b | a4ac3147b9eeebe68d008297c96159eaaf3ed4ae | refs/heads/main | 2023-06-15T20:50:46.005025 | 2021-06-29T09:03:04 | 2021-06-29T09:03:04 | 315,830,157 | 2 | 1 | null | 2021-06-29T09:03:05 | 2020-11-25T04:38:30 | Python | UTF-8 | Python | false | false | 302 | py | import os
import subprocess
filenames = os.listdir()
for filename in filenames:
if not filename.endswith(".npz"):
continue
command = f"""python3 populate_profile_data.py -f "sample.db" --profile_filename "{filename}" """
cmd = subprocess.run(command, shell=True)
print(cmd)
| [
"noreply@github.com"
] | lmachadopolettivalle.noreply@github.com |
f536843fd3e985980ccbd96c847fd641a3b73c45 | 7d33f3ffd3e8af75abb60959668d070b9d595e30 | /my_computer_vision/connected_component_clean.py | efd5858009d029e8c7a39f1c8c555a5eca195530 | [] | no_license | XuChongBo/pydemo | 33ad4615158b39b79ad81a92dcbf5d27fb60184f | ded0d15a22ed8c606deb35b83357fe7eeb9cb6af | refs/heads/master | 2021-06-13T09:11:57.564740 | 2020-09-13T11:24:32 | 2020-09-13T11:24:32 | 15,645,208 | 0 | 1 | null | 2021-03-19T22:24:58 | 2014-01-05T04:08:47 | HTML | UTF-8 | Python | false | false | 2,372 | py | from PIL import Image
from pylab import imshow,show,subplot,array,figure,gray,uint8,hist
import numpy as np
from pylab import jet
from skimage import filter
from scipy.ndimage import filters,measurements
from scipy import stats
#file_name='./data/das-0.jpg'
#file_name='./data/EngBill21.jpg'
#file_name='./data/sample1.jpg'
file_name='/Users/xcbfreedom/projects/data/formula_images/user_images/531283fa24f0b8afb.png'
# load the image file
img = Image.open(file_name)
print img
# convert to gray
img_gray = array(img.convert('L')) # not inplace operator
img_gray = 255-img_gray
# binary
#img_bin = filter.threshold_adaptive(img_gray,17,method='mean')
global_thresh = filter.threshold_otsu(img_gray)
img_bin = img_gray > global_thresh
# find connect components
s = array([[1,1,1],[1,1,1],[1,1,1]])
# the mask image and num of objects
labeled_array, num_features = measurements.label(img_bin, structure=s)
print num_features
# list of slice index of object's box
obj_list = measurements.find_objects(labeled_array)
ob_area_list = []
#for ob in obj_list:
#h = ob[0].stop-ob[0].start
#w = ob[1].stop-ob[1].start
#print ob, h, w
img_bin_words = np.zeros_like(img_bin)
for i in range(num_features):
area = measurements.sum(img_bin,labeled_array,index=i+1)
if area<20:
continue
print area
ob_area_list.append(area)
img_bin_words[labeled_array==(i+1)]=img_bin[labeled_array==(i+1)]
hist(ob_area_list)
area_mode = stats.mode(ob_area_list,axis=None)
print area_mode
#print img_bin,stats.mode(img_bin,axis=None)
#print img_bin,np.max(img_bin)
# do gaussian blur to the bin img
#img_bin = filters.gaussian_filter(img_bin,0.26935)
#print img_bin,stats.mode(img_bin,axis=None)
#print img_bin,np.max(img_bin)
# binary again
#img_bin = filters.maximum_filter(img_bin,7)
#img_bin = filter.threshold_adaptive(img_bin,7)
#img_bin[img_bin>0]=255
Image.fromarray(uint8(img_bin)).save('feature_points.png')
figure(); gray(); # don't use colors
# show the two pics on 1*2 frame
#subplot(1,3,1)
imshow(img_gray)
#subplot(1,3,2)
figure(); gray(); # don't use colors
imshow(img_bin)
figure(); gray(); # don't use colors
imshow(img_bin_words)
#subplot(1,3,3)
#imshow(labeled_array)
#ob = labeled_array[obj_list[100]]
figure(); gray(); # don't use colors
imshow(labeled_array)
# starts the figure GUI and raises the figure windows
jet()
show()
| [
"xcbfreedom@gmail.com"
] | xcbfreedom@gmail.com |
d591f7b0205b9f53ea686b13c7b45b5cf9130cac | d0ff9af885dc01de43ae7bdd2d26d6370c7b7ab5 | /unsup_vvs/network_training/optimizer.py | 8a9074a8a6b8a52355defc3ceb1a37b7cea592c6 | [] | no_license | augix/unsup_vvs | a09f89c7d002006f59ffbe223c9469e959949e04 | 168ed0d068d27b7a7ca1dd5c1ebc28fbe84f8c7c | refs/heads/master | 2023-07-17T05:55:27.630844 | 2021-06-24T01:27:28 | 2021-06-24T01:27:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,966 | py | import os
import copy
import tensorflow as tf
import numpy as np
import logging
if 'TFUTILS_LOGFILE' in os.environ:
logging.basicConfig(filename=os.environ['TFUTILS_LOGFILE'])
print ("USING LOGFILE: %s" % os.environ['TFUTILS_LOGFILE'])
else:
logging.basicConfig()
log = logging.getLogger('tfutils')
log.setLevel('DEBUG')
class ClipOptimizerSelf(object):
"""A wrapper for general optimizers.
This class supports:
- Clipping the gradients. (controlled by clip parameter)
- Train part of trainable parameters (controlled by trainable_names)
Args:
optimizer_class: Returned value of this function should have `compute_gradients` and `apply_gradients` methods.
clip (bool, optional): Default is True, clipping by `[-1, 1]`.
"""
def __init__(
self, optimizer_class, clip=True, clipping_method='value', clipping_value=1.0, print_global_norm=False,
trainable_scope=None, *optimizer_args, **optimizer_kwargs):
self._optimizer = optimizer_class(*optimizer_args, **optimizer_kwargs)
# The optimizer needs to have these required methods
required_methods = ['compute_gradients', 'apply_gradients']
for required_method in required_methods:
assert required_method in dir(self._optimizer), \
"Your optimizer needs to have method %s!" % required_method
self.clip = clip
self.clipping_method = clipping_method
self.clipping_value = clipping_value
self.print_global_norm = print_global_norm
self.trainable_scope = trainable_scope
def compute_gradients(self, loss, var_list=None, *args, **kwargs):
"""Compute gradients to model variables from loss.
Args:
loss (tf.Tensor): Tensorflow loss to optimize.
Returns:
(tf.Operation): Compute gradient update to model followed by a
clipping operation if `self.clip` is True.
"""
# freeze all variables except those with self.trainable_scope in their names
if var_list is None:
var_list = tf.trainable_variables()
if self.trainable_scope is not None:
new_var_list = [v for v in var_list if any([nm in v.name for nm in self.trainable_scope])]
if len(new_var_list):
var_list = new_var_list
log.info("Only training variables in scope: %s" % self.trainable_scope)
log.info("variables to be trained: %s" % var_list)
if var_list is not None:
num_trainable_params = sum([np.prod(v.shape.as_list()) for v in var_list])
log.info("Number of Trainable Parameters: %d" % num_trainable_params)
gvs = self._optimizer.compute_gradients(loss, var_list=var_list,
*args, **kwargs)
if self.clip:
if self.clipping_method == "value":
# gradient clipping. Some gradients returned are 'None' because
# no relation between the variable and loss; so we skip those.
gvs = [(tf.clip_by_value(grad, -self.clipping_value, self.clipping_value), var)
for grad, var in gvs if grad is not None]
elif self.clipping_method == "norm":
print("USING GLOBAL NORM CLIPPING with clip_value %.2f" % self.clipping_value)
gradients, variables = zip(*gvs)
norm = tf.global_norm(gradients)
if self.print_global_norm:
norm = tf.Print(norm, [norm], message="grad_global_norm")
true_fn = lambda: tf.constant(1.0)
false_fn = lambda: tf.identity(norm)
norm = tf.case([(tf.logical_or(tf.is_inf(norm), tf.is_nan(norm)), true_fn)], default=false_fn)
gradients, global_norm = tf.clip_by_global_norm(gradients, self.clipping_value,
use_norm=norm)
gvs = zip(gradients, variables)
else:
raise ValueError("optimizer.clip = True but you didn't specify a valid method in ['value', 'norm']")
return gvs
def apply_gradients(self, grads_and_vars, global_step=None, name=None):
"""Apply gradients to model variables specified in `grads_and_vars`.
`apply_gradients` returns an op that calls
`tf.train.Optimizer.apply_gradients`
Args:
grads_and_vars (list): Description.
global_step (None, optional): tensorflow global_step variable.
Returns:
(tf.Operation): Applies gradient update to model followed by an
internal gradient zeroing operation to `self.grads_and_vars`.
"""
optimize = self._optimizer.apply_gradients(grads_and_vars,
global_step=global_step,
name=name)
return optimize
| [
"chengxuz@node07-ccncluster.stanford.edu"
] | chengxuz@node07-ccncluster.stanford.edu |
296f3efdb1aeb0f6e2d0c8152bb030aa39addcb7 | f1c24389196ef2a5eefebaedc7abf684ea930733 | /serverQt.py | fe54b7f3a5c8c36dbb44c12d1aceb9ec2d72d4a3 | [] | no_license | SarathM1/PatientMonitoringSystem | d68d7ebf801fad9504a6462f370c8843d002ed25 | 720d18bbf825a212b5dd2553b8837f73775769d5 | refs/heads/master | 2021-01-01T05:49:51.969198 | 2015-02-21T09:58:40 | 2015-02-21T09:58:40 | 31,121,411 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,907 | py | from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
import socket
from PyQt4 import uic
import socket
import threading
import gui
h='0.0.0.0'
p=5000
class myThread(threading.Thread):
def __init__(self, threadId, name, counter):
threading.Thread.__init__(self)
self.threadId = threadId
self.name = name
self.counter = counter
def run(self):
print "Starting "+self.name
############################
""" s=socket.socket()
s.bind(('0.0.0.0',5000))
s.listen(2)
(c,(ip,port))=s.accept()
print 'client address: '+str(c)+','+str(ip)+','+str(port)
while True:
data=c.recv(1024)
if not data:
break
print "from connected user: " + str(data)
data=str(data).upper()
print "Sending: "+str(data)
c.send(data)
c.close()"""
##################################
print "Ending "+self.name
class myWindow(QMainWindow,gui.Ui_MainWindow):
def __init__(self):
super(myWindow,self).__init__()
uic.loadUi('main.ui',self)
self.setupUi(self)
self.connect(self.socketOk,SIGNAL("clicked()"),self.threadInit)
def serverInit(self):
global h
global p
h='0.0.0.0'
p=5000
print str(type(h)) + ',' + h + ',' + str(type(p)) + ',' + str(p)
self.threadInit()
def threadInit(self):
threads=[]
thread1=myThread(1,'Client1',1)
thread2=myThread(2,'Client2',2)
thread1.start()
thread2.start()
threads.append(thread1)
threads.append(thread2)
for t in threads:
t.join()
print 'Exiting main thread'
app = QApplication(sys.argv)
window = myWindow()
window.show()
sys.exit(app.exec_())
| [
"sarathm00@gmail.com"
] | sarathm00@gmail.com |
64da5162935266d4ef9f51a50b0ab4a510b0c7ff | ed2bdbe14b7da9233634aad4f2f93ca0fc44d2dd | /python/python-crash-course/name_cases.py | dfe151347f609a8eafe18d7b363a443b624c24a8 | [] | no_license | klajdikume/CodingDojo | f76d1d4a0d16a257cfacd4a13c40466c367c3c5a | dc7c903b1f897968508c70bde10fdfa575ed9ecc | refs/heads/master | 2021-12-29T13:25:30.810864 | 2017-11-21T16:49:22 | 2017-11-21T16:49:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 473 | py | # Strings
person = "Artur Bosch"
print("Hello, " + person + "! Do you want to learn some python today?")
print(person.title())
print(person.lower())
print(person.upper())
famous_person = "albert einstein"
quote = 'once said, "A person who never made a mistake never tried anything new."'
print(famous_person.title() + " " + quote)
new_person = "\t\t\tArtur Bosch\t\t\n"
print(new_person)
print(new_person.rstrip())
print(new_person.lstrip())
print(new_person.strip())
| [
"arturbosch@gmx.de"
] | arturbosch@gmx.de |
e85e48e63bdb7736ebd61bba58ff16c6c00e16c1 | caee3d333a6f8115f99c7a33138d2a2a2d8e9678 | /arrayoperation.py | 6d8d24a1274272596933710c7c7c696571632f97 | [] | no_license | VishalGupta2597/batch89 | c24e004ce4beee075a0e75f740e1afdae724f992 | b11cfbcccb3884e06190938f8ca6272a41161366 | refs/heads/master | 2022-01-22T10:02:46.204693 | 2019-08-01T02:39:51 | 2019-08-01T02:39:51 | 197,910,034 | 2 | 1 | null | 2019-07-20T09:39:48 | 2019-07-20T09:39:47 | null | UTF-8 | Python | false | false | 521 | py | from numpy import *
import os
import time
arr = array([1,12,33,4,5])
print(arr)
arr = arr + 5
print(arr)
arr2 =ones(5)
print(arr2)
arr3 = arr + arr2
print(arr3)
'''for i in arr3:
time.sleep(1)
print(i)'''
arr4 = sqrt(arr)
print(arr4)
print("Min=",min(arr))
print("Max=",max(arr))
print("Sum=",sum(arr))
a = sort(arr)
print(a)
print(concatenate([arr,arr2]))
print(concatenate([arr2,arr]))
s=char.array(['ram','shyam'])
s1=char.array(['Sharma','singh'])
print(s)
print(s1)
s3= s+s1
print(s3)
| [
"aswanibtech@gmail.com"
] | aswanibtech@gmail.com |
7645534c3137ef86857d250e0eb979bdc9e7f7d7 | c1e6e7740bc3957d63597cbdcdc98b10e4b2321b | /config/get_config.py | 8c24e33e73472dc3127a05af819f8eacf8637dfe | [] | no_license | tungnkhust/Coverage-in-Wireless-Sensor-Networks | b05c11c32475d32b644d389e579d3d178e53227e | aa8f49e4a93ff0a5ef679d0a3548452d7f13baa5 | refs/heads/main | 2023-01-23T21:02:40.064232 | 2020-12-02T10:48:25 | 2020-12-02T10:48:25 | 309,088,005 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 651 | py | import yaml
import sys
ROOT_PATH = '/home/tungnk/Desktop/learning/20201/Evolution_Computing/Coverage-in-Wireless-Sensor-Networks'
with open(ROOT_PATH + '/config/config.yaml', 'r') as pf:
config = yaml.safe_load(pf)
NUM_TARGET = config['TARGET']['NUM_TARGET']
Q_MIN = config['TARGET']['Q_MIN']
Q_MAX = config['TARGET']['Q_MAX']
W = config['DOMAIN']['W']
H = config['DOMAIN']['H']
Rs = config['RADIUS']['SENSE']
Rc = config['RADIUS']['TRANSFER']
EPSILON = config['OPTIONAL']['EPSILON']
CHANGE_DATA = config['DATA']['CHANGE_DATA']
CHANGE_Q = config['TARGET']['CHANGE_Q']
N_TEST = config['DATA']['N_TEST'] | [
"nguyenkytungcntt04@gmail.com"
] | nguyenkytungcntt04@gmail.com |
e85f6099b850b6c1da899cbe13646bea67e2ee69 | f1462223a09da151dc29ffeaf27c916d5c5afe1d | /setup.py | 6a831288cc761514fd014b53e27eae15a2a3bcab | [
"MIT"
] | permissive | RUalexeyusman/apache-airflow-providers-teradata | 30eed45b60478cfa8e8a815969a2b23e2f380efa | 08fc77595209f1d9220f3c9301f4fecc45a7c6e0 | refs/heads/main | 2023-02-22T01:42:02.356931 | 2021-01-24T14:56:20 | 2021-01-24T14:56:20 | 347,649,794 | 2 | 0 | MIT | 2021-03-14T13:51:01 | 2021-03-14T13:51:00 | null | UTF-8 | Python | false | false | 1,391 | py | #!/usr/bin/env python
"""The setup script."""
from setuptools import setup, find_namespace_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
setup(
author="Felipe Lolas",
author_email='flolas@icloud.com',
python_requires='>=3.5',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
description="Teradata Tools and Utils wrapper for Apache Airflow 2.0/1.1x.",
install_requires=['apache-airflow>=2.0.0a0',],
license="MIT license",
long_description=readme + '\n\n' + history,
include_package_data=True,
keywords=['airflow', 'teradata'],
name='apache-airflow-providers-teradata',
packages=find_namespace_packages(include=['airflow.providers.teradata', 'airflow.providers.teradata.*']),
setup_requires=['setuptools', 'wheel'],
url='https://github.com/flolas/apache_airflow_providers_teradata',
version='1.0.4',
zip_safe=False,
)
| [
"felipe.lolas@bci.cl"
] | felipe.lolas@bci.cl |
d21ed483315927392f91996b9887c804d6a8c19b | 26f6313772161851b3b28b32a4f8d255499b3974 | /Python/SetMatrixZeroes.py | 3864067eec769d1f7e01f4fd60be96322284154d | [] | no_license | here0009/LeetCode | 693e634a3096d929e5c842c5c5b989fa388e0fcd | f96a2273c6831a8035e1adacfa452f73c599ae16 | refs/heads/master | 2023-06-30T19:07:23.645941 | 2021-07-31T03:38:51 | 2021-07-31T03:38:51 | 266,287,834 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,533 | py | """
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Example 2:
Input:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
Output:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
Follow up:
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution
"""
class Solution:
def setZeroes(self, matrix) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
m,n = len(matrix), len(matrix[0])
mul_rows = [1]*m
mul_cols = [1]*n
for i in range(m):
tmp = 1
for j in range(n):
tmp *= matrix[i][j]
mul_rows[i] = tmp
for j in range(n):
tmp = 1
for i in range(m):
tmp *= matrix[i][j]
mul_cols[j] = tmp
# print(mul_cols)
for i in range(m):
if mul_rows[i] == 0:
for j in range(n):
matrix[i][j] = 0
for j in range(n):
if mul_cols[j] == 0:
for i in range(m):
matrix[i][j] = 0
for row in matrix:
print(row)
s = Solution()
matrix = [[1,1,1],[1,0,1],[1,1,1]]
print(s.setZeroes(matrix))
matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
print(s.setZeroes(matrix))
| [
"here0009@163.com"
] | here0009@163.com |
a8952a45d4005620456406f27a6f16c3f54825b7 | c5959b7e4fc5b752b54a6352449c1bb0d28d9115 | /bab/bab-4/while4.py | 63e1174ea481eb96df7ea0cf2938d8605d486f37 | [] | no_license | romanbatavi/kickstarter-python | f5592a371740b28c045ef99dd510d1c6a92ff8d1 | ed3eb692e09a3f44fd3e0b16ab7b042ee2658db6 | refs/heads/master | 2023-03-29T11:34:23.774873 | 2021-04-04T09:11:28 | 2021-04-04T09:11:28 | 354,500,208 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 335 | py | ######################################################
# Nama file: while4.py
######################################################
def main():
# melakukan pengulangan dari indeks 'a' sampai 'e'
ch = 'a'
while ch <= 'e':
print("%c: Hello World!" % ch)
ch = chr(ord(ch) + 1)
if __name__ == "__main__":
main()
| [
"romanbatavi98@gmail.com"
] | romanbatavi98@gmail.com |
91145a4cb8372af53e27d7179291e58fdfdc4f46 | 6c219c1cdc92a4e0c3fe7af02998ba964bbc74ed | /ORS/ctl/TimeTableListCtl.py | 88b4a939eae9c79beaf0e69e28a27e578beb4dde | [] | no_license | kanchansahu97/SOS_PROJECT | 983a89043280d952a5f08e3c91a3fa8f684118fa | c2ff948ef1ea578f2f6f7cc6dba5944d50b16e96 | refs/heads/main | 2023-03-02T00:56:28.926005 | 2021-02-02T12:26:31 | 2021-02-02T12:26:31 | 335,276,813 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,729 | py |
from django.http import HttpResponse
from .BaseCtl import BaseCtl
from django.shortcuts import render
from ORS.utility.DataValidator import DataValidator
from service.forms import TimeTableForm
from service.models import TimeTable
from service.service.TimeTableService import TimeTableService
class TimeTableListCtl(BaseCtl):
def request_to_form(self,requestForm):
self.form["examTime"]=requestForm.get("examTime",None)
self.form["examDate"]=requestForm.get("examDate",None)
self.form["subject_ID"]=requestForm.get("subject_ID",None)
self.form["course_ID"]=requestForm.get("course_ID",None)
self.form["semester"]=requestForm.get("semester",None)
self.form["ids"]= requestForm.getlist( "ids", None)
def display(self,request,params={}):
self.page_list = self.get_service().search(self.form)
res = render(request,self.get_template(),{"pageList":self.page_list})
return res
def submit(self,request,params={}):
self.request_to_form(request.POST)
self.page_list = self.get_service().search(self.form)
res = render(request,self.get_template(),{"pageList":self.page_list, "form":self.form})
return res
def get_template(self):
return "ors/TimeTableList.html"
# Service of Marksheet
def get_service(self):
return TimeTableService()
def deleteRecord(self,request,params={}):
self.page_list = self.get_service().search(self.form)
res = render(request,self.get_template(),{"pageList":self.page_list})
if(bool(self.form["ids"])==False):
self.form["error"] = True
self.form["message"] = "Please Select at least one check box"
res = render(request,self.get_template(),{"pageList":self.page_list,"form":self.form})
else:
for ids in self.form["ids"]:
self.page_list = self.get_service().search(self.form)
id=int(ids)
if( id > 0):
r = self.get_service().get(id)
if r is not None:
self.get_service().delete(r.id)
self.form["error"] = False
self.form["message"] = "Data is successfully deleted"
res = render(request,self.get_template(),{"pageList":self.page_list,"form":self.form})
else:
self.form["error"] = True
self.form["message"] = "Data is not delete"
res = render(request,self.get_template(),{"pageList":self.page_list,"form":self.form})
return res
| [
"kanchansahuji97@gmail.com"
] | kanchansahuji97@gmail.com |
a54681f57124be8cfe5c0b63c97f65316051aece | cc2f3a665a9f4dec23db7e7810712122ccabf491 | /OnlineGameHall/OnlineGameHall/settings.py | 7abd984228654c9d25e7f7fa441fef70f30b6b90 | [] | no_license | MiaoPengPython/Python | de035981c868aec5a56655f5627137241303b23a | 84cbe5ae85edad5ae4d483f69d7fcde3ccb92cea | refs/heads/master | 2020-08-28T09:12:29.984812 | 2019-10-26T05:16:46 | 2019-10-26T05:16:46 | 217,658,043 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,835 | py | """
Django settings for OnlineGameHall project.
Generated by 'django-admin startproject' using Django 1.11.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^li9kpe(7sqgvyn#rdu4c+r=#7_gwe+!_2n1q^e=v*gpi-!%f1'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'user',
'game',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'OnlineGameHall.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'OnlineGameHall.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'webgame',
'USER': 'tarena',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), )
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # 固定写法
EMAIL_HOST = 'smtp.qq.com' # 腾讯QQ邮箱 SMTP 服务器地址
EMAIL_PORT = 25 # SMTP服务的端口号
EMAIL_HOST_USER = '2865756660@qq.com' # 发送邮件的QQ邮箱
EMAIL_HOST_PASSWORD = 'efqjswjvsbjldggj' # 在QQ邮箱->设置->帐户->“POP3/IMAP......服务” 里得到的在第三方登录QQ邮箱授权码
EMAIL_USE_TLS = True # 与SMTP服务器通信时,是否启动TLS链接(安全链接)默认false
| [
"2651281713@qq.com"
] | 2651281713@qq.com |
f83dcc8ca7030d644bb4a42a4fd959abafeb8317 | c35e0abd098583e70d737761250a8e3ff6c52e16 | /MGLP_scan/process_Rad_omega_comb.py | 353da9a458853385ade9ea41fe53beccf9ac7741 | [] | no_license | Michael-Gong/emission_sup | a820c45498e6e31812964dc97b951d83adeb0e4b | e515371faf0759d676bf837a69bf4ab5943e9b4d | refs/heads/master | 2020-03-20T02:54:21.921790 | 2020-01-05T14:32:29 | 2020-01-05T14:32:29 | 137,128,326 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,773 | py | import sdf
import matplotlib
matplotlib.use('agg')
#%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
#from numpy import ma
from matplotlib import colors, ticker, cm
from matplotlib.mlab import bivariate_normal
from optparse import OptionParser
import os
import scipy.integrate as integrate
import scipy.special as special
from scipy.special import kv
######## Constant defined here ########
pi = 3.1415926535897932384626
pi2d = 180./pi
q0 = 1.602176565e-19 # C
m0 = 9.10938291e-31 # kg
v0 = 2.99792458e8 # m/s^2
kb = 1.3806488e-23 # J/K
mu0 = 4.0e-7*pi # N/A^2
epsilon0 = 8.8541878176203899e-12 # F/m
h_planck = 6.62606957e-34 # J s
wavelength= 1.0e-6
frequency = v0*2*pi/wavelength
exunit = m0*v0*frequency/q0
bxunit = m0*frequency/q0
denunit = frequency**2*epsilon0*m0/q0**2
print('electric field unit: '+str(exunit))
print('magnetic field unit: '+str(bxunit))
print('density unit nc: '+str(denunit))
font = {'family' : 'monospace',
'style' : 'normal',
'color' : 'black',
'weight' : 'normal',
'size' : 20,
}
###############read data into array################
from_path = './C-Rad/'
grid_omega_x = np.loadtxt(from_path+'grid_omega_x.txt')
grid_theta_y = np.loadtxt(from_path+'grid_theta_y.txt')
grid_phi_z = np.loadtxt(from_path+'grid_phi_z.txt')
data_I = np.loadtxt(from_path+'data.txt')
print(grid_omega_x.size)
print(grid_theta_y*pi2d)
print(grid_phi_z*pi2d)
print(data_I.size)
data_I = data_I.reshape(grid_omega_x.size, grid_theta_y.size, grid_phi_z.size)
print(data_I.shape)
px=np.loadtxt('./Data/px_0.txt')
py=np.loadtxt('./Data/py_0.txt')
gg=(px**2+py**2+1)**0.5
b0=np.loadtxt('./Data/bz_part_0.txt')
t0=np.loadtxt('./Data/t_0.txt')
gg = gg[0]
#b0 = 100 #b0[3]
t0 = t0[-1]
#r0=gg/b0
alpha_0 = 10
#omega_critic = 1.5*gg**3/r0
omega_critic = 3*gg**2.5*alpha_0**0.5
r0=gg/(2*alpha_0**0.5*gg**0.5)
for i_theta in range(grid_theta_y.size):
for i_phi in range(grid_phi_z.size):
if grid_theta_y.size >1:
theta_1 = abs(grid_theta_y[i_theta] - pi/2)
else:
theta_1 = abs(grid_theta_y - pi/2)
# data_omega = np.sum(np.sum(data_I,axis=2),axis=1)
data_omega = data_I
norm_fac = q0**2/(4*pi*epsilon0*4*pi**2*v0)/(m0*v0**2)*frequency
data_omega = data_omega*norm_fac
xi = grid_omega_x*r0/3.0/gg**3*(1.0+gg**2*theta_1**2)**1.5
y_line = np.linspace(1e-7,5e-4,1000)
x_line = np.zeros_like(y_line)+omega_critic
if (abs(grid_phi_z[i_phi]*pi2d) <89.5):
b1 = 2*alpha_0**0.5*((gg**2-1)/((np.tan(grid_phi_z[i_phi]))**2+1))**0.25
omega_critic_1 = 1.5*gg**2*b1
r1 = gg/b1
xi_1 = grid_omega_x*r1/3.0/gg**3*(1.0+gg**2*theta_1**2)**1.5
theory_line_1 = norm_fac*3*(2*grid_omega_x*r1/3.0/gg**2)**2*(1+gg**2*theta_1**2)**2*(kv(0.66666666666667,xi_1)**2+(gg**2*theta_1**2)/(1.0+gg**2*theta_1**2)*kv(0.3333333333333,xi_1)**2)
theory_line = norm_fac*3*(2*grid_omega_x*r0/3.0/gg**2)**2*(1+gg**2*theta_1**2)**2*(kv(0.66666666666667,xi)**2+(gg**2*theta_1**2)/(1.0+gg**2*theta_1**2)*kv(0.3333333333333,xi)**2)
#norm_x = matplotlib.colors.Normalize()
plt.subplot(2,2,1)
plt.plot(grid_omega_x, data_omega[:,i_theta,i_phi], '-k', marker='o',linewidth=1,label='my code calculation')
plt.plot(grid_omega_x,theory_line,':r',linewidth=2,label='theoretical equation')
if (abs(grid_phi_z[i_phi]*pi2d) <89.5):
plt.plot(grid_omega_x,theory_line_1,':b',linewidth=2,label='theoretical equation with r')
#plt.plot(x_line, y_line, ':b',linewidth=3,label='$\omega_{c}=(3c\gamma^3)/(2r_0)$')
#cbar=plt.colorbar(ticks=np.linspace(0.0, 4, 5))
#cbar.set_label(r'$log_{10}\frac{dI}{\sin\theta d\theta d\omega}$'+' [A.U.]', fontdict=font)
#cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(), fontsize=20)
#plt.plot(x_omega,np.sum(np.sum(data_I_t,axis=0),axis=0),'-b',linewidth=3)
#### manifesting colorbar, changing label and axis properties ####
#plt.grid(which='major',color='k', linestyle='--', linewidth=0.3)
plt.xlabel('$\omega$ [$\omega_0$]',fontdict=font)
plt.ylabel(r'$\frac{dI^2}{d\omega d\Omega}$'+' [$m_ec^2/\omega_0$]',fontdict=font)
plt.xticks(fontsize=20); plt.yticks(fontsize=20);
#plt.yscale('log')
# plt.xlim(2,5990)
# plt.ylim(0,1e-4)
plt.legend(loc='best',fontsize=16,framealpha=1.0)
#plt.text(285,4e8,'t='+str(round(time/1.0e-15,0))+' fs',fontdict=font)
#plt.subplots_adjust(left=0.2, bottom=None, right=0.88, top=None,wspace=None, hspace=None)
plt.subplot(2,2,2)
plt.plot(grid_omega_x, data_omega[:,i_theta,i_phi], '-k',marker='o',linewidth=1)
plt.plot(grid_omega_x,theory_line,':r',linewidth=2)
if (abs(grid_phi_z[i_phi]*pi2d) <89.5):
plt.plot(grid_omega_x,theory_line_1,':b',linewidth=2,label='theoretical equation with r')
#plt.plot(x_line, y_line, ':b',linewidth=3)
#cbar=plt.colorbar(ticks=np.linspace(0.0, 4, 5))
#cbar.set_label(r'$log_{10}\frac{dI}{\sin\theta d\theta d\omega}$'+' [A.U.]', fontdict=font)
#cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(), fontsize=20)
#plt.plot(x_omega,np.sum(np.sum(data_I_t,axis=0),axis=0),'-b',linewidth=3)
#### manifesting colorbar, changing label and axis properties ####
#plt.grid(which='major',color='k', linestyle='--', linewidth=0.3)
plt.xlabel('$\omega$ [$\omega_0$]',fontdict=font)
plt.ylabel(r'$\frac{dI^2}{d\omega d\Omega}$'+' [$m_ec^2/\omega_0$]',fontdict=font)
plt.xticks(fontsize=20); plt.yticks(fontsize=20);
plt.xscale('log')
plt.yscale('log')
# plt.xlim(2,6000)
plt.ylim(1e-8,3e-5)
#plt.legend(loc='upper right',fontsize=16,framealpha=1.0)
#plt.text(285,4e8,'t='+str(round(time/1.0e-15,0))+' fs',fontdict=font)
#plt.subplots_adjust(left=0.2, bottom=None, right=0.88, top=None,wspace=None, hspace=None)
theta_c = 1/gg*(2*omega_critic/grid_omega_x)**0.33333333333333/np.pi*180
#norm_x = matplotlib.colors.Normalize()
plt.subplot(2,2,3)
plt.plot(grid_omega_x, theta_c, '-k', marker='^',linewidth=1,label='my code calculation')
#plt.plot(x_line, y_line, ':b',linewidth=3,label='$\omega_{c}=(3c\gamma^3)/(2r_0)$')
#cbar=plt.colorbar(ticks=np.linspace(0.0, 4, 5))
#cbar.set_label(r'$log_{10}\frac{dI}{\sin\theta d\theta d\omega}$'+' [A.U.]', fontdict=font)
#cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(), fontsize=20)
#plt.plot(x_omega,np.sum(np.sum(data_I_t,axis=0),axis=0),'-b',linewidth=3)
#### manifesting colorbar, changing label and axis properties ####
#plt.grid(which='major',color='k', linestyle='--', linewidth=0.3)
plt.xlabel('$\omega$ [$\omega_0$]',fontdict=font)
plt.ylabel(r'$\theta_c\ [^o]$',fontdict=font)
plt.xticks(fontsize=20); plt.yticks(fontsize=20);
#plt.yscale('log')
# plt.xlim(2,5990)
# plt.ylim(0,1e-4)
plt.legend(loc='best',fontsize=16,framealpha=1.0)
plt.xscale('log')
#plt.text(285,4e8,'t='+str(round(time/1.0e-15,0))+' fs',fontdict=font)
#plt.subplots_adjust(left=0.2, bottom=None, right=0.88, top=None,wspace=None, hspace=None)
plt.subplot(2,2,4)
plt.plot(grid_omega_x, theta_c, '-k', marker='^',linewidth=1,label='my code calculation')
#plt.plot(x_line, y_line, ':b',linewidth=3)
#cbar=plt.colorbar(ticks=np.linspace(0.0, 4, 5))
#cbar.set_label(r'$log_{10}\frac{dI}{\sin\theta d\theta d\omega}$'+' [A.U.]', fontdict=font)
#cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(), fontsize=20)
#plt.plot(x_omega,np.sum(np.sum(data_I_t,axis=0),axis=0),'-b',linewidth=3)
#### manifesting colorbar, changing label and axis properties ####
#plt.grid(which='major',color='k', linestyle='--', linewidth=0.3)
plt.xlabel('$\omega$ [$\omega_0$]',fontdict=font)
plt.ylabel(r'$\theta_c\ [^o]$',fontdict=font)
plt.xticks(fontsize=20); plt.yticks(fontsize=20);
plt.xscale('log')
plt.yscale('log')
# plt.xlim(2,6000)
# plt.ylim(1e-7,5e-4)
#plt.legend(loc='upper right',fontsize=16,framealpha=1.0)
#plt.text(285,4e8,'t='+str(round(time/1.0e-15,0))+' fs',fontdict=font)
#plt.subplots_adjust(left=0.2, bottom=None, right=0.88, top=None,wspace=None, hspace=None)
fig = plt.gcf()
fig.set_size_inches(18.0, 18.0)
#fig.savefig('./C-Rad/spectral_theta='+str(int(round(grid_theta_y[i_theta]*pi2d,1))).zfill(4)+'_phi='+str(int(round(grid_phi_z[i_phi]*pi2d,1))).zfill(4)+'.png',format='png',dpi=160)
fig.savefig('./C-Rad/spectral_theta='+str(int(round(grid_theta_y*pi2d,1))).zfill(4)+'_phi='+str(int(round(grid_phi_z[i_phi]*pi2d,1))).zfill(4)+'.png',format='png',dpi=160)
plt.close("all")
| [
"noreply@github.com"
] | Michael-Gong.noreply@github.com |
484fe49b65b57a90d4a0867e0ed54cdbf67a5642 | fe6e0a2cfb00d34b58f64f164a747e3df08e8a9d | /client/application/model/downloadModel.py | 942132358bcf5d897119d704c82000cf414bb740 | [] | no_license | huboqiao/kmvip | c141814666631c35b8adeec3d3beb5aca0d2d1cd | 11ae7e1f78943c8425516c4f06acf043a99acdcc | refs/heads/master | 2020-02-26T14:58:31.573602 | 2016-08-03T06:29:41 | 2016-08-03T06:29:41 | 64,809,269 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,788 | py | #coding:utf8
'''
Created on 2014年10月30日
@author: ivan
'''
from __future__ import division
import os
import sys
import ast
import time
import pickle
import struct
from socket import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class VerCheck( QThread ):
'''检查版本'''
def __init__(self,ini,act,ver,parent=None):
super(VerCheck,self).__init__()
self.host = ini.get('ver','ip')
self.port = int(ini.get('ver','port'))
self.sock = socket(AF_INET,SOCK_STREAM,0)
self.act = act
self.ver = ver
try:
self.sock.connect((self.host,self.port))
except:
print 'socket error'
def run(self):
data = {'act':self.act,'ver':self.ver}
data = pickle.dumps(data)
self.sock.send(data)#发送文件基本信息数据
serverdata = self.sock.recv(1024)
result = pickle.loads(serverdata)
self.emit(SIGNAL("checkver"),result)
self.sock.close()
class Download( QThread ):
def __init__(self,ini,act,parent=None):
super(Download,self).__init__()
self.host = ini.get('ver','ip')
self.port = int(ini.get('ver','port'))
self.sock = socket(AF_INET,SOCK_STREAM,0)
self.act = act
try:
self.sock.connect((self.host,self.port))
self.mutex = QMutex()
data = {'act':self.act}
data = pickle.dumps(data)
self.sock.send(data)#发送文件基本信息数据
FILEINFO_SIZE=struct.calcsize('128s32sI8s')
fhead = self.sock.recv(FILEINFO_SIZE)
filename,temp1,filesize,temp2=struct.unpack('128s32sI8s',fhead)
#result = pickle.loads(serverdata)
self.filename = os.getcwd()+'/VIPcore.dll'
self.fp = open(self.filename,'wb')
self.restsize = filesize
self.lens = filesize
except Exception as e:
print e
self.stoped = False
#下载数据
def run(self):
while True:
if self.stoped:
return
if self.restsize <= 0:
self.fp.close()
self.sock.close()
break
filedata = self.sock.recv(1024)
self.fp.write(filedata)
self.restsize = int(self.restsize) - int(len(filedata))
#计算完成百分比
load = float('%.3f'%( 1 - (int(self.restsize) / int(self.lens)))) * 100
loaddata = {'load':load}
self.emit(SIGNAL("download"),loaddata)
time.sleep(0.001)
| [
"42320756@qq.com"
] | 42320756@qq.com |
0e85144ea11e6dce439806aac93853f61cab7a4c | f7b918c573958f21dcd341cfa3fcd839b2f5ecd8 | /MMA/macro.orig.py | 9a28d5dbaf89ca286b699d008ce1c8090ed33972 | [] | no_license | lmaxwell/mma | 05504dbd86b45518cab70e36fd08f097950ad96b | 98ba26b1354df5ac48be5b08ff15456c0539b460 | refs/heads/master | 2022-12-26T23:25:07.893705 | 2020-10-05T00:40:12 | 2020-10-05T00:40:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 27,897 | py |
# macros.py
"""
This module is an integeral part of the program
MMA - Musical Midi Accompaniment.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Bob van der Poel <bob@mellowood.ca>
The macros are stored, set and parsed in this single-instance
class. At the top of MMAparse an instance in created with
something like: macros=MMMmacros.Macros().
"""
import random
import datetime
import MMA.midiC
import MMA.translate
import MMA.volume
import MMA.grooves
import MMA.parse
import MMA.parseCL
import MMA.player
import MMA.seqrnd
import MMA.midinote
import MMA.swing
import MMA.ornament
import MMA.rpitch
import MMA.chords
import MMA.debug
from . import gbl
from MMA.notelen import getNoteLen
from MMA.keysig import keySig
from MMA.timesig import timeSig
from MMA.lyric import lyric
from MMA.common import *
from MMA.safe_eval import safe_eval
def sliceVariable(p, sl):
""" Slice a variable. Used by macro expand. """
try:
new = eval('p' + "[" + sl + "]")
except IndexError:
error("Index '%s' out of range." % sl)
except:
error("Index error in '%s'." % sl)
if ":" not in sl:
new = [new]
return new
class Macros:
vars = {} # storage
expandMode = 1 # flag for variable expansion
pushstack = []
def __init__(self):
self.vars = {}
def clear(self, ln):
if ln:
error("VarClear does not take an argument.")
self.vars = {}
if MMA.debug.debug:
dPrint("All variable definitions cleared.")
def stackValue(self, s):
self.pushstack.append(' '.join(s))
def sysvar(self, s):
""" Create an internal macro. """
# Simple/global system values
if s == 'CHORDADJUST':
return ' '.join([ "%s=%s" % (a, MMA.chords.cdAdjust[a])
for a in sorted(MMA.chords.cdAdjust)])
elif s == 'FILENAME':
return str(gbl.inpath.fname)
elif s == 'KEYSIG':
return keySig.getKeysig()
elif s == 'TIME':
return str(gbl.QperBar)
elif s == 'CTABS':
return ','.join([ str((float(x) / gbl.BperQ) + 1) for x in MMA.parseCL.chordTabs])
elif s == 'TIMESIG':
return timeSig.getAscii()
elif s == 'TEMPO':
return str(gbl.tempo)
elif s == 'OFFSET':
return str(gbl.tickOffset)
elif s == 'SONGFILENAME':
return str(gbl.infile)
elif s == 'VOLUME':
return str(int(MMA.volume.volume * 100)) # INT() is important
elif s == 'VOLUMERATIO':
return str((MMA.volume.vTRatio * 100))
elif s == 'LASTVOLUME':
return str(int(MMA.volume.lastVolume * 100))
elif s == 'GROOVE':
return MMA.grooves.currentGroove
elif s == 'GROOVELIST':
return ' '.join(sorted([x for x in MMA.grooves.glist.keys() if isinstance(x, str)]))
elif s == 'TRACKLIST':
return ' '.join(sorted(gbl.tnames.keys()))
elif s == 'LASTGROOVE':
return MMA.grooves.lastGroove
elif s == 'PLUGINS':
from MMA.regplug import simplePlugs # to avoid circular import error
return ' '.join(simplePlugs)
elif s == 'TRACKPLUGINS':
from MMA.regplug import trackPlugs # to avoid circular import error
return ' '.join(trackPlugs)
elif s == 'DATAPLUGINS':
from MMA.regplug import dataPlugs # to avoid circular import error
return ' '.join(dataPlugs)
elif s == 'SEQ':
return str(gbl.seqCount)
elif s == 'SEQRND':
if MMA.seqrnd.seqRnd[0] == 0:
return "Off"
if MMA.seqrnd.seqRnd[0] == 1:
return "On"
return ' '.join(MMA.seqrnd.seqRnd[1:])
elif s == 'SEQSIZE':
return str(gbl.seqSize)
elif s == 'SWINGMODE':
return MMA.swing.settings()
elif s == 'TICKPOS':
return str(gbl.tickOffset)
elif s == 'TRANSPOSE':
return str(gbl.transpose)
elif s == 'STACKVALUE':
if not self.pushstack:
error("Empty push/pull variable stack")
return self.pushstack.pop()
elif s == 'DEBUG':
return MMA.debug.getFlags()
elif s == 'LASTDEBUG':
return MMA.debug.getLFlags()
elif s == 'VEXPAND':
if self.expandMode:
return "On"
else:
return "Off"
elif s == "MIDIPLAYER":
return "%s Background=%s Delay=%s." % \
(' '.join(MMA.player.midiPlayer), MMA.player.inBackGround,
MMA.player.waitTime)
elif s == "MIDISPLIT":
return ' '.join([str(x) for x in MMA.midi.splitChannels])
elif s.startswith("NOTELEN(") and s.endswith(")"):
return "%sT" % getNoteLen(s[8:-1])
elif s == 'SEQRNDWEIGHT':
return ' '.join([str(x) for x in MMA.seqrnd.seqRndWeight])
elif s == 'AUTOLIBPATH':
return ' '.join(MMA.paths.libDirs)
elif s == 'LIBPATH':
return ' '.join(MMA.paths.libPath)
elif s == 'MMAPATH':
return gbl.MMAdir
elif s == 'INCPATH':
return ' '.join(MMA.paths.incPath)
elif s == 'VOICETR':
return MMA.translate.vtable.retlist()
elif s == 'TONETR':
return MMA.translate.dtable.retlist()
elif s == 'OUTPATH':
return gbl.outPath
elif s == 'BARNUM':
return str(gbl.barNum + 1)
elif s == 'LINENUM':
return str(gbl.lineno)
elif s == 'LYRIC':
return lyric.setting()
# Some time/date macros. Useful for generating copyright strings
elif s == 'DATEYEAR':
return str(datetime.datetime.now().year)
elif s == 'DATEDATE':
return datetime.datetime.now().strftime("%Y-%m-%d")
elif s == 'DATETIME':
return datetime.datetime.now().strftime("%H:%M:%S")
# Track vars ... these are in format TRACKNAME_VAR
a = s.rfind('_')
if a == -1:
error("Unknown system variable $_%s" % s)
tname = s[:a]
func = s[a+1:]
try:
t = gbl.tnames[tname]
except KeyError:
error("System variable $_%s refers to nonexistent track." % s)
if func == 'ACCENT':
r = []
for s in t.accent:
r.append("{")
for b, v in s:
r.append('%g' % (b/float(gbl.BperQ)+1))
r.append(str(int(v * 100)))
r.append("}")
return ' '.join(r)
elif func == 'ARTICULATE':
return ' '.join([str(x) for x in t.artic])
elif func == 'CHORDS':
r = []
for l in t.chord:
r.append('{' + ' '.join(l) + '}')
return ' '.join(r)
elif func == 'CHANNEL':
return str(t.channel)
elif func == 'COMPRESS':
return ' '.join([str(x) for x in t.compress])
elif func == 'DELAY':
return ' '.join([str(x) for x in t.delay])
elif func == 'DIRECTION':
if t.vtype == 'ARIA':
return ' '.join([str(x) for x in t.selectDir])
else:
return ' '.join([str(x) for x in t.direction])
elif func == 'DUPROOT':
if t.vtype != "CHORD":
error("Only CHORD tracks have DUPROOT")
return t.getDupRootSetting()
elif func == 'FRETNOISE':
return t.getFretNoiseOptions()
elif func == 'HARMONY':
return ' '.join([str(x) for x in t.harmony])
elif func == 'HARMONYONLY':
return ' '.join([str(x) for x in t.harmonyOnly])
elif func == 'HARMONYVOLUME':
return ' '.join([str(int(i * 100)) for i in t.harmonyVolume])
elif func == 'INVERT':
return ' '.join([str(x) for x in t.invert])
elif func == 'LIMIT':
return str(t.chordLimit)
elif func == 'MALLET':
if t.vtype not in ("SOLO", "MELODY"):
error("Mallet only valid in SOLO and MELODY tracks")
return "Mallet Rate=%i Decay=%i" % (t.mallet, t.malletDecay*100)
elif func == 'MIDINOTE':
return MMA.midinote.mopts(t)
elif func == 'MIDIVOLUME':
return "%s" % t.cVolume
elif func == 'OCTAVE':
return ' '.join([str(i//12) for i in t.octave])
elif func == 'MOCTAVE':
return ' '.join([str((i//12)-1) for i in t.octave])
elif func == 'ORNAMENT':
return MMA.ornament.getOrnOpts(t)
elif func == 'PLUGINS':
from MMA.regplug import trackPlugs # avoids circular import
return ' '.join(trackPlugs)
elif func == 'RANGE':
return ' '.join([str(x) for x in t.chordRange])
elif func == 'RSKIP':
m = ''
if t.rSkipBeats:
m = "Beats=%s " % ','.join(['%g' % (x/float(gbl.BperQ)+1) for x in t.rSkipBeats])
m += ' '.join([str(int(i * 100)) for i in t.rSkip])
return m
elif func == 'RDURATION':
tmp = []
for a1, a2 in t.rDuration:
a1 = int(a1 * 100)
a2 = int(a2 * 100)
if a1 == a2:
tmp.append('%s' % abs(a1))
else:
tmp.append('%s,%s' % (a1, a2))
return ' '. join(tmp)
elif func == 'RTIME':
tmp = []
for a1, a2 in t.rTime:
if a1 == a2:
tmp.append('%s' % abs(a1))
else:
tmp.append('%s,%s' % (a1, a2))
return ' '.join(tmp)
elif func == 'RVOLUME':
tmp = []
for a1, a2 in t.rVolume:
a1 = int(a1 * 100)
a2 = int(a2 * 100)
if a1 == a2:
tmp.append('%s' % abs(a1))
else:
tmp.append('%s,%s' % (a1, a2))
return ' '.join(tmp)
elif func == 'RPITCH':
return MMA.rpitch.getOpts(t)
elif func == 'SEQUENCE':
tmp = []
for a in range(gbl.seqSize):
tmp.append('{' + t.formatPattern(t.sequence[a]) + '}')
return ' '.join(tmp)
elif func == 'SEQRND':
if t.seqRnd:
return 'On'
else:
return 'Off'
elif func == 'SEQRNDWEIGHT':
return ' '.join([str(x) for x in t.seqRndWeight])
elif func == 'SPAN':
return "%s %s" % (t.spanStart, t.spanEnd)
elif func == 'STICKY':
if t.sticky:
return "True"
else:
return "False"
elif func == 'STRUM':
r = []
for v in t.strum:
if v is None:
r.append("0")
else:
a, b = v
if a == b:
r.append("%s" % a)
else:
r.append("%s,%s" % (a, b))
return ' '.join(r)
elif func == 'STRUMADD':
return ' '.join([str(x) for x in t.strumAdd])
elif func == 'TRIGGER':
return MMA.trigger.getTriggerOptions(t)
elif func == 'TONE':
if t.vtype in ('MELODY', 'SOLO'):
if not t.drumType:
error("Melody/Solo tracks must be DRUMTYPE for tone.")
return str(MMA.midiC.valueToDrum(t.drumTone))
elif t.vtype != 'DRUM':
error("Tracktype %s doesn't have TONE" % t.vtype)
return ' '.join([MMA.midiC.valueToDrum(a) for a in t.toneList])
elif func == 'UNIFY':
return ' '.join([str(x) for x in t.unify])
elif func == 'VOICE':
return ' '.join([MMA.midiC.valueToInst(a) for a in t.voice])
elif func == 'VOICING':
if t.vtype != 'CHORD':
error("Only CHORD tracks have VOICING")
t = t.voicing
return "Mode=%s Range=%s Center=%s RMove=%s Move=%s Dir=%s" % \
(t.mode, t.range, t.center, t.random, t.bcount, t.dir)
elif func == 'VOLUME':
return ' '.join([str(int(a * 100)) for a in t.volume])
else:
error("Unknown system track variable %s" % s)
def expand(self, l):
""" Loop though input line and make variable subsitutions.
MMA variables are pretty simple ... any word starting
with a "$xxx" is a variable.
l - list
RETURNS: new list with all subs done.
"""
if not self.expandMode:
return l
gotmath = 0
sliceVar = None
while 1: # Loop until no more subsitutions have been done
sub = 0
for i, s in enumerate(l):
if s[0] == '$':
s = s[1:].upper()
if not s:
error("Illegal macro name '%s'." % l[i])
frst = s[0] # first char after the leading '$'
if frst == '$': # $$ - don't expand (done in IF clause)
continue
if frst == '(': # flag math macro
gotmath = 1
continue
# pull slice notation off the end of the name
if s.endswith(']'):
x = s.rfind('[')
if not x:
error("No matching for '[' for trailing ']' in variable '%s'." % s)
sliceVar = s[x+1:-1]
s = s[:x]
""" Since we be using an 'eval' to do the actual slicing,
we check the slice string to make sure it's looking
valid. The easy way out makes as much sense as anything
else ... just step through the slice string and make
sure we ONLY have integers or empty slots.
"""
for test in sliceVar.split(":"):
try:
test == '' or int(test)
except:
error("Invalid index in slice notation '%s'." % sliceVar)
else:
sliceVar = None
# we have a var, see if system or user. Set 'ex'
if frst == '_': # system var
ex = self.sysvar(s[1:])
elif s in self.vars: # user var?
ex = self.vars[s]
else: # unknown var...error
error("User variable '%s' has not been defined" % s)
if isinstance(ex, list): # MSET variable
if sliceVar:
ex = sliceVariable(ex, sliceVar)
sliceVar = None
if len(ex):
gbl.inpath.push(ex[1:], [gbl.lineno] * len(ex[1:]))
if len(ex):
ex = ex[0]
else:
ex = []
else: # regular SET variable
ex = ex.split()
if sliceVar:
ex = sliceVariable(ex, sliceVar)
sliceVar = None
""" we have a simple variable (ie $_TEMPO) converted to a list,
or a list-like var (ie $_Bass_Volume) converted to a list,
or the 1st element of a multi-line variable
We concat this into the existing line, process some more
"""
l = l[:i] + ex + l[i+1:]
sub = 1
break
if not sub:
break
# all the mma internal and system macros are expanded. Now check for math.
if gotmath:
l = ' '.join(l) # join back into one line
while 1:
try:
s1 = l.index('$(') # any '$(' left?
except:
break # nope, done
# find trailing )
nest = 0
s2 = s1+2
max = len(l)
while 1:
if l[s2] == '(':
nest += 1
if l[s2] == ')':
if not nest:
break
else:
nest -= 1
s2 += 1
if s2 >= max:
error("Unmatched delimiter in '%s'." % l)
l = l[:s1] + str(safe_eval(l[s1+2:s2].strip())) + l[s2+1:]
l = l.split()
return l
def showvars(self, ln):
""" Display all currently defined user variables. """
if len(ln):
for a in ln:
a = a.upper()
if a in self.vars:
print("$%s: %s" % (a, self.vars[a]))
else:
print("$%s - not defined" % a)
else:
print("User variables defined:")
kys = self.vars.keys()
kys.sort()
mx = 0
for a in kys: # get longest name
if len(a) > mx:
mx = len(a)
mx = mx + 2
for a in kys:
print(" %-*s %s" % (mx, '$'+a, self.vars[a]))
def getvname(self, v):
""" Helper routine to validate variable name. """
if v[0] in ('$', '_'):
error("Variable names cannot start with a '$' or '_'")
if '[' in v or ']' in v:
error("Variable names cannot contain [ or ] characters.")
return v.upper()
def rndvar(self, ln):
""" Set a variable randomly from a list. """
if len(ln) < 2:
error("Use: RndSet Variable_Name <list of possible values>")
v = self.getvname(ln[0])
self.vars[v] = random.choice(ln[1:])
if MMA.debug.debug:
dPrint("Variable $%s randomly set to '%s'" % (v, self.vars[v]))
def newsetvar(self, ln):
""" Set a new variable. Ignore if already set. """
if not len(ln):
error("Use: NSET VARIABLE_NAME [Value] [[+] [Value]]")
if self.getvname(ln[0]) in self.vars:
return
self.setvar(ln)
def setvar(self, ln):
""" Set a variable. Note the difference between the next 2 lines:
Set Bar BAR
Set Foo AAA BBB $bar
$Foo == "AAA BBB BAR"
Set Foo AAA + BBB + $bar
$Foo == "AAABBBBAR"
The "+"s just strip out intervening spaces.
"""
if len(ln) < 1:
error("Use: SET VARIABLE_NAME [Value] [[+] [Value]]")
v = self.getvname(ln.pop(0))
t = ''
addSpace = 0
for i, a in enumerate(ln):
if a == '+':
addSpace = 0
continue
else:
if addSpace:
t += ' '
t += a
addSpace = 1
self.vars[v] = t
if MMA.debug.debug:
dPrint("Variable $%s == '%s'" % (v, self.vars[v]))
def msetvar(self, ln):
""" Set a variable to a number of lines. """
if len(ln) != 1:
error("Use: MSET VARIABLE_NAME <lines> MsetEnd")
v = self.getvname(ln[0])
lm = []
while 1:
l = gbl.inpath.read()
if not l:
error("Reached EOF while looking for MSetEnd")
cmd = l[0].upper()
if cmd in ("MSETEND", 'ENDMSET'):
if len(l) > 1:
error("No arguments permitted for MSetEnd/EndMSet")
else:
break
lm.append(l)
self.vars[v] = lm
def unsetvar(self, ln):
""" Delete a variable reference. """
if len(ln) != 1:
error("Use: UNSET Variable")
v = ln[0].upper()
if v[0] == '_':
error("Internal variables cannot be deleted or modified")
if v in self.vars:
del(macros.vars[v])
if MMA.debug.debug:
dPrint("Variable '%s' UNSET" % v)
else:
warning("Attempt to UNSET nonexistent variable '%s'" % v)
def vexpand(self, ln):
if len(ln) == 1:
cmd = ln[0].upper()
else:
cmd = ''
if cmd == 'ON':
self.expandMode = 1
if MMA.debug.debug:
dPrint("Variable expansion ON")
elif cmd == 'OFF':
self.expandMode = 0
if MMA.debug.debug:
dPrint("Variable expansion OFF")
else:
error("Use: Vexpand ON/Off")
def varinc(self, ln):
""" Increment a variable. """
if len(ln) == 1:
inc = 1
elif len(ln) == 2:
inc = stof(ln[1], "Expecting a value (not %s) for Inc" % ln[1])
else:
error("Usage: INC Variable [value]")
v = ln[0].upper()
if v[0] == '_':
error("Internal variables cannot be modified")
if not v in self.vars:
error("Variable '%s' not defined" % v)
vl = stof(self.vars[v], "Variable must be a value to increment") + inc
# lot of mma commands expect ints, so convert floats like 123.0 to 123
if vl == int(vl):
vl = int(vl)
self.vars[v] = str(vl)
if MMA.debug.debug:
dPrint("Variable '%s' INC to %s" % (v, self.vars[v]))
def vardec(self, ln):
""" Decrement a varaiable. """
if len(ln) == 1:
dec = 1
elif len(ln) == 2:
dec = stof(ln[1], "Expecting a value (not %s) for Inc" % ln[1])
else:
error("Usage: DEC Variable [value]")
v = ln[0].upper()
if v[0] == '_':
error("Internal variables cannot be modified")
if not v in self.vars:
error("Variable '%s' not defined" % v)
vl = stof(self.vars[v], "Variable must be a value to decrement") - dec
# lot of mma commands expect ints, so convert floats like 123.0 to 123
if vl == int(vl):
vl = int(vl)
self.vars[v] = str(vl)
if MMA.debug.debug:
dPrint("Variable '%s' DEC to %s" % (v, self.vars[v]))
def varIF(self, ln):
""" Conditional variable if/then. """
def expandV(l):
""" Private func. """
l = l.upper()
if l[:2] == '$$':
l = l.upper()
l = l[2:]
if not l in self.vars:
error("String Variable '%s' does not exist" % l)
l = self.vars[l]
try:
v = float(l)
except:
try:
v = int(l, 0) # this lets us convert HEX/OCTAL
except:
v = None
return(l.upper(), v)
def readblk():
""" Private, reads a block until ENDIF, IFEND or ELSE.
Return (Terminator, lines[], linenumbers[] )
"""
q = []
qnum = []
nesting = 0
while 1:
l = gbl.inpath.read()
if not l:
error("EOF reached while looking for EndIf")
cmd = l[0].upper()
if cmd == 'IF':
nesting += 1
if cmd in ("IFEND", 'ENDIF', 'ELSE'):
if len(l) > 1:
error("No arguments permitted for IfEnd/EndIf/Else")
if not nesting:
break
if cmd != 'ELSE':
nesting -= 1
q.append(l)
qnum.append(gbl.lineno)
return (cmd, q, qnum)
if len(ln) < 2:
error("Usage: IF <Operator> ")
action = ln[0].upper()
# 1. do the unary options: DEF, NDEF
if action in ('DEF', 'NDEF'):
if len(ln) != 2:
error("Usage: IF %s VariableName" % action)
v = ln[1].upper()
if action == 'DEF':
compare = v in self.vars
elif action == 'NDEF':
compare = (v not in self.vars)
else:
error("Unreachable unary conditional") # can't get here
# 2. Binary ops: EQ, NE, etc.
elif action in ('LT', '<', 'LE', '<=', 'EQ', '==', 'GE', '>=', 'GT', '>', 'NE', '!='):
if len(ln) != 3:
error("Usage: VARS %s Value1 Value2" % action)
s1, v1 = expandV(ln[1])
s2, v2 = expandV(ln[2])
# Make the comparison to strings or values. If either arg
# is NOT a value, use string values for both.
if None in (v1, v2):
v1, v2 = s1, s2
if action == 'LT' or action == '<':
compare = (v1 < v2)
elif action == 'LE' or action == '<=':
compare = (v1 <= v2)
elif action == 'EQ' or action == '==':
compare = (v1 == v2)
elif action == 'GE' or action == '>=':
compare = (v1 >= v2)
elif action == 'GT' or action == '>':
compare = (v1 > v2)
elif action == 'NE' or action == '!=':
compare = (v1 != v2)
else:
error("Unreachable binary conditional") # can't get here
else:
error("Usage: IF <CONDITON> ...")
""" Go read until end of if block.
We shove the block back if the compare was true.
Unless, the block is terminated by an ELSE ... then we need
to read another block and push back one of the two.
"""
cmd, q, qnum = readblk()
if cmd == 'ELSE':
cmd, q1, qnum1 = readblk()
if cmd == 'ELSE':
error("Only one ELSE is permitted in IF construct")
if not compare:
compare = 1
q = q1
qnum = qnum1
if compare:
gbl.inpath.push(q, qnum)
macros = Macros()
| [
"karim.ratib@gmail.com"
] | karim.ratib@gmail.com |
a5363e09c885d6ccc0278f85192602da6cb8ccbc | abed0712f5e70fa3d27ca586edc4999aaa2086fa | /src/flow_to_image.py | 056f32784df4a78e13d3a9a6b679fffdd0e7a473 | [
"MIT"
] | permissive | ki-lm/flownet2-tf | 86e346c0e370a2fcd2e3ad55d856431cd77a0fa1 | 31cac0ab7dab01bf862e9faa93ffe1bfe045aa3c | refs/heads/master | 2020-07-08T13:41:53.258687 | 2019-10-11T07:33:24 | 2019-10-11T07:33:24 | 203,532,277 | 0 | 0 | MIT | 2019-08-21T07:38:46 | 2019-08-21T07:38:45 | null | UTF-8 | Python | false | false | 2,723 | py | # -*- coding: utf-8 -*-
# Copyright 2018 The Blueoil Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
import numpy as np
from scipy.interpolate import interp1d
def make_color_wheel():
"""
Generate color wheel according Middlebury color code
:return: Color wheel
"""
RY, YG, GC, CB, BM, MR = 15, 6, 4, 11, 13, 6
ncols = RY + YG + GC + CB + BM + MR
color_wheel = np.zeros([ncols + 1, 3])
col = 0
# RY
color_wheel[0:RY, 0] = 255
color_wheel[0:RY, 1] = np.floor(255 * np.arange(0, RY) / RY)
col += RY
# YG
color_wheel[col:col + YG, 0] = 255 - np.floor(255 * np.arange(0, YG) / YG)
color_wheel[col:col + YG, 1] = 255
col += YG
# GC
color_wheel[col:col + GC, 1] = 255
color_wheel[col:col + GC, 2] = np.floor(255 * np.arange(0, GC) / GC)
col += GC
# CB
color_wheel[col:col + CB, 1] = 255 - np.floor(255 * np.arange(0, CB) / CB)
color_wheel[col:col + CB, 2] = 255
col += CB
# BM
color_wheel[col:col + BM, 2] = 255
color_wheel[col:col + BM, 0] = np.floor(255 * np.arange(0, BM) / BM)
col += BM
# MR
color_wheel[col:col + MR, 2] = 255 - np.floor(255 * np.arange(0, MR) / MR)
color_wheel[col:col + MR, 0] = 255
# loop function
color_wheel[-1] = color_wheel[0]
return color_wheel
color_table = make_color_wheel()
color_function = interp1d(
np.linspace(0, 2 * np.pi, color_table.shape[0]), color_table, axis=0)
def flow_to_image(flow, threshold=100.0):
# idxUnknow = (abs(u) > UNKNOWN_FLOW_THRESH) | (abs(v) > UNKNOWN_FLOW_THRESH)
nan_index = np.isnan(flow).any(axis=2)
rad = np.linalg.norm(flow, axis=2)
rad[nan_index] = 0.0
rad *= (1 / max(threshold, np.max(rad)))
arg = np.arctan2(-flow[..., 1], -flow[..., 0]) + np.pi
# arg = (arg - 0.5 * np.pi) % (2 * np.pi)
image = color_function(arg)
height, width, channels = image.shape
white_image = 255 * (1 - rad)
for _i in range(channels):
image[..., _i] *= rad
image[..., _i] += white_image
image = image.astype(np.uint8)
image[image > 255] = 255
return image
| [
"inoue+github@leapmind.io"
] | inoue+github@leapmind.io |
5e52c9ce72f0595241c4bde8969db30cd55b76ee | 3148c2786d41c6dbaae788c698839b37d5fbef07 | /myexamples/python_cpp_binding/src/python/bindings_test.py | ec78b4620a15c09138cde3f3ee96aa0f64a5faf1 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | fuhailin/show-me-cpp-code | 97b5b5ee8b05cfcb8204c7d4c948aa14a5decbdf | 40b41451bc7218c82c975a9feb65f8cc340446e7 | refs/heads/master | 2022-05-16T13:56:04.156171 | 2022-03-20T10:46:09 | 2022-03-20T10:46:09 | 128,388,041 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 83 | py | from myexamples.python_cpp_binding.src.bindings import mycpplib
mycpplib.myPrint()
| [
"hailinfufu@outlook.com"
] | hailinfufu@outlook.com |
bdcfc429cc61c5228cff130c3c95a4af6e86377c | ad7495b3cb8669d2fabe530c60193e7069c68d7b | /pong/auth/views.py | 366ce76d4ad6179ed745cd423213bb88b62a3fd1 | [] | no_license | seanpreston/Pong | b0f81abecf692b6471b297547f5826eb22de0565 | fa9e18daa8097e1bf89b570234dd640e0c6186ea | refs/heads/master | 2016-09-10T09:31:49.983319 | 2014-11-29T12:13:30 | 2014-11-29T12:13:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 855 | py | # -*- coding: utf-8 -*-
from pong.request import api_call
import statsd
import logging
logger = logging.getLogger(__name__)
class RegistrationFailure(Exception):
pass
class LoginFailure(Exception):
pass
class AuthFailure(Exception):
pass
def _login_request(request, remember=True, *args, **kwargs):
res, status = api_call('post', '/api/v0/account/login/', data=kwargs)
if status != 200 or 'token' not in res:
raise LoginFailure()
token = res['token']
data, status = api_call('get', '/api/v0/account/authed/', token=token)
if status != 200 or data is None:
raise AuthFailure()
statsd.increment('login.success')
for key, val in data.items():
request.session[key] = val
request.session['token'] = token
if remember:
request.session.set_expiry(0)
return token, data | [
"seanmpreston@gmail.com"
] | seanmpreston@gmail.com |
61d592d21fbcdc1ecbc009dd0f04c3e9032d4de0 | 878e61194469e37ee2052806d7829125215067bf | /Amadon/apps/apps.py | d69ad51b66f4cfd0782c92dcc8884289e9de0c1c | [] | no_license | kieranrege/Django-v3-CodingDojo | 65230606d1f919b42db28a40222a4abf55b3fc27 | d70b8c9006815fe322e8408b2d034ee956bce4c2 | refs/heads/master | 2020-04-01T12:47:22.928632 | 2018-10-16T20:52:40 | 2018-10-16T20:52:40 | 153,223,830 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 131 | py | from __future__ import unicode_literals
from django.apps import AppConfig
class AmadonAppConfig(AppConfig):
name = 'amadon_app' | [
"noreply@github.com"
] | kieranrege.noreply@github.com |
2c3730600250ae421a16683729f969e0854b7f04 | 7407ad364fe48721d5018dd1a759e26bbd806df9 | /Graph_Algorithms/Graph_Algorithms.py | e0807c3f9f33f46790b01cfd42f1ba7336755589 | [] | no_license | pavelgolikov/Python-Code | 663a487f6f708207757ff5012a40dc36043dcf9d | f4346b1c706a16dc8b2271e220b84aa48ab41fda | refs/heads/master | 2020-03-28T08:10:57.843860 | 2018-09-10T14:46:40 | 2018-09-10T14:46:40 | 147,949,865 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,859 | py | """Graph questions"""
from Data_Structures.Disjoint_Set_Union_Rank_Path_Comp import makeset, find, union, combine_dsets
from Data_Structures.Stack import Stack
from copy import copy, deepcopy
import sys
inf = sys.maxsize
"""Graph questions"""
# def bfs(gnode: GNode) -> None:
# """Breadth first traversal of self using queue."""
#
# q = Queue()
# lst = []
# q.add(gnode)
# lst.append(gnode)
#
# while not q.is_empty():
# el = q.remove() # remove element from queue
# print(el.value)
# for node in el.adj_list:
# # if the node is not in the list,
# # add it to the list and to the queue
# if node not in lst:
# lst.append(node)
# q.add(node)
#
#
# def dfs(gnode: GNode) -> None:
# """Breadth first traversal of self using queue."""
#
# s = Stack()
# lst = []
# s.add(gnode)
# lst.append(gnode)
#
# while not s.is_empty():
# el = s.remove() # remove element from stack
# print(el.value)
# for node in el.adj_list:
# # if the node is not in the list,
# # add it to the list and to the stack
# if node not in lst:
# lst.append(node)
# s.add(node)
class GraphUndirNoWeight:
"""Graph.
"""
def __init__(self) -> None:
"""Create an instance of GNode"""
self.vertices = []
self.edges = []
self.adj_dict = {}
def add_edge(self, u, v):
"""Add edge (u,v) to graph self."""
if u not in self.vertices:
self.vertices.append(u)
if v not in self.vertices:
self.vertices.append(v)
if u in self.adj_dict.keys():
self.adj_dict[u].append(v)
else:
self.adj_dict[u] = [v]
if v in self.adj_dict.keys():
self.adj_dict[v].append(u)
else:
self.adj_dict[v] = [u]
def connected_components(g: GraphUndirNoWeight)-> dict:
"""Return the dictionary with connected components of Graph g.
"""
sets = {}
for el in g.vertices:
sets[el] = makeset(el)
for ed in g.edges:
if find(sets[ed[0]]) != find(sets[ed[1]]):
union(sets[ed[0]], sets[ed[1]])
return sets
def print_connected_components(d: dict):
"""Print connected components from dictionary."""
lst = []
for el in d.values():
lst.append(el)
return combine_dsets(lst)
def cycle_detection(g: GraphUndirNoWeight) -> bool:
"""Returns true if graph contains cycle, returns False otherwise."""
sets = {}
for el in g.vertices:
sets[el] = makeset(el)
for ed in g.edges:
if find(sets[ed[0]]) != find(sets[ed[1]]):
union(sets[ed[0]], sets[ed[1]])
else:
return True
return False
def mst_kruskal(g: GraphUndirNoWeight)-> list:
"""Return a list containint mst of g using Kruskal's algorithm.
"""
lst = []
sets = {}
for el in g.vertices:
sets[el] = makeset(el)
sorted_ = sorted(g.edges, key=lambda tup: tup[2])
for ed in sorted_:
if find(sets[ed[0]]) != find(sets[ed[1]]):
union(sets[ed[0]], sets[ed[1]])
lst.append(ed)
return lst
def mst_penn(g: GraphUndirNoWeight, start) -> list:
"""Return a list containint mst of g using Penn's algorithm. Start
is the starting vertex.
"""
mst_set = []
keys = {}
for el in g.vertices:
if el == start:
keys[el] = 0
else:
keys[el] = 999
while keys:
min_value_vertex = min(keys, key=keys.get)
mst_set.append((min_value_vertex, keys[min_value_vertex]))
del keys[min_value_vertex]
for ed in g.edges:
if ed[0] == min_value_vertex and ed[1] in keys.keys():
if ed[2] < keys[ed[1]]:
keys[ed[1]] = ed[2]
elif ed[1] == min_value_vertex and ed[0] in keys.keys():
if ed[2] < keys[ed[0]]:
keys[ed[0]] = ed[2]
return mst_set
def dijikstra(g: GraphUndirNoWeight, source) -> list:
"""Return a list containint shortest path from source to every other node
of g using Dijkstra's algorithm.
Source is the starting vertex.
"""
spt_set = []
distances = {}
for el in g.vertices:
if el == source:
distances[el] = 0
else:
distances[el] = 999
distances_queue = copy(distances)
while distances_queue:
min_value_vertex = min(distances_queue, key=distances_queue.get)
spt_set.append((min_value_vertex, distances[min_value_vertex]))
for ed in g.edges:
if ed[0] == min_value_vertex and ed[1] in distances.keys():
if ed[2] + distances[ed[0]] < distances[ed[1]]:
distances[ed[1]] = ed[2] + distances[ed[0]]
distances_queue[ed[1]] = ed[2] + distances_queue[ed[0]]
elif ed[1] == min_value_vertex and ed[0] in distances.keys():
if ed[2] + distances[ed[1]] < distances[ed[0]]:
distances[ed[0]] = ed[2] + distances[ed[1]]
distances_queue[ed[0]] = ed[2] + distances_queue[ed[1]]
del distances_queue[min_value_vertex]
return spt_set
def artic_point(gr: GraphUndirNoWeight):
"""Find all articulation points of graph g."""
# create visited, low, and disc dictionaries:
visited_ = {}
disc_ = {}
low_ = {}
parent_ = {}
for el in gr.vertices:
visited_[el] = False
disc_[el] = inf
low_[el] = inf
parent_[el] = None
def artic_detect(g: GraphUndirNoWeight, parent: dict,
visited: dict, disc: dict, low: dict, ver, time_):
"""Helper function that actually looks for articulation points"""
visited[ver] = True
disc[ver] = time_
low[ver] = disc[ver]
child = 0
for v in g.adj_dict[ver]:
if visited[v] is False:
# look at all adjacent vertices
parent[v] = ver
child += 1
# perform artic_point on the child
artic_detect(g, parent, visited, disc, low, v, time_+1)
low[ver] = min(low[ver], low[v])
if parent[ver] is None and child > 1:
print(ver)
if parent[ver] is not None and low[v] >= disc[ver]:
print(ver)
elif parent[ver] != v:
low[ver] = min(low[ver], disc[v])
artic_detect(gr, parent_, visited_, disc_, low_, 'a', 0)
g0 = GraphUndirNoWeight()
g0.add_edge('a', 'e')
g0.add_edge('a', 'b')
g0.add_edge('b', 'c')
g0.add_edge('c', 'd')
g0.add_edge('e', 'c')
artic_point(g0)
g0.vertices = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k']
g0.edges = [('a', 'e', 1), ('e', 'g', 2), ('e', 'f', 23), ('f', 'k', 3),
('k', 'g', 4), ('g', 'j', 5), ('j', 'k', 6), ('k', 'h', 7),
('h', 'b', 8), ('c', 'b', 9), ('c', 'd', 10), ('a', 'd', 12),
('b', 'a', 14), ('e', 'h', 14), ('h', 'j', 18), ('a', 'g', 16)]
class DirGraph:
"""Directed Graph. Weighted."""
def __init__(self):
"""Create instance of directed graph."""
self.vertices = []
self.adj_dict = {}
self.adj_matrix = []
def add_edge(self, u, v, weight):
"""Add edge (u,v) to graph self."""
if u not in self.vertices:
self.vertices.append(u)
if v not in self.vertices:
self.vertices.append(v)
if u in self.adj_dict.keys():
self.adj_dict[u].append((v, weight))
else:
self.adj_dict[u] = [(v, weight)]
if v not in self.adj_dict.keys():
self.adj_dict[v] = []
def dfs(g: DirGraph):
"""DFSearch of g."""
def visit(g: DirGraph, visited, v):
"""Helper function."""
print(v)
visited[v] = 1
for adj_vertex in g.adj_dict[v]:
if visited[adj_vertex[0]] == 0:
visit(g, visited, adj_vertex[0])
# create a visited dictionary
visited = {el: 0 for el in g.adj_dict.keys()}
for ver in g.vertices:
if visited[ver] != 1:
visit(g, visited, ver)
def topological_sort(g: DirGraph):
"""Topological sort of graph g."""
def visit(g: DirGraph, visited, v, s: Stack):
"""Helper function."""
visited[v] = 1
for adj_vertex in g.adj_dict[v]:
if visited[adj_vertex[0]] == 0:
visit(g, visited, adj_vertex[0], s)
s.add(v)
# stack to keep track of which nodes comes before which
s = Stack()
# dictionary of nodes already visited
visited = {el: 0 for el in g.adj_dict.keys()}
# run through vertices and visit every one that is not yet visited
for ver in g.vertices:
if visited[ver] == 0:
visit(g, visited, ver, s)
# print all vertices
while not s.is_empty():
print(s.remove())
def floyd_warshall(g: DirGraph) -> list:
"""Return a list of shortest minimum distances between nodes of g
using Floyd_Warshall algorithm."""
# initialize solution matrix as g's adhacency matrix
sol_matrix = deepcopy(g.adj_matrix)
for k in range(7):
for i in range(7):
for j in range(7):
# if distance i->k + k->j is smaller than i->j
if sol_matrix[i][k] + sol_matrix[k][j] < sol_matrix[i][j]:
sol_matrix[i][j] = sol_matrix[i][k] + sol_matrix[k][j]
return sol_matrix
def boggle_(matrix: list, dictionary_: list):
"""Print words from the dictionary that can be formed with
letters from input matrix."""
def boggle(matrix: list, dictionary_: list, w: str, row, col):
"""Helper function to consider all combinations."""
# get the letter from matrix
# print(row, col)
letter = matrix[row][col]
# mark letter as visited
matrix[row][col] = '-'
# construct new word
word = w + letter
# print(word)
if word in dictionary_:
print(word)
# call boggle with word as argument on all adjecent cells
for i in range(-1, 2):
if i + row > len(matrix)-1 or i + row < 0:
continue
for j in range(-1, 2):
if j + col > len(matrix)-1 or j + col < 0:
continue
# print(i + row, j + col)
if matrix[i + row][j + col] == '-':
continue
boggle(matrix, dictionary_, word, i + row, j + col)
# unmark letter as visited
matrix[row][col] = letter
# start the possible string from every character:
for i_ in range(len(matrix)):
for j_ in range(len(matrix)):
boggle(matrix, dictionary_, '', i_, j_)
# g = DirGraph()
# g.add_edge('a', 'b', 8)
# g.add_edge('a', 'c', 1)
# g.add_edge('b', 'd', 5)
# g.add_edge('b', 'k', 5)
# g.add_edge('f', 'd', 6)
# g.add_edge('a', 'f', 3)
# g.add_edge('b', 'f', 1)
# g.add_edge('c', 'e', 2)
# g.add_edge('e', 'g', 4)
# g.add_edge('g', 'f', 7)
# g.add_edge('e', 'f', 6)
# g.add_edge('g', 'd', 20)
# g.add_edge('k', 'd', 16)
# g.adj_matrix = [[0, 8, 1, inf, inf, 3, inf],
# [inf, 0, inf, 5, inf, 1, inf],
# [inf, inf, 0, inf, 2, inf, inf],
# [inf, inf, inf, 0, inf, inf, inf],
# [inf, inf, inf, inf, 0, 16, 4],
# [inf, inf, inf, 6, inf, 0, inf],
# [inf, inf, inf, 20, inf, 7, 0]]
# g.adj_matrix = [['g', 'i', 'z'],
# ['u', 'e', 'k'],
# ['q', 's', 'e']]
# dictionary_ = ['geeks', 'quiz']
# boggle_(g.adj_matrix, dictionary_)
| [
"noreply@github.com"
] | pavelgolikov.noreply@github.com |
936b48ee81fd3a1af560c37d3d21098e5aa08a5a | 6a549c904abd31a0f9baafb2cde145eee92c8f9a | /virt/bin/pyrsa-sign | 06364ad7695f39d35a8eac3c7c989d05d706820e | [] | no_license | wnwanne/Celeb-Rekogntion-elasticbeanstalk-flask | 865d9b402ecae5807c0808d011ae151e22198fdf | 9d3d1a3f0cde46721c2a892a401846659f1c248b | refs/heads/master | 2022-12-27T04:17:52.745162 | 2020-10-02T15:48:13 | 2020-10-02T15:48:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 235 | #!/Users/nwannw/Python/eb-flask/virt/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from rsa.cli import sign
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(sign())
| [
"wnwanne@gmail.com"
] | wnwanne@gmail.com | |
478b7883a15d785cb783879ce765ad4e80b129cc | 09e57dd1374713f06b70d7b37a580130d9bbab0d | /benchmark/startCirq2159.py | f30bd1b9e7076d764cccf0b2f8633f2db406f693 | [
"BSD-3-Clause"
] | permissive | UCLA-SEAL/QDiff | ad53650034897abb5941e74539e3aee8edb600ab | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | refs/heads/main | 2023-08-05T04:52:24.961998 | 2021-09-19T02:56:16 | 2021-09-19T02:56:16 | 405,159,939 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,780 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=31
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
from cirq.contrib.svg import SVGCircuit
# Symbols for the rotation angles in the QAOA circuit.
def make_circuit(n: int, input_qubit):
c = cirq.Circuit() # circuit begin
c.append(cirq.H.on(input_qubit[0])) # number=9
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[3])) # number=21
c.append(cirq.X.on(input_qubit[3])) # number=22
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[3])) # number=23
c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=28
c.append(cirq.Z.on(input_qubit[1])) # number=29
c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=30
c.append(cirq.H.on(input_qubit[1])) # number=2
c.append(cirq.H.on(input_qubit[3])) # number=16
c.append(cirq.H.on(input_qubit[2])) # number=3
c.append(cirq.H.on(input_qubit[3])) # number=4
c.append(cirq.H.on(input_qubit[0])) # number=5
c.append(cirq.H.on(input_qubit[1])) # number=6
c.append(cirq.H.on(input_qubit[2])) # number=7
c.append(cirq.H.on(input_qubit[3])) # number=8
c.append(cirq.X.on(input_qubit[3])) # number=1
c.append(cirq.H.on(input_qubit[0])) # number=18
c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=19
c.append(cirq.H.on(input_qubit[2])) # number=24
c.append(cirq.H.on(input_qubit[0])) # number=20
c.append(cirq.rx(-1.8378317023500288).on(input_qubit[1])) # number=25
c.append(cirq.Z.on(input_qubit[3])) # number=14
c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=15
c.append(cirq.X.on(input_qubit[2])) # number=11
c.append(cirq.X.on(input_qubit[2])) # number=12
c.append(cirq.Z.on(input_qubit[1])) # number=27
# circuit end
c.append(cirq.measure(*input_qubit, key='result'))
return c
def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
if __name__ == '__main__':
qubit_count = 4
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
circuit = make_circuit(qubit_count,input_qubits)
circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')
circuit_sample_count =2000
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=circuit_sample_count)
frequencies = result.histogram(key='result', fold_func=bitstring)
writefile = open("../data/startCirq2159.csv","w+")
print(format(frequencies),file=writefile)
print("results end", file=writefile)
print(circuit.__len__(), file=writefile)
print(circuit,file=writefile)
writefile.close() | [
"wangjiyuan123@yeah.net"
] | wangjiyuan123@yeah.net |
82a42c7bb24b95f394c0e9b6c27770954cf29f6c | 893efdd4adf81513bb34bf57ba90396b93adfa99 | /planner/models/__init__.py | 1dfb3cceea635daace465579db2f8c2bccd75a21 | [] | no_license | idvhfd/work-planner-api | 675be95366b71b311aecbacb7379a7214f61f795 | f0fa8c834a27ab0fd27f9319e04bcd7db73ec870 | refs/heads/main | 2023-03-17T05:21:41.859440 | 2021-03-08T10:37:07 | 2021-03-08T10:37:07 | 345,508,456 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 262 | py | from planner.app import db
from planner.models.base import Base
from planner.models.shift import Shift
from planner.models.worker import Worker
from planner.models.worker_shift import WorkerShift
__all__ = [
'db', 'Base', 'Shift', 'Worker', 'WorkerShift'
]
| [
"napuras@yahoo.com"
] | napuras@yahoo.com |
3819d7c059301682d62aad45f0a1abdd331fb962 | 79f42fd0de70f0fea931af610faeca3205fd54d4 | /base_lib/ChartDirector/pythondemo_cgi/paramcurve.py | 57fbd78daa0eb63e76913fb967eb41f277fcb584 | [
"IJG"
] | permissive | fanwen390922198/ceph_pressure_test | a900a6dc20473ae3ff1241188ed012d22de2eace | b6a5b6d324e935915090e791d9722d921f659b26 | refs/heads/main | 2021-08-27T16:26:57.500359 | 2021-06-02T05:18:39 | 2021-06-02T05:18:39 | 115,672,998 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,571 | py | #!/usr/bin/python
from pychartdir import *
# The XY data of the first data series
dataX0 = [10, 35, 17, 4, 22, 29, 45, 52, 63, 39]
dataY0 = [2.0, 3.2, 2.7, 1.2, 2.8, 2.9, 3.1, 3.0, 2.3, 3.3]
# The XY data of the second data series
dataX1 = [30, 35, 17, 4, 22, 59, 43, 52, 63, 39]
dataY1 = [1.0, 1.3, 0.7, 0.6, 0.8, 3.0, 1.8, 2.3, 3.4, 1.5]
# The XY data of the third data series
dataX2 = [28, 35, 15, 10, 22, 60, 46, 64, 39]
dataY2 = [2.0, 2.2, 1.2, 0.4, 1.8, 2.7, 2.4, 2.8, 2.4]
# Create a XYChart object of size 540 x 480 pixels
c = XYChart(540, 480)
# Set the plotarea at (70, 65) and of size 400 x 350 pixels, with white background and a light grey
# border (0xc0c0c0). Turn on both horizontal and vertical grid lines with light grey color
# (0xc0c0c0)
c.setPlotArea(70, 65, 400, 350, 0xffffff, -1, 0xc0c0c0, 0xc0c0c0, -1)
# Add a legend box with the top center point anchored at (270, 30). Use horizontal layout. Use 10pt
# Arial Bold Italic font. Set the background and border color to Transparent.
legendBox = c.addLegend(270, 30, 0, "arialbi.ttf", 10)
legendBox.setAlignment(TopCenter)
legendBox.setBackground(Transparent, Transparent)
# Add a title to the chart using 18 point Times Bold Itatic font.
c.addTitle("Parametric Curve Fitting", "timesbi.ttf", 18)
# Add titles to the axes using 12pt Arial Bold Italic font
c.yAxis().setTitle("Axis Title Placeholder", "arialbi.ttf", 12)
c.xAxis().setTitle("Axis Title Placeholder", "arialbi.ttf", 12)
# Set the axes line width to 3 pixels
c.yAxis().setWidth(3)
c.xAxis().setWidth(3)
# Add a scatter layer using (dataX0, dataY0)
c.addScatterLayer(dataX0, dataY0, "Polynomial", GlassSphere2Shape, 11, 0xff0000)
# Add a degree 2 polynomial trend line layer for (dataX0, dataY0)
trend0 = c.addTrendLayer2(dataX0, dataY0, 0xff0000)
trend0.setLineWidth(3)
trend0.setRegressionType(PolynomialRegression(2))
# Add a scatter layer for (dataX1, dataY1)
c.addScatterLayer(dataX1, dataY1, "Exponential", GlassSphere2Shape, 11, 0x00aa00)
# Add an exponential trend line layer for (dataX1, dataY1)
trend1 = c.addTrendLayer2(dataX1, dataY1, 0x00aa00)
trend1.setLineWidth(3)
trend1.setRegressionType(ExponentialRegression)
# Add a scatter layer using (dataX2, dataY2)
c.addScatterLayer(dataX2, dataY2, "Logarithmic", GlassSphere2Shape, 11, 0x0000ff)
# Add a logarithmic trend line layer for (dataX2, dataY2)
trend2 = c.addTrendLayer2(dataX2, dataY2, 0x0000ff)
trend2.setLineWidth(3)
trend2.setRegressionType(LogarithmicRegression)
# Output the chart
print("Content-type: image/png\n")
binaryPrint(c.makeChart2(PNG))
| [
"fanwen@sscc.com"
] | fanwen@sscc.com |
23f873a81c26372241e78defd80acb0e77ecd5e4 | a520c0474e5375309a9aeaa80e24b8d260966b58 | /src/tools/command_calibration.py | cdfbe35966dd4b4562b0a81ae72782195069f322 | [] | no_license | CLAP-Framework/clap | 6caf7ca549f23f493a5197e08608495448b17fb3 | a14602323d63cccf62a12e6db2979205ff2efe30 | refs/heads/master | 2022-04-28T21:03:04.252498 | 2021-01-23T09:38:12 | 2021-01-23T09:38:12 | 253,822,544 | 13 | 6 | null | null | null | null | UTF-8 | Python | false | false | 480 | py | import numpy as np
class LongitudinalCalibration():
"""
Calibrate the mapping from v,throttle,brake to acc/dec
"""
def __init__(self):
self.last_speed = None
pass
def run_step(self, target_speed, current_speed, debug=False, dt=0.05):
"""
target is not useful
"""
pass
if self.last_speed is not None:
acc = (current_speed - self.last_speed)/dt
# save file
control = 0.1
| [
"caozhong@0587403218.wireless.umich.net"
] | caozhong@0587403218.wireless.umich.net |
83bcbab51477d33600aadd5a6445baedef77b289 | 91a720fd23224a1f363c19c826852062e49b65ec | /Loop/test3.3.py | 69c3011fd45e741df366d97e24c3a3403e687ceb | [] | no_license | ronnapoom/python | d8d8b64ed8122841d7d4e28bdbaf02ba57b82625 | 1b02445a5932b220c11de74b6ff45cfd28525429 | refs/heads/master | 2023-03-09T21:09:24.245633 | 2021-02-20T10:31:51 | 2021-02-20T10:31:51 | 336,190,030 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 441 | py | print("ป้อนชื่ออาหารสุดโปรดของคุณ หรือ exit เพื่อออกจากโปรแกรม")
food_fav = []
n = 0
while(True) :
n += 1
food = str(input("อาหารโปรดลำดับที่ {} :\t".format(n)))
food_fav.append(food)
if(food == "exit") :
break
for n in range (1,n) :
print(n,".",food_fav[n-1], end = " " )
| [
"ronnapoom.p@kkumail.com"
] | ronnapoom.p@kkumail.com |
d0131f28edd0dbb70f2227022124e8b134eb6603 | 6805e7e3535e03e8563beeae5c6bdd23a8d13166 | /Src/certificacion/admin.py | 1480579cdfb2773926aff3375c78520fa4bd359a | [] | no_license | natchz/auditoria | 0b00cbee29faa9b015bf399722c1cd9534b22fd3 | 9c9b66dbf68d702726386e8f894b509faa55d56c | refs/heads/master | 2022-12-19T19:30:58.813805 | 2016-10-23T03:05:55 | 2016-10-23T03:05:55 | 68,713,561 | 0 | 1 | null | 2022-12-18T01:37:38 | 2016-09-20T13:16:06 | Python | UTF-8 | Python | false | false | 728 | py | from django.contrib import admin
import nested_admin
from .models import *
class ControlInline(nested_admin.NestedTabularInline):
model = Control
extra = 0
class ObjetivoInline(nested_admin.NestedTabularInline):
model = Objetivo
extra = 0
inlines = [
ControlInline,
]
class DominioInline(nested_admin.NestedTabularInline):
model = Dominio
extra = 0
inlines = [
ObjetivoInline,
]
class CertificacionAdmin(nested_admin.NestedModelAdmin):
list_display = ["nombre", "tipo"]
inlines = [
DominioInline,
]
class Meta:
model = Certificacion
admin.site.register(Certificacion, CertificacionAdmin)
admin.site.register(Dominio)
admin.site.register(Objetivo)
admin.site.register(Control)
admin.site.register(Tipo) | [
"luis.garciap@upb.edu.co"
] | luis.garciap@upb.edu.co |
19cba141ff8d1bd69e3aefcd565294ac906b246a | 13bb19cdcca1a7ebf10f5077650300e28ed75214 | /kmap_ids.py | 9e258edd7fc69a6a1803d13aa14906b393cc8d52 | [] | no_license | shanti-uva/shanti-texts-thl-migrate | 7172d777d26401e41daf2cc1c2d9c4aace1441d4 | b9b7d6ec17ab92b4685f31e60fa25c67668b1d52 | refs/heads/master | 2016-09-05T12:54:20.070233 | 2015-01-26T20:06:29 | 2015-01-26T20:06:29 | 28,922,175 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,650 | py | # Lists of some KMap IDs with documents
kmaps = {'places':[],'subjects':[]}
kmaps['places'] = [1, 179, 317, 433, 486, 516, 534, 570, 588, 634, 637, 674,
749, 782, 807, 838, 884, 1063, 1064, 1068, 1070, 1073, 1075, 1084, 1085, 1087,
1089, 1090, 1091, 1094, 1098, 1144, 1147, 1165, 1236, 2541, 2675, 3507, 3718,
3862, 3873, 4439, 4874, 5224, 5225, 5226, 5228, 5230, 5231, 5233, 5234, 5235,
5298, 10656, 11613, 13734, 13735, 13740, 15344, 15345, 15346, 15347, 15348,
15354, 15355, 15356, 15369, 15372, 15373, 15374, 15375, 15376, 15389, 15401,
15404, 15405, 15406, 15407, 15409, 15410, 15411, 15412, 15413, 15414, 15415,
15416, 15417, 15418, 15419, 15420, 15421, 15422, 15423, 15424, 15425, 15426,
15427, 15428, 15432, 15433, 15434, 15435, 15436, 15437, 15438, 15439, 15440,
15441, 15442, 15443, 15444, 15445, 15446, 15447, 15448, 15456, 15466, 15467,
15468, 15470, 15472, 15474, 15476, 15478, 15479, 15480, 15481, 15482, 15483,
15774, 16408, 16409, 16410, 16411, 16412, 16413, 16414, 16415, 16416, 16417,
16418, 16420, 16421, 16422, 16424, 16425, 16426, 16427, 16428, 16429, 16430,
16431, 16432, 16433, 16434, 16435, 16436, 16437, 16438, 16439, 16440, 16441,
16442, 16443, 16444, 16468, 16469, 16470, 16471, 16472, 16473, 16474, 16475,
16476, 16477, 16478, 16479, 16480, 16481, 16482, 16483, 16484, 16485, 16486,
16487, 16488, 16489, 16490, 16491, 16492, 16493, 16494, 16495, 16496, 16497,
16498, 16499, 16500, 16501, 16502, 16503, 16504, 16506, 16507, 16508, 16509,
16510, 16511, 16512, 16513, 16514, 16515, 16516, 16517, 16518, 16519, 16520,
16521, 16522, 16523, 16524, 16525, 16526, 16527, 16528, 16529, 16531, 16532,
16533, 16534, 16535, 16536, 16537, 16538, 16539, 16540, 16541, 16542, 16543,
16544, 16545, 16546, 16548, 16549, 16550, 16551, 16552, 16553, 16554, 16555,
16556, 16557, 16558, 16559, 16560, 16561, 16562, 16563, 16564, 16565, 16566,
16567, 16568, 16569, 16570, 16571, 16572, 16573, 16574, 16575, 16576, 16577,
16578, 16579, 16580, 16581, 16582, 16583, 16584, 16585, 16586, 16587, 16588,
16589, 16590, 16591, 16592, 16593, 16594, 16595, 16596, 16597, 16598, 16599,
16600, 16601, 16602, 16604, 16605, 16606, 16607, 16608, 16609, 16610, 16611,
16612, 16613, 16614, 16615, 16616, 16617, 16618, 16619, 16620, 16621, 16622,
16623, 16624, 16625, 16626, 16627, 16628, 16629, 16630, 16631, 16632, 16633,
16634, 16635, 16636, 16637, 16638, 16639, 16640, 16641, 16642, 16643, 16644,
16645, 16646, 16647, 16648, 16649, 16650, 16651, 16652, 16653, 16654, 16655,
16656, 16657, 16658, 16659, 16660, 16661, 16662, 16663, 16664, 16665, 16666,
16667, 16668, 16669, 16670, 16671, 16672, 16673, 16674, 16675, 16676, 16677,
16678, 16679, 16680, 16681, 16682, 16683, 16684, 16685, 16686, 16687, 16688,
16689, 16690, 16691, 16692, 16693, 16694, 16695, 16696, 16697, 16698, 16699,
16700, 16701, 16702, 16703, 16704, 16705, 16706, 16707, 16708, 16709, 16710,
16711, 16713, 16714, 16715, 16716, 16717, 16718, 16719, 16721, 16722, 16723,
16724, 16725, 16726, 16727, 16730, 16731, 16732, 16733, 16734, 16735, 16736,
16737, 16738, 16739, 16740, 16741, 16742, 16743, 16744, 16746, 16748, 16749,
16750, 16751, 16752, 16754, 16755, 16756, 16757, 16758, 16759, 16760, 16761,
16762, 16763, 16764, 16765, 16766, 16767, 16768, 16770, 16771, 16772, 16773,
16774, 16775, 16776, 16777, 16778, 16781, 16782, 16783, 16784, 16785, 16786,
16787, 16788, 16790, 16791, 16792, 16793, 16794, 16795, 16796, 16797, 16798,
16799, 16801, 16802, 16803, 16804, 16805, 16806, 16807, 16808, 16809, 16810,
16811, 16812, 16814, 16815, 16816, 16817, 16819, 16820, 16821, 16822, 16823,
16824, 16825, 16826, 16827, 16828, 16829, 16830, 16831, 16832, 16835, 16836,
16837, 16838, 16841, 16842, 16843, 16845, 16846, 16847, 16848, 16849, 16850,
16851, 16852, 16853, 16854, 16855, 16856, 16857, 16859, 16860, 16861, 16862,
16863, 16864, 16865, 16866, 16867, 16868, 16869, 16885, 16886, 16887, 16888,
16889, 16890, 16891, 16892, 16894, 16895, 16896, 16897, 16898, 16900, 16901,
16902, 16903, 16904, 16905, 16906, 16907, 16908, 16909, 16910, 16911, 16912,
16913, 16914, 16915, 16916, 16917, 16918, 16919, 16920, 16921, 16922, 16923,
16924, 16925, 16926, 16927, 16928, 16929, 16930, 16931, 16932, 16933, 16934,
16935, 16936, 16937, 16938, 16939, 16940, 16941, 16942, 16943, 16944, 16945,
16946, 16947, 16949, 16950, 16951, 16952, 16953, 16954, 16955, 16956, 16957,
16958, 16959, 16960, 16961, 16962, 17021, 17089, 17093, 17108, 17421, 17447,
22146, 22253, 22297, 22298, 22299, 22300, 22302, 22303, 22304, 22305, 22306,
22307, 22308, 22309, 22335, 22338, 22339, 22340, 22341, 22342, 22343, 22344,
22348, 22349, 22350, 22352, 22353, 22354, 22355, 22356, 22357, 22361, 22363,
22365, 22366, 22367, 22368, 22369, 22370, 22371, 22372, 22373, 22374, 22375,
22377, 22378, 22379, 22380, 22381, 22382, 22384, 22385, 22386, 22387, 22388,
22389, 22390, 22391, 22393, 22395, 22396, 22397, 22401, 22409, 22411, 22412,
22413, 22415, 22416, 22418, 22421, 22424, 22568, 22707, 23155, 23294, 23335,
23404, 23405, 23406, 23407, 23408, 23409, 23410, 23411, 23412, 23413, 23414,
23415, 23416, 23417, 23418, 23419, 23420, 23421, 23422, 23423, 23424, 23425,
23426, 23427, 23428, 23429, 23430, 23431, 23432, 23433, 23434, 23435, 23436,
23437, 23438, 23439, 23440, 23441, 23442, 23443, 23444, 23445, 23446, 23447,
23448, 23449, 23450, 23451, 23452, 23453, 23454, 23455, 23456, 23457, 23458,
23459, 23460, 23461, 23462, 23463, 23464, 23465, 23466, 23467, 23468, 23469,
23470, 23471, 23472, 23473, 23474, 23475, 23476, 23477, 23478, 23479, 23480,
23481, 23482, 23483, 23484, 23485, 23486, 23487, 23488, 23489, 23490, 23492,
23493, 23494, 23497, 23498, 23499, 23500, 23501, 23502, 23503, 23504, 23505,
23506, 23507, 23508, 23509, 23510, 23511, 23512, 23513, 23514, 23515, 23516,
23517, 23518, 23519, 23520, 23521, 23522, 23523, 23524, 23525, 23526, 23527,
23528, 23529, 23530, 23531, 23532, 23533, 23534, 23535, 23536, 23537, 23538,
23539, 23540, 23541, 23542, 23543, 23544, 23545, 23546, 23547, 23548, 23549,
23550, 23551, 23552, 23553, 23554, 23555, 23556, 23557, 23558, 23559, 23560,
23561, 23562, 23563, 23564, 23565, 23566, 23567, 23568, 23569, 23570, 23571,
23572, 23573, 23574, 23575, 23576, 23577, 23578, 23579, 23580, 23581, 23582,
23583, 23584, 23585, 23586, 23587, 23588, 23589, 23590, 23591, 23592, 23593,
23594, 23595, 23596, 23597, 23598, 23599, 23600, 23601, 23602, 23603, 23604,
23605, 23606, 23607, 23608, 23609, 23610, 23611, 23612, 23613, 23614, 23615,
23616, 23617, 23618, 23619, 23620, 23621, 23623, 23624, 23625, 23626, 23627,
23628, 23629, 23630, 23631, 23632, 23633, 23634, 23635, 23636, 23637, 23638,
23639, 23640, 23641, 23642, 23643, 23644, 23653, 23671, 23672, 23673, 23674,
23675, 23676, 23677, 23678, 23679, 23680, 23681, 23682, 23683, 23684, 23685,
23686, 23687, 23688, 23689, 23690, 23691, 23700, 23725, 23731, 23744, 23745,
23748, 23750, 23751, 23752, 23753, 24071, 24106, 24107, 24108, 24111, 24112,
24121, 24122, 24123, 24124, 24125, 24126, 24127, 24128, 24353, 24566, 24567,
24568, 24573, 25107]
kmaps['subjects'] = [20, 21, 23, 24, 25, 26, 27, 28, 29, 31, 32, 35, 36, 38,
84, 104, 109, 111, 119, 125, 132, 133, 134, 141, 143, 147, 150, 154, 159, 160,
161, 162, 164, 169, 173, 191, 202, 203, 204, 252, 263, 264, 265, 266, 268, 286,
289, 290, 292, 293, 294, 295, 297, 299, 300, 301, 302, 303, 304, 307, 308, 353,
363, 377, 381, 382, 385, 386, 387, 391, 399, 402, 406, 418, 420, 422, 423, 425,
426, 435, 436, 442, 448, 455, 456, 462, 463, 466, 469, 470, 471, 475, 477, 478,
479, 480, 481, 482, 483, 485, 486, 487, 490, 491, 492, 494, 495, 499, 508, 514,
516, 522, 523, 524, 525, 526, 549, 555, 576, 588, 590, 591, 595, 619, 635, 638,
639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 655, 657, 661,
662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 675, 676, 677, 678, 679,
680, 681, 682, 683, 684, 685, 686, 687, 689, 690, 691, 692, 693, 694, 695, 696,
697, 698, 705, 709, 727, 728, 729, 731, 732, 733, 737, 752, 760, 761, 762, 763,
764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779,
780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795,
796, 797, 798, 799, 800, 802, 803, 804, 805, 806, 807, 808, 809, 810, 816, 817,
818, 819, 820, 821, 822, 824, 825, 829, 831, 832, 833, 834, 835, 840, 844, 845,
846, 847, 848, 849, 850, 852, 853, 854, 855, 856, 857, 871, 883, 884, 885, 887,
888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 902, 903, 904,
905, 906, 907, 908, 909, 910, 911, 912, 914, 915, 916, 917, 918, 920, 921, 923,
925, 927, 936, 937, 938, 947, 1063, 1705, 1708, 1709, 1710, 1712, 1713, 1716,
1718, 1724, 1725, 1726, 1727, 1752, 1775, 1776, 1777, 1780, 1781, 1782, 1783,
1784, 1785, 1786, 1787, 1788, 1789, 1790, 1808, 1809, 1811, 1812, 1813, 1814,
1815, 1816, 1817, 1818, 1820, 1821, 1822, 1823, 1824, 1825, 1826, 1828, 1829,
1831, 1832, 1833, 1834, 1835, 1836, 1838, 1839, 1840, 1841, 1842, 1848, 1849,
1851, 1852, 1853, 1854, 1855, 1857, 1858, 1859, 1860, 1861, 1862, 1863, 1864,
1865, 1866, 1867, 1868, 1869, 1870, 1871, 1872, 1873, 1874, 1875, 1876, 1877,
1878, 1880, 1881, 1882, 1883, 1884, 1886, 1887, 1888, 1889, 1891, 1892, 1895,
1896, 1897, 1898, 1908, 1909, 1910, 1912, 1913, 1914, 1915, 1916, 1917, 1926,
1927, 1928, 1929, 1930, 1933, 1934, 1938, 1941, 1945, 1949, 1950, 1951, 1952,
1953, 1957, 1959, 1960, 1961, 1962, 1963, 1964, 1965, 1966, 1968, 1969, 1970,
1971, 1977, 1983, 1986, 1987, 1989, 1992, 1995, 2001, 2002, 2003, 2012, 2015,
2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029,
2030, 2031, 2032, 2033, 2034, 2035, 2036, 2040, 2041, 2042, 2043, 2044, 2045,
2047, 2062, 2063, 2065, 2066, 2080, 2093, 2095, 2108, 2109, 2110, 2111, 2112,
2113, 2114, 2115, 2116, 2117, 2118, 2119, 2121, 2122, 2124, 2125, 2126, 2127,
2128, 2130, 2131, 2132, 2133, 2134, 2135, 2136, 2137, 2138, 2139, 2144, 2150,
2151, 2152, 2153, 2154, 2156, 2157, 2160, 2164, 2165, 2166, 2167, 2168, 2169,
2170, 2171, 2172, 2173, 2174, 2176, 2177, 2178, 2179, 2180, 2181, 2182, 2183,
2184, 2185, 2187, 2188, 2189, 2190, 2191, 2192, 2193, 2194, 2195, 2196, 2197,
2198, 2199, 2200, 2201, 2202, 2203, 2204, 2205, 2206, 2207, 2208, 2209, 2210,
2212, 2213, 2214, 2215, 2216, 2217, 2218, 2219, 2220, 2221, 2222, 2223, 2225,
2226, 2227, 2228, 2230, 2231, 2233, 2234, 2236, 2237, 2238, 2239, 2240, 2241,
2242, 2243, 2244, 2245, 2247, 2248, 2249, 2250, 2251, 2252, 2253, 2254, 2255,
2256, 2257, 2258, 2259, 2260, 2261, 2262, 2263, 2264, 2265, 2266, 2267, 2268,
2269, 2270, 2271, 2272, 2273, 2274, 2276, 2277, 2279, 2280, 2281, 2282, 2283,
2284, 2285, 2287, 2288, 2289, 2290, 2291, 2292, 2293, 2294, 2295, 2296, 2297,
2298, 2299, 2300, 2301, 2302, 2303, 2304, 2305, 2306, 2307, 2308, 2309, 2310,
2311, 2312, 2313, 2315, 2316, 2317, 2318, 2319, 2321, 2322, 2323, 2324, 2325,
2326, 2327, 2328, 2329, 2330, 2331, 2332, 2334, 2335, 2336, 2337, 2338, 2340,
2341, 2342, 2343, 2345, 2347, 2348, 2349, 2350, 2351, 2352, 2353, 2354, 2355,
2356, 2357, 2358, 2359, 2360, 2361, 2362, 2363, 2364, 2365, 2366, 2367, 2368,
2369, 2370, 2371, 2372, 2373, 2376, 2377, 2379, 2380, 2382, 2383, 2384, 2385,
2387, 2388, 2389, 2390, 2391, 2392, 2393, 2394, 2395, 2396, 2397, 2398, 2399,
2400, 2401, 2402, 2403, 2404, 2405, 2407, 2408, 2409, 2410, 2411, 2412, 2413,
2414, 2415, 2416, 2417, 2418, 2419, 2420, 2421, 2422, 2423, 2425, 2426, 2428,
2429, 2430, 2431, 2433, 2434, 2435, 2436, 2437, 2439, 2440, 2441, 2442, 2443,
2444, 2445, 2446, 2447, 2448, 2449, 2450, 2451, 2452, 2453, 2454, 2455, 2456,
2457, 2458, 2459, 2460, 2461, 2462, 2463, 2464, 2465, 2466, 2467, 2468, 2469,
2470, 2472, 2473, 2474, 2475, 2476, 2477, 2478, 2479, 2480, 2481, 2482, 2483,
2484, 2485, 2486, 2487, 2488, 2489, 2490, 2491, 2492, 2493, 2494, 2495, 2496,
2497, 2498, 2499, 2501, 2502, 2503, 2504, 2505, 2506, 2507, 2508, 2510, 2511,
2512, 2513, 2514, 2516, 2517, 2519, 2521, 2522, 2523, 2524, 2525, 2526, 2527,
2528, 2529, 2530, 2531, 2532, 2533, 2534, 2535, 2536, 2537, 2538, 2539, 2540,
2541, 2542, 2543, 2545, 2546, 2547, 2548, 2549, 2550, 2552, 2554, 2636, 2695,
2711, 2713, 2714, 2805, 2988, 2992, 3006, 3033, 3070, 3072, 3088, 3101, 3435,
3437, 3438, 3443, 3445, 3655, 3702, 3765, 3808, 3809, 3810, 3811, 3964, 3965,
3967, 3972, 3977, 3979, 3980, 3989, 3990, 3991, 3992, 3993, 3994, 3995, 3996,
3997, 3998, 4000, 4001, 4005, 4008, 4009, 4012, 4091, 4092, 4093, 4095, 4096,
4097, 4098, 4099, 4100, 4101, 4109, 4110, 4139, 4145, 4146, 4173, 4174, 4195,
4196, 4197, 4198, 4287, 4290, 4291, 4292, 4294, 4309, 4315, 4318, 4319, 4320,
4321, 4322, 4323, 4324, 4326, 4327, 4328, 4374, 4427, 4441, 4482, 4483, 4499,
4500, 4501, 4502, 4503, 4504, 4509, 4533, 4539, 4544, 4545, 4546, 4550, 4551,
4552, 4576, 4719, 4720, 4767, 4769, 4771, 4772, 4773, 4774, 4775, 4776, 4777,
4778, 4779, 4780, 4781, 4782, 4783, 4784, 4785, 4786, 4787, 4788, 4790, 4791,
4792, 4793, 4794, 4795, 4848, 4851, 4852, 4853, 4854, 4855, 4856, 4857, 4860,
4861, 4862, 4863, 4864, 4865, 4866, 4867, 4868, 4869, 4871, 4872, 4873, 4874,
4876, 4881, 4882, 4884, 4885, 4887, 4888, 4889, 4890, 4891, 4892, 4894, 4895,
4896, 4897, 4898, 4900, 4901, 4903, 4904, 4906, 4913, 4914, 4915, 4916, 4921,
4924, 4941, 4949, 4950, 4951, 4952, 4961, 5009, 5010, 5048, 5049, 5050, 5051,
5052, 5053, 5067, 5070, 5071, 5072, 5073, 5074, 5075, 5077, 5078, 5080, 5081,
5082, 5083, 5084, 5085, 5086, 5087, 5088, 5089, 5090, 5091, 5092, 5093, 5094,
5095, 5096, 5097, 5098, 5099, 5100, 5101, 5102, 5103, 5106, 5107, 5110, 5111,
5112, 5113, 5115, 5116, 5117, 5118, 5119, 5120, 5121, 5122, 5124, 5125, 5126,
5128, 5129, 5130, 5132, 5133, 5134, 5135, 5136, 5138, 5139, 5140, 5142, 5143,
5145, 5147, 5148, 5150, 5151, 5152, 5153, 5154, 5155, 5156, 5157, 5158, 5182,
5190, 5191, 5192, 5193, 5194, 5195, 5196, 5197, 5198, 5199, 5200, 5201, 5202,
5203, 5205, 5206, 5207, 5208, 5209, 5210, 5211, 5214, 5215, 5216, 5217, 5220,
5221, 5222, 5223, 5224, 5225, 5226, 5227, 5228, 5229, 5230, 5231, 5232, 5233,
5234, 5235, 5237, 5238, 5239, 5240, 5241, 5242, 5243, 5244, 5245, 5246, 5248,
5249, 5250, 5251, 5252, 5253, 5254, 5255, 5257, 5258, 5259, 5260, 5261, 5262,
5263, 5264, 5265, 5266, 5267, 5268, 5269, 5270, 5271, 5272, 5273, 5274, 5275,
5276, 5277, 5278, 5279, 5280, 5281, 5283, 5284, 5285, 5286, 5287, 5288, 5289,
5290, 5291, 5292, 5293, 5294, 5295, 5296, 5297, 5298, 5299, 5300, 5301, 5302,
5303, 5304, 5305, 5306, 5307, 5308, 5309, 5310, 5311, 5312, 5313, 5314, 5315,
5316, 5318, 5319, 5320, 5321, 5322, 5323, 5324, 5325, 5326, 5327, 5328, 5330,
5331, 5332, 5333, 5334, 5335, 5336, 5338, 5339, 5340, 5341, 5342, 5343, 5344,
5345, 5346, 5348, 5349, 5350, 5351, 5352, 5353, 5354, 5355, 5356, 5357, 5358,
5359, 5360, 5361, 5362, 5363, 5364, 5365, 5366, 5367, 5368, 5369, 5370, 5381,
5401, 5402, 5407, 5416, 5418, 5422, 5456, 5464, 5465, 5466, 5470, 5517, 5543,
5548, 5549, 5660, 5662, 5663, 5664, 5665, 5666, 5667, 5668, 5669, 5670, 5671,
5672, 5673, 5674, 5675, 5676, 5677, 5678, 5680, 5681, 5682, 5683, 5684, 5685,
5686, 5687, 5688, 5689, 5690, 5691, 5692, 5693, 5694, 5697, 5698, 5699, 5700,
5701, 5703, 5704, 5706, 5707, 5708, 5709, 5710, 5712, 5713, 5715, 5716, 5717,
5718, 5719, 5720, 5721, 5722, 5723, 5724, 5725, 5726, 5727, 5729, 5730, 5731,
5732, 5733, 5734, 5735, 5736, 5738, 5739, 5740, 5742, 5743, 5745, 5746, 5747,
5748, 5749, 5750, 5751, 5752, 5753, 5754, 5756, 5757, 5758, 5759, 5760, 5762,
5769, 5770, 5771, 5772, 5773, 5778, 5779, 5781, 5783, 5804, 5814, 5815, 5816,
5818, 5822, 5823, 5824, 5825, 5826, 5827, 5828, 5829, 5830, 5831, 5834, 5837,
5839, 5840, 5841, 5842, 5843, 5844, 5847, 5852, 5857, 5902, 5905, 5913, 5920,
5935, 5944, 6033, 6171, 6310, 6327, 6328, 6330, 6345, 6364, 6401, 6404, 6431,
6647, 6651, 6690, 6704, 6705, 6706, 6707, 6709, 6710, 6711, 6712, 6713, 6715,
6716, 6717, 6718, 6719, 6720, 6721, 6722, 6723, 6724, 6725, 6726, 6727, 6728,
6729, 6730, 6731, 6732, 6733, 6734, 6735, 6736, 6737, 6738, 6739, 6740, 6741,
6742, 6743, 6744, 6745, 6747, 6748, 6750, 6751, 6752, 6753, 6754, 6756, 6758,
6759, 6760, 6761, 6762, 6772, 6773, 6774, 6775, 6776, 6777, 6779, 6780, 6805,
6811, 6812, 6813, 6814, 6815, 6816, 6817, 6818, 6819, 6820, 6821, 6822, 6823,
6824, 6825, 6826, 6827, 6828, 6830, 6831, 6832, 6833, 6834, 6835, 6836, 6837,
6838, 6839, 6840, 6841, 6842, 6884, 6885, 6886, 6887, 6888, 6889, 6890, 6891,
6892, 6894, 6895, 6896, 6898, 6899, 6900, 6901, 6902, 6903, 6904, 6905, 6906,
6907, 6908, 6909, 6910, 6911, 6912, 6913, 6914, 6915, 6916, 6917, 6918, 6919,
6920, 6921, 6922, 6923, 6924, 6925, 6926, 6927, 6928, 6932, 6933, 6934, 6936,
6937, 6938, 6939, 6940, 6941, 6942, 6943, 6944, 6945, 6946, 6947, 6948, 6949,
6950, 6951, 6952, 6953, 6954, 6955, 6956, 6957, 6958, 6959, 6960, 6961, 6962,
6963, 6964, 6965, 6966, 6967, 6968, 6969, 6970, 6971, 6972, 6973]
| [
"ontoligent@gmail.com"
] | ontoligent@gmail.com |
606e6885dd12bc55c37b30f970e4fae09dbb24a5 | e2350b2f7408c109f19a3cae061826dd2dbec4b9 | /jsonrpcdb/tests/test_connection.py | 77745c7771eb8d0545e9f5781459b34d7ed73d1c | [
"MIT"
] | permissive | livestalker-archive/json-rpc-db | 3a0c7e794be3a97ae594bc844a9b8a1503e8dacd | f18067b0e38241a3b3c77358c16cddbc26b45127 | refs/heads/master | 2021-06-22T17:07:37.991647 | 2017-06-29T09:18:04 | 2017-06-29T09:18:04 | 94,331,081 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,445 | py | from unittest import TestCase
import jsonrpcdb as Database
from jsonrpcdb.auth import TokenAuth
from jsonrpcdb.error import ProgrammingError
class ConnectionTest(TestCase):
def test_empty_conn_params(self):
conn_params = {}
conn = Database.connect(**conn_params)
self.assertEqual('http://localhost', conn.get_url())
def test_conn_params(self):
conn_params = {
'database': 'json-rpc.php'
}
conn = Database.connect(**conn_params)
self.assertEqual('http://localhost/json-rpc.php', conn.get_url())
conn_params = {
'database': '/json-rpc.php'
}
conn = Database.connect(**conn_params)
self.assertEqual('http://localhost/json-rpc.php', conn.get_url())
conn_params = {
'host': 'test.com',
'port': 4000,
'database': '/json-rpc.php'
}
conn = Database.connect(**conn_params)
self.assertEqual('http://test.com:4000/json-rpc.php', conn.get_url())
conn_params = {
'schema': 'https',
'host': 'test.com',
'port': 4000,
'database': '/json-rpc.php'
}
conn = Database.connect(**conn_params)
self.assertEqual('https://test.com:4000/json-rpc.php', conn.get_url())
def test_is_protect(self):
conn_params = {
'port': 4000,
'user': 'test',
'password': 'test',
'auth_type': 'token'
}
conn = Database.connect(**conn_params)
self.assertEqual(True, conn.is_protected())
def test_is_auth(self):
conn_params = {
'port': 4000,
'user': 'test',
'password': 'test',
'auth_type': 'token'
}
conn = Database.connect(**conn_params)
self.assertEqual(True, conn.is_auth())
def test_protected_res(self):
conn_params = {
'port': 4000,
'user': 'test',
'password': 'test',
'auth_type': 'token'
}
conn = Database.connect(**conn_params)
cur = conn.cursor()
data = {
'params': [1]
}
cur.execute('protected_res', data)
result = cur.fetchone()
self.assertEqual((1,), result)
cur.auth.set_token('fail_token')
with self.assertRaises(ProgrammingError):
cur.execute('protected_res', data)
| [
"mi.aleksio@gmail.com"
] | mi.aleksio@gmail.com |
73bf82bf1ab0ecd80b60da1489216bbcf7c8d918 | 2f9e5f3d98babc6e66027e97430104cc5489f930 | /tests/evse_tester.py | f07cd4aefb3d65ec1879c0c5e0d3da8a11504444 | [] | no_license | Tinkerforge/evse-bricklet | da6c0a8a703563d99e825df7a6a99fd3e94af16e | 889c852e75d63737b93859c25ddbd84ce6f8da8c | refs/heads/master | 2023-08-31T09:26:20.982738 | 2023-08-22T08:04:06 | 2023-08-22T08:04:06 | 251,574,386 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 5,346 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
HOST = "localhost"
PORT = 4223
UID_EVSE = None
UID_IDAI = "Mj8"
UID_IDO4 = "QXz"
UID_IDI4 = "QQ3"
UID_IQR1 = "FYF"
UID_IQR2 = "NWq"
UID_ICOU = "Gh4"
from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_evse import BrickletEVSE
from tinkerforge.bricklet_industrial_dual_analog_in_v2 import BrickletIndustrialDualAnalogInV2
from tinkerforge.bricklet_industrial_digital_out_4_v2 import BrickletIndustrialDigitalOut4V2
from tinkerforge.bricklet_industrial_digital_in_4_v2 import BrickletIndustrialDigitalIn4V2
from tinkerforge.bricklet_industrial_quad_relay_v2 import BrickletIndustrialQuadRelayV2
from tinkerforge.bricklet_industrial_counter import BrickletIndustrialCounter
import time
log = print
class EVSETester:
def __init__(self, log_func = None):
if log_func:
global log
log = log_func
self.ipcon = IPConnection()
self.ipcon.connect(HOST, PORT)
self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate)
self.ipcon.enumerate()
log("Trying to find EVSE Bricklet...")
while UID_EVSE == None:
time.sleep(0.1)
log("Found EVSE Bricklet: {0}".format(UID_EVSE))
self.evse = BrickletEVSE(UID_EVSE, self.ipcon)
self.idai = BrickletIndustrialDualAnalogInV2(UID_IDAI, self.ipcon)
self.ido4 = BrickletIndustrialDigitalOut4V2(UID_IDO4, self.ipcon)
self.idi4 = BrickletIndustrialDigitalIn4V2(UID_IDI4, self.ipcon)
self.iqr1 = BrickletIndustrialQuadRelayV2(UID_IQR1, self.ipcon)
self.iqr2 = BrickletIndustrialQuadRelayV2(UID_IQR2, self.ipcon)
self.icou = BrickletIndustrialCounter(UID_ICOU, self.ipcon)
def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type):
global UID_EVSE
if device_identifier == BrickletEVSE.DEVICE_IDENTIFIER:
UID_EVSE = uid
# Live = True
def set_contactor(self, contactor_input, contactor_output):
if contactor_input:
self.ido4.set_pwm_configuration(0, 500, 5000)
log('AC0 live')
else:
self.ido4.set_pwm_configuration(0, 500, 0)
log('AC0 off')
if contactor_output:
self.ido4.set_pwm_configuration(1, 500, 5000)
log('AC1 live')
else:
self.ido4.set_pwm_configuration(1, 500, 0)
log('AC1 off')
def set_diode(self, enable):
value = list(self.iqr1.get_value())
value[0] = enable
self.iqr1.set_value(value)
if enable:
log("Enable lock switch configuration diode")
else:
log("Disable lock switch configuration diode")
def get_cp_pe_voltage(self):
return self.idai.get_voltage(1)
def set_cp_pe_resistor(self, r2700, r880, r240):
value = list(self.iqr1.get_value())
value[1] = r2700
value[2] = r880
value[3] = r240
self.iqr1.set_value(value)
l = []
if r2700: l.append("2700 Ohm")
if r880: l.append("880 Ohm")
if r240: l.append("240 Ohm")
log("Set CP/PE resistor: " + ', '.join(l))
def set_pp_pe_resistor(self, r1500, r680, r220, r100):
value = [r1500, r680, r220, r100]
self.iqr2.set_value(value)
l = []
if r1500: l.append("1500 Ohm")
if r680: l.append("680 Ohm")
if r220: l.append("220 Ohm")
if r100: l.append("110 Ohm")
log("Set PP/PE resistor: " + ', '.join(l))
def wait_for_contactor_gpio(self, active):
if active:
log("Waiting for contactor GPIO to become active...")
else:
log("Waiting for contactor GPIO to become inactive...")
while True:
state = self.evse.get_low_level_state()
if state.gpio[3] == active:
break
time.sleep(0.01)
log("Done")
def wait_for_button_gpio(self, active):
if active:
log("Waiting for button GPIO to become active...")
else:
log("Waiting for button GPIO to become inactive...")
while True:
state = self.evse.get_low_level_state()
if state.gpio[0] == active:
break
time.sleep(0.1)
log("Done")
if __name__ == "__main__":
evse_tester = EVSETester()
# Initial config
evse_tester.set_contactor(True, False)
evse_tester.set_diode(True)
evse_tester.set_cp_pe_resistor(False, False, False)
evse_tester.set_pp_pe_resistor(False, False, True, False)
evse_tester.evse.reset()
time.sleep(5)
while True:
time.sleep(5)
evse_tester.set_cp_pe_resistor(True, False, False)
time.sleep(5)
evse_tester.set_cp_pe_resistor(True, True, False)
evse_tester.wait_for_contactor_gpio(True)
evse_tester.set_contactor(True, True)
time.sleep(10)
evse_tester.set_cp_pe_resistor(True, False, False)
evse_tester.wait_for_contactor_gpio(False)
evse_tester.set_contactor(True, False)
time.sleep(5)
evse_tester.set_cp_pe_resistor(False, False, False)
time.sleep(5)
| [
"olaf@tinkerforge.com"
] | olaf@tinkerforge.com |
898a48b374106740cf5b5f8e87bb25430f272b68 | 43684c2ffcfe81ffb278450d603493b4994d5da4 | /Test/test.py | f37d21bc13407175efad464016887c10a40e77c3 | [
"MIT"
] | permissive | fengduqianhe/CANE-master | cc5b3a9dde9a00a17993c9a1b6626aaf0428435d | 4d94bbd0669ccb103292e1e1f2c51e7c7a961e54 | refs/heads/master | 2020-08-09T23:06:20.933118 | 2019-10-10T13:57:20 | 2019-10-10T13:57:20 | 214,196,792 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 969 | py | import tensorflow as tf
if __name__ == "__main__":
a = tf.placeholder(tf.int32, [2, 3], name='Ta')
b = tf.Variable(tf.truncated_normal([64, 200, 300, 1], stddev=0.3))
te = tf.Variable(tf.truncated_normal([1148, 300], stddev=0.3))
ta = tf.Variable(tf.ones([64, 300], tf.int32))
c = tf.Variable(tf.truncated_normal([2, 100, 1, 100], stddev=0.3))
convA = tf.nn.conv2d(b, c, strides=[1, 1, 1, 1], padding='VALID')
tu = tf.nn.embedding_lookup(te, ta)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
#tu = sess.run(tu)
convA = sess.run(convA)
print(convA.shape)
hA = tf.tanh(tf.squeeze(convA))
print(hA.shape)
tmphA = tf.reshape(hA, [64 * 299, 2000 // 2])
#ha_mul_rand = tf.reshape(tf.matmul(tmphA, rand_matrix), [64, 300 - 1, 200 // 2])
# r1 = tf.matmul(ha_mul_rand, hB, adjoint_b=True)
# r3 = tf.matmul(ha_mul_rand, hNEG, adjoint_b=True)
# att1 = tf.expand_dims(tf.stack(r1), -1) | [
"www.qiaohezhe@foxmail.com"
] | www.qiaohezhe@foxmail.com |
5117725254eace3bbe900494720c70e983eceb81 | 0aa4698444bb67208173183dfa82bb71f1a5afd4 | /Matt/ClassifierNN/test.py | 564fee2bb11deb2742422e5284ac840ba37bdee0 | [
"MIT"
] | permissive | chrisburch96/LearningLAMOST | 3112091995f05ff95d7d6bbbb7f32a7d5d36589c | 082f1be6841828d6b62982cc11a043005d877668 | refs/heads/master | 2020-03-31T14:03:57.505144 | 2018-10-09T15:50:26 | 2018-10-09T15:50:26 | 152,278,431 | 0 | 0 | MIT | 2018-10-09T15:46:43 | 2018-10-09T15:46:42 | null | UTF-8 | Python | false | false | 445 | py | from sklearn.preprocessing import LabelEncoder
import numpy as np
import matplotlib.pyplot as plt
#import seaborn as sb
conf = np.loadtxt('Files/confusion.csv', delimiter = ',')
classes = ['STAR', 'GALAXY', 'QSO', 'Unknown']
actual = [[row[i] for row in conf] for i in range(len(classes))]
a = ['Matt', 'Chris', 'Chris', 'Matt', 'Chris']
hot = LabelEncoder()
print(hot.fit_transform(a))
#actual = actual.reshape
ax, fig = plt.subplots() | [
"mrs493@star.sr.bham.ac.uk"
] | mrs493@star.sr.bham.ac.uk |
47676a71c2dc34ca35a0b79ab4fe7de096c69750 | b29a579166c607cf320ec052f1c20aa541430255 | /pythone 3sem/lab4-5/task_5_1d.py | ef810adb08800c1700e09bee1759215fec9093d4 | [] | no_license | TohsyrovD/-1 | 5acb84f33d7d88e65399f085b896821945f12d25 | ebf19ef09c7ed36bf75db9ec88d1a6b6e4ed40da | refs/heads/master | 2021-07-14T11:21:19.923417 | 2020-12-03T10:32:26 | 2020-12-03T10:32:26 | 242,962,809 | 0 | 0 | null | 2021-03-20T05:32:52 | 2020-02-25T09:40:10 | HTML | UTF-8 | Python | false | false | 1,691 | py | # -*- coding: utf-8 -*-
"""
Задание 5.1d
Переделать скрипт из задания 5.1c таким образом, чтобы, при запросе параметра,
пользователь мог вводить название параметра в любом регистре.
Пример выполнения скрипта:
$ python task_5_1d.py
Введите имя устройства: r1
Введите имя параметра (ios, model, vendor, location, ip): IOS
15.4
Ограничение: нельзя изменять словарь london_co.
Все задания надо выполнять используя только пройденные темы.
То есть эту задачу можно решить без использования условия if.
"""
london_co = {
"r1": {
"location": "21 New Globe Walk",
"vendor": "Cisco",
"model": "4451",
"ios": "15.4",
"ip": "10.255.0.1",
},
"r2": {
"location": "21 New Globe Walk",
"vendor": "Cisco",
"model": "4451",
"ios": "15.4",
"ip": "10.255.0.2",
},
"sw1": {
"location": "21 New Globe Walk",
"vendor": "Cisco",
"model": "3850",
"ios": "3.6.XE",
"ip": "10.255.0.101",
"vlans": "10,20,30",
"routing": True,
},
}
x = input('Введите имя устройства: ')
y = input('Введите имя параметра {}:'.format(sorted(london_co[x])))
if not y in y.lower() :
y=y.lower()
if not y in london_co[x]:
print('Такого параметра нет')
print(london_co[x][y])
| [
"noreply@github.com"
] | TohsyrovD.noreply@github.com |
5c51bce7be23ebb58823dcc2a25575d9423ff5aa | 79817d40829ae2a959a80aa90131335066d9f11c | /DiaryFi/apps.py | 13f956c234d0fbe00d7dc4546f3fb463d8e597ef | [] | no_license | kushardogra/diaryfi | 897ac8a31c35382a5a88ff40be7f7170716fa1e7 | 75162e1de8b2e9b0757264df25f1df827e306880 | refs/heads/master | 2023-07-16T14:31:55.931022 | 2021-09-03T13:12:11 | 2021-09-03T13:12:11 | 402,774,275 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 146 | py | from django.apps import AppConfig
class DairyfiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'DiaryFi'
| [
"dograkushar@gmail.com"
] | dograkushar@gmail.com |
26270846aa0b5d6f85b668e71c0056a950a5a7ba | 266841fa3d2bd39a042fa8e75c7766eac8d5c3e0 | /text_model.py | 307f36f8ac981e4fbf5c9a5aaa8e0cd96aa62485 | [] | no_license | xixiareone/scene-graph-image-retrieval | ee7dc77102305ac3bbc4e08976d21aa6f2e3c359 | 5602f48da69bf62fc6fa87615e8c1f80b7ec47c0 | refs/heads/main | 2023-01-09T07:12:01.573767 | 2020-11-07T12:01:57 | 2020-11-07T12:01:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,975 | py | # Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Class for text data."""
import string
import numpy as np
import torch
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
class SimpleVocab(object):
def __init__(self):
super(SimpleVocab, self).__init__()
self.word2id = {}
self.wordcount = {}
self.word2id['<UNK>'] = 0
self.wordcount['<UNK>'] = 9e9
def tokenize_text(self, text):
text = text.encode('ascii', 'ignore').decode('ascii')
tokens = str(text).lower().translate(string.punctuation).strip().split()
return tokens
def add_text_to_vocab(self, text):
tokens = self.tokenize_text(text)
for token in tokens:
if token not in self.word2id:
self.word2id[token] = len(self.word2id)
self.wordcount[token] = 0
self.wordcount[token] += 1
def threshold_rare_words(self, wordcount_threshold=5):
for w in self.word2id:
if self.wordcount[w] < wordcount_threshold:
self.word2id[w] = 0
def encode_text(self, text):
tokens = self.tokenize_text(text)
x = [self.word2id.get(t, 0) for t in tokens]
return x
def get_size(self):
return len(self.word2id)
class TextLSTMModel(torch.nn.Module):
def __init__(self,
texts_to_build_vocab,
word_embed_dim=512,
lstm_hidden_dim=512):
super(TextLSTMModel, self).__init__()
self.vocab = SimpleVocab()
for text in texts_to_build_vocab:
self.vocab.add_text_to_vocab(text)
vocab_size = self.vocab.get_size()
self.word_embed_dim = word_embed_dim
self.lstm_hidden_dim = lstm_hidden_dim
self.embedding_layer = torch.nn.Embedding(vocab_size, word_embed_dim)
self.lstm = torch.nn.LSTM(word_embed_dim, lstm_hidden_dim)
self.fc_output = torch.nn.Sequential(
torch.nn.Dropout(p=0.1),
torch.nn.Linear(lstm_hidden_dim, lstm_hidden_dim),
)
def forward(self, x):
""" input x: list of strings"""
if type(x) is list:
if type(x[0]) is str or type(x[0]) is unicode:
x = [self.vocab.encode_text(text) for text in x]
assert type(x) is list
assert type(x[0]) is list
assert type(x[0][0]) is int
return self.forward_encoded_texts(x)
def forward_encoded_texts(self, texts):
# to tensor
lengths = [len(t) for t in texts]
itexts = torch.zeros((np.max(lengths), len(texts))).long()
for i in range(len(texts)):
itexts[:lengths[i], i] = torch.tensor(texts[i])
# embed words
itexts = torch.autograd.Variable(itexts).to(device)
etexts = self.embedding_layer(itexts)
# lstm
lstm_output, _ = self.forward_lstm_(etexts)
# get last output (using length)
text_features = []
for i in range(len(texts)):
text_features.append(lstm_output[lengths[i] - 1, i, :])
# output
text_features = torch.stack(text_features)
text_features = self.fc_output(text_features)
return text_features
def forward_lstm_(self, etexts):
batch_size = etexts.shape[1]
first_hidden = (torch.zeros(1, batch_size, self.lstm_hidden_dim),
torch.zeros(1, batch_size, self.lstm_hidden_dim))
first_hidden = (first_hidden[0].to(device), first_hidden[1].to(device))
lstm_output, last_hidden = self.lstm(etexts, first_hidden)
return lstm_output, last_hidden
| [
"revantteotia@gmail.com"
] | revantteotia@gmail.com |
a4d84d862a72f5ab47b575aa90a9c04a04ebc803 | ce7e1fdfe3c27edc11b8ebf3cc9ba3f04c534f99 | /dojo_moving.py | 0af5e1865673ec0585da77c2e19c457277a08cce | [] | no_license | sforaaleksander/rougelike | 3da792aeac473b594c5f3139e7822b43bc4f34b4 | 58d6882592620e03914f3e1394e6bd6925531817 | refs/heads/master | 2021-01-05T15:42:21.265768 | 2020-02-17T09:18:42 | 2020-02-17T09:18:42 | 241,064,980 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 941 | py | import os
os.system('clear')
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def display(hero_pos_x, hero_pos_y):
height = 20
width = 20
field = []
for i in range(height):
line = []
for j in range(width):
if i == 0 or i == height-1 or j == 0 or j == width-1:
line.append("#")
elif i == hero_pos_y and j == hero_pos_x:
line.append("@")
else:
line.append(".")
field.append(line)
field_string = ""
for element in field:
field_string += "".join(element) + "\n"
return field_string
print(display(12,17))
x = getch()
while x !="x":
x = getch()
print(x)
| [
"sforaaleksander@gmail.com"
] | sforaaleksander@gmail.com |
20f50a6fb34f4fcee24a7c178b4996af12e070cf | cb0c89bdb38203e5759a97737ac29026eb81be2f | /minesweeper/games/migrations/0005_cell_value.py | d4780f8ba8f1d9e5ba7df87b42789eaebd728462 | [] | no_license | lardissone/minesweeper-api | 632e84660120e900b7ffc1cd6b1cada0a3793dea | 86e43356fac8e37ad710be3ac18fa8b6164a5690 | refs/heads/master | 2020-09-15T00:18:52.643254 | 2019-11-22T02:26:46 | 2019-11-22T02:26:46 | 223,303,662 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 378 | py | # Generated by Django 2.2.7 on 2019-11-19 04:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('games', '0004_auto_20191117_2142'),
]
operations = [
migrations.AddField(
model_name='cell',
name='value',
field=models.IntegerField(default=0),
),
]
| [
"lardissone@gmail.com"
] | lardissone@gmail.com |
d4dc295b5768bb0563e5e17ef7ffbd1df08b817a | e87e95c0f2c59b01afeb2d4b3d78da3e6e7e93be | /backend/backend/settings.py | 449efbdf91e0218edc6b4c0b32cecad13bd32894 | [] | no_license | ScrollPage/Test-Game | dbaf7efb2a5d752c09e42b01ba157e46a8903ab3 | a19293605751c016d183b654a0ff6f8d763d0aff | refs/heads/master | 2022-11-15T17:44:33.566285 | 2020-07-11T16:19:53 | 2020-07-11T16:19:53 | 278,646,939 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 3,661 | py | """
Django settings for backend project.
Generated by 'django-admin startproject' using Django 2.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'k@5v0r89*ju7!_#cpcd_u_&w081+-az#+%oj+@bi&h%!s-puh&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'account',
'tictactoe',
'search',
'gamification',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'backend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'backend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
REACT_DOMEN = 'http://localhost:3000'
DJANGO_DOMEN = 'http://localhost:8000'
AUTH_USER_MODEL = 'account.Account'
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'reqww00@gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TSL = True
EMAIL_HOST_PASSWORD = 'CFHFYXF228hec;'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True | [
"54814200+reqww@users.noreply.github.com"
] | 54814200+reqww@users.noreply.github.com |
aa693b18b335f055cd06055f996cb848047da2ac | 3c569047f2fb4d76d1ed4e5c9f749c717f13ebec | /doorTest.py | 3a10415c077106f6f6b55c31481a254bc39a33ae | [] | no_license | edb87/coop | 33599ee76f7aa113767acd59b8bbfa9001ba72d5 | 294b645369490772d3c6e8e30fd714fb62400d26 | refs/heads/master | 2021-01-20T13:56:29.655151 | 2017-05-07T15:18:29 | 2017-05-07T15:18:29 | 90,541,303 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 347 | py | from time import sleep
import Adafruit_BBIO.GPIO as GPIO
hallUpSensor = "P8_18"
hallDnSensor = "P8_19"
GPIO.setup(hallDnSensor, GPIO.IN)
GPIO.setup(hallUpSensor, GPIO.IN)
if not GPIO.input(hallDnSensor):
print "Door down!"
else :
print "Door NOT down..."
if not GPIO.input(hallUpSensor):
print "Door up!"
else :
print "Door NOT up..."
| [
"ebeckstrom@gmail.com"
] | ebeckstrom@gmail.com |
26fc8b14b8964e884abdb3033be76bb1fa84a67a | c88420c9abf96c73139da0769f6eddbe6cf732dd | /tests_oval_graph/conftest.py | 30297732c79d5b28d2925ef852b8a3928442c711 | [
"Apache-2.0"
] | permissive | pombredanne/OVAL-visualization-as-graph | 0dcf077c6254e95f3f66ba00a805b5f09d1f21c3 | 64dcb9e14f58e3708022eda55ea3c4d3ec2b7b89 | refs/heads/master | 2023-01-20T09:21:31.215607 | 2022-01-31T17:08:56 | 2022-01-31T17:08:56 | 238,423,157 | 0 | 0 | Apache-2.0 | 2020-02-05T10:25:14 | 2020-02-05T10:25:13 | null | UTF-8 | Python | false | false | 345 | py | import os
from glob import glob
import pytest
@pytest.fixture()
def remove_generated_reports_in_root():
yield
path = os.getcwd()
pattern = os.path.join(
path, "graph-of-xccdf_org.ssgproject.content_rule_package_abrt_removed*")
for item in glob(pattern):
if not os.path.isdir(item):
os.remove(item)
| [
"hony.com@seznam.cz"
] | hony.com@seznam.cz |
925c5a8ce8f7964a1d1f643ae348dd026d002811 | 9a2dba0314e25d57f80c248954ac374014e72e9c | /scripts/new_script.py | 6c9c64e2f3539af37635c078deb13116eac83a29 | [
"MIT"
] | permissive | Shreya869/minor-pro | bfb048ff0652be76e23714fc95c4dabb35af8016 | 06e30e70023c25b264d887820ad5aeec2a6ebb51 | refs/heads/main | 2023-02-11T04:42:32.134331 | 2021-01-15T20:07:33 | 2021-01-15T20:07:33 | 330,000,651 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 981 | py | import pandas as pa
import csv
import statistics as stat
#%%
dataset=pa.read_csv('old_datasets/value_data.csv')
#%%
#selecting the unique field value from the first column
e=dataset.drop_duplicates('Element')['Element']
#%%
#getting unique crops from the dataset
crops=dataset.drop_duplicates('Item')['Item']
crops=list(crops)
#%%
#add crop name to the start of the headings i.e the first column name
e=list(e)
r=['Crop']
r.extend(e)
f=[]
f.append(r)
with open('one.csv','w') as ff:
writer=csv.writer(ff)
writer.writerows(f)
#%%
def insert(l1,row):
for k in range(0,len(row)):
l1[k].append(list(row['Value'])[k])
return l1
e=dataset.drop_duplicates('Element')['Element']
name='one.csv'
with open(name,'a') as ff:
for i in crops:
l1=[[i] for _ in range(10)]
for j in e:
row=dataset.loc[(dataset['Element']==j) & (dataset['Item']==i)]
l1=insert(l1,row)
writer=csv.writer(ff)
writer.writerows(l1)
| [
"noreply@github.com"
] | Shreya869.noreply@github.com |
adb7eb8524a2ca5b0cb525b97d8a07ddf158dabe | 5aedfa32410c58f48d683a71e85bfdd691acc6d5 | /advent_of_code/2016/day03/aoc_day_03_1.py | 38bddb042cecc017445b9d95f02e5ff74cb6cf28 | [
"MIT"
] | permissive | M0nica/advent_of_code | 344e6b4e26acc9c9f72919fef82783c177080e3d | ffa5de75cac7b62acc53a9fc3021820727137264 | refs/heads/master | 2020-09-22T11:59:26.741874 | 2019-11-06T15:01:58 | 2019-11-06T15:01:58 | 225,184,342 | 1 | 1 | MIT | 2019-12-01T15:33:27 | 2019-12-01T15:33:27 | null | UTF-8 | Python | false | false | 469 | py | #!/bin/python3
def squares_with_three_sides(sides):
perimeter = sum(sides)
for side in sides:
if side >= perimeter - side:
return False
return True
if __name__ == '__main__':
counter = 0
with open("aoc_day_03_input.txt", "r") as f:
for line in f:
processed_line = list(map(int, filter(None, line.strip().split(' '))))
counter += squares_with_three_sides(processed_line)
print(counter) | [
"chris.s.cordero@gmail.com"
] | chris.s.cordero@gmail.com |
5da0a11ef51783812520ddf046cae1ad169b1090 | a66ab94dc7e9a86f702174eb64d3a278d452e893 | /set.py | 6e94e283e0b6fec43f5ca938610d165a92732900 | [] | no_license | SamridhiPathak/python-programs | a91a392cbf8db882ce3c01cd081f0e883920992a | 96d599ac273ee0b02123ae0e9320db0f34de3dd7 | refs/heads/master | 2023-04-13T14:57:09.595757 | 2021-04-16T14:48:03 | 2021-04-16T14:48:03 | 358,631,068 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 182 | py | s1={"ria","pathak"}
s2={10,40,50,"ravi"}
print(s2)
for a in s2:
print(a)
s2.add(90)
print(s2)
s2.update([80,100,100])
print(s2)
s2.remove(40)
print(s2)
s3=s1.union(s2)
print(s3)
| [
"samridhipathak5@gmail.com"
] | samridhipathak5@gmail.com |
e801a8a7f5e1e1dd40400c3d1c43623c3b8b59de | c2612dce88769abf7e8fcb25b4703b07fea65bb6 | /4.py | 375ef5b06476cc76b840772ba8f1b621e05992ba | [] | no_license | Ye980226/leetcode_50_problem | c4784ae92325e50190f5b4492d29f6494471ab9b | 9768e6b45e6d1a3ce2f30a84c560382ec324e49f | refs/heads/main | 2023-02-22T01:23:50.102684 | 2021-01-29T11:24:42 | 2021-01-29T11:24:42 | 328,693,732 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 305 | py | class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
nums=nums1+nums2
nums.sort()
if len(nums)%2==0:
median=len(nums)//2
return (nums[median-1]+nums[median])/2
else:
return nums[len(nums)//2] | [
"18955993726@163.com"
] | 18955993726@163.com |
fde7aa4f808c9c5c4468d7ff10477a89b52e06d4 | 488793e256e72cfc99ef4df576e82364747dc41a | /Power.py | 08dfb796d35bfec70824ba1fab3ffb208780ff3d | [] | no_license | RobertH1999/CMPSCI-Projects | 72588a6c62dfd307431c44ff00e12f2136ceaf28 | b022c25e7d04d18e561fa8b6db493816047a80c6 | refs/heads/master | 2021-09-24T15:28:17.459537 | 2018-10-10T23:13:23 | 2018-10-10T23:13:23 | 105,831,609 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 28 | py | def power(value, exp):
| [
"noreply@github.com"
] | RobertH1999.noreply@github.com |
41e4879179f6dec5fc9fca7ace3aa1000f1d3de0 | 580640e18ba218863db529236138e624b44a40e8 | /api/migrations/versions/61fa3cf3732a_.py | afcb55a92fd3a7759e521825610498d9231a1eae | [] | no_license | NatLibFi/Finto-suggestions | 2029612d288382ac469eb9119a4bbb502df519d6 | c6032aebf8fcfd2c3b7c6e2959353f2378c9da0e | refs/heads/master | 2021-06-11T01:12:00.173153 | 2020-03-30T09:06:49 | 2020-03-30T09:06:49 | 136,152,000 | 7 | 1 | null | 2021-01-05T02:26:54 | 2018-06-05T09:17:38 | Vue | UTF-8 | Python | false | false | 737 | py | """Add new field yse_term to suggestion table. Yse_term is used to link suggestion to yse.
Revision ID: 61fa3cf3732a
Revises: 6c8aa3d470ce
Create Date: 2019-02-06 13:44:39.612259
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '61fa3cf3732a'
down_revision = '6c8aa3d470ce'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('suggestions', sa.Column('yse_term', sa.JSON(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('suggestions', 'yse_term')
# ### end Alembic commands ###
| [
"noreply@github.com"
] | NatLibFi.noreply@github.com |
b6e0fa5be2a4f5509e94be2a3035063e1bf778c9 | 90a1c09f8efb4f1e596a24983809693876536176 | /app/db/models/server.py | 5d0a019312f11ab3df5cb4143969653764661b7b | [] | no_license | vlmaksimuk/vscale | ff35ea4f913760fb89905080fd84e63e9eb0b40e | 8e52110971a824102f0d50d550fd908434784101 | refs/heads/main | 2023-03-27T04:18:43.631275 | 2021-03-30T13:41:37 | 2021-03-30T13:54:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,234 | py | from __future__ import annotations
from typing import List
from sqlalchemy import Column, Integer, DateTime, Boolean, String
from sqlalchemy.orm import relationship
from app.db.base_class import Base
from .key import Key
from ...vscale.schemas.vscale_api import (
ServerCreationResponse as Py_ServerCreationResponse,
)
class Server(Base):
id = Column(Integer, primary_key=True, index=True)
status = Column(String(64), comment="Статус сервера")
deleted = Column(
DateTime,
comment="Время удаления сервера",
index=True,
nullable=True,
default=None,
)
active = Column(Boolean, comment="Маркер запуска сервера")
location = Column(String(16), comment="Распроложение сервера")
locked = Column(Boolean, comment="")
hostname = Column(String(255), comment="Наименование хоста")
created = Column(DateTime, comment="Время создания сервера")
made_from = Column(
String(255), comment="Id образа или бэкапа, на основе которого создан сервер"
)
name = Column(String(255), comment="Имя сервера")
ext_ctid = Column(Integer, comment="Идентификатор сервера в vscale.io")
rplan = Column(String(16), comment="Id тарифного плана")
keys = relationship("Key", back_populates="server")
public_address_gateway = Column(
String(64), comment="Публичный гейтвей", nullable=True
)
public_address_netmask = Column(
String(64), comment="Публичная маска сети", nullable=True
)
public_address_address = Column(
String(64), comment="Публичный адрес", nullable=True
)
private_address_gateway = Column(
String(64), comment="Приватный гейтвей", nullable=True
)
private_address_netmask = Column(
String(64), comment="Приватная маска сети", nullable=True
)
private_address_address = Column(
String(64), comment="Приватный адрес", nullable=True
)
@classmethod
def from_vscale_create_response(
cls, server_data: Py_ServerCreationResponse
) -> Server:
"""
Создает объект Server из данных полученных из ответа запроса на создание сервера
:param server_data: ответ запроса на создание сервера
:return: объект Server
"""
data = server_data.dict()
public_address: dict = data.pop("public_address")
private_address: dict = data.pop("private_address")
data["ext_ctid"] = data.pop("ctid")
for key, val in public_address.items():
data[f"public_address_{key}"] = str(val)
for key, val in private_address.items():
data[f"private_address_{key}"] = str(val)
keys: List[dict] = data.pop("keys")
server = cls(**data) # type: ignore
server.keys = [Key.from_vscale_create_response(key) for key in keys]
return server
| [
"v.maksimuk@bsl.dev"
] | v.maksimuk@bsl.dev |
bd62df7ab529c5ae4a7ae5102451ecbd11384454 | 99078b5d47a6b9bb476bdf27cd466a4fb1e78538 | /src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/_validators.py | ddd7a5f8ba52467bbaff76f0d76f957ee9e94b71 | [
"MIT"
] | permissive | enterstudio/azure-cli | 949c54464fbce7ff596665c6bcc3d4aeefe54b53 | b0504c3b634e17f1afc944a9572864a40da6bc18 | refs/heads/master | 2023-07-14T11:09:45.925689 | 2017-02-03T18:26:09 | 2017-02-03T18:26:09 | 81,024,949 | 0 | 0 | NOASSERTION | 2023-07-02T22:24:59 | 2017-02-05T21:53:49 | Python | UTF-8 | Python | false | false | 8,161 | py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import argparse
import base64
import binascii
from datetime import datetime
import re
from azure.mgmt.keyvault import KeyVaultManagementClient
from azure.mgmt.keyvault.models.key_vault_management_client_enums import \
(KeyPermissions, SecretPermissions, CertificatePermissions)
from azure.cli.core.commands.client_factory import get_mgmt_service_client
from azure.cli.core.commands.arm import parse_resource_id
from azure.cli.core.commands.validators import validate_tags
from azure.cli.core._util import CLIError
from azure.keyvault.generated.models.key_vault_client_enums \
import JsonWebKeyOperation
secret_text_encoding_values = ['utf-8', 'utf-16le', 'utf-16be', 'ascii']
secret_binary_encoding_values = ['base64', 'hex']
def _extract_version(item_id):
return item_id.split('/')[-1]
# COMMAND NAMESPACE VALIDATORS
def process_certificate_cancel_namespace(namespace):
namespace.cancellation_requested = True
def process_secret_set_namespace(namespace):
validate_tags(namespace)
content = namespace.value
file_path = namespace.file_path
encoding = namespace.encoding
tags = namespace.tags or {}
use_error = CLIError("incorrect usage: [Required] --value VALUE | --file PATH")
if (content and file_path) or (not content and not file_path):
raise use_error
encoding = encoding or 'utf-8'
if file_path:
if encoding in secret_text_encoding_values:
with open(file_path, 'r') as f:
try:
content = f.read()
except UnicodeDecodeError:
raise CLIError("Unable to decode file '{}' with '{}' encoding.".format(
file_path, encoding))
encoded_str = content
encoded = content.encode(encoding)
decoded = encoded.decode(encoding)
elif encoding == 'base64':
with open(file_path, 'rb') as f:
content = f.read()
try:
encoded = base64.encodebytes(content)
except AttributeError:
encoded = base64.encodestring(content) # pylint: disable=deprecated-method
encoded_str = encoded.decode('utf-8')
decoded = base64.b64decode(encoded_str)
elif encoding == 'hex':
with open(file_path, 'rb') as f:
content = f.read()
encoded = binascii.b2a_hex(content)
encoded_str = encoded.decode('utf-8')
decoded = binascii.unhexlify(encoded_str)
if content != decoded:
raise CLIError("invalid encoding '{}'".format(encoding))
content = encoded_str
tags.update({'file-encoding': encoding})
namespace.tags = tags
namespace.value = content
# PARAMETER NAMESPACE VALIDATORS
def get_attribute_validator(name, attribute_class, create=False):
def validator(ns):
ns_dict = ns.__dict__
enabled = not ns_dict.pop('disabled') if create else ns_dict.pop('enabled') == 'true'
attributes = attribute_class(
enabled,
ns_dict.pop('not_before'),
ns_dict.pop('expires'))
setattr(ns, '{}_attributes'.format(name), attributes)
return validator
def validate_key_import_source(ns):
byok_file = ns.byok_file
pem_file = ns.pem_file
pem_password = ns.pem_password
if (not byok_file and not pem_file) or (byok_file and pem_file):
raise ValueError('supply exactly one: --byok-file, --pem-file')
if byok_file and pem_password:
raise ValueError('--byok-file cannot be used with --pem-password')
if pem_password and not pem_file:
raise ValueError('--pem-password must be used with --pem-file')
def validate_key_ops(ns):
allowed = [x.value.lower() for x in JsonWebKeyOperation]
for p in ns.key_ops or []:
if p not in allowed:
raise ValueError("unrecognized key operation '{}'".format(p))
def validate_key_type(ns):
if ns.destination:
dest_to_type_map = {
'software': 'RSA',
'hsm': 'RSA-HSM'
}
ns.destination = dest_to_type_map[ns.destination]
if ns.destination == 'RSA' and hasattr(ns, 'byok_file') and ns.byok_file:
raise CLIError('BYOK keys are hardware protected. Omit --protection')
def validate_policy_permissions(ns):
key_perms = ns.key_permissions
secret_perms = ns.secret_permissions
cert_perms = ns.certificate_permissions
if not any([key_perms, secret_perms, cert_perms]):
raise argparse.ArgumentError(
None,
'specify at least one: --key-permissions, --secret-permissions, '
'--certificate-permissions')
key_allowed = [x.value for x in KeyPermissions]
secret_allowed = [x.value for x in SecretPermissions]
cert_allowed = [x.value for x in CertificatePermissions]
for p in key_perms or []:
if p not in key_allowed:
raise ValueError("unrecognized key permission '{}'".format(p))
for p in secret_perms or []:
if p not in secret_allowed:
raise ValueError("unrecognized secret permission '{}'".format(p))
for p in cert_perms or []:
if p not in cert_allowed:
raise ValueError("unrecognized cert permission '{}'".format(p))
def validate_principal(ns):
num_set = sum(1 for p in [ns.object_id, ns.spn, ns.upn] if p)
if num_set != 1:
raise argparse.ArgumentError(
None, 'specify exactly one: --object-id, --spn, --upn')
def validate_resource_group_name(ns):
if not ns.resource_group_name:
vault_name = ns.vault_name
client = get_mgmt_service_client(KeyVaultManagementClient).vaults
for vault in client.list():
id_comps = parse_resource_id(vault.id)
if id_comps['name'] == vault_name:
ns.resource_group_name = id_comps['resource_group']
return
raise CLIError(
"The Resource 'Microsoft.KeyVault/vaults/{}'".format(vault_name) + \
" not found within subscription")
def validate_x509_certificate_chain(ns):
def _load_certificate_as_bytes(file_name):
cert_list = []
regex = r'-----BEGIN CERTIFICATE-----([^-]+)-----END CERTIFICATE-----'
with open(file_name, 'r') as f:
cert_data = f.read()
for entry in re.findall(regex, cert_data):
cert_list.append(base64.b64decode(entry.replace('\n', '')))
return cert_list
ns.x509_certificates = _load_certificate_as_bytes(ns.x509_certificates)
# ARGUMENT TYPES
def base64_encoded_certificate_type(string):
""" Loads file and outputs contents as base64 encoded string. """
with open(string, 'rb') as f:
cert_data = f.read()
try:
# for PEM files (including automatic endline conversion for Windows)
cert_data = cert_data.decode('utf-8').replace('\r\n', '\n')
except UnicodeDecodeError:
cert_data = binascii.b2a_base64(cert_data).decode('utf-8')
return cert_data
def datetime_type(string):
""" Validates UTC datettime in accepted format. Examples: 2017-12-31T01:11:59Z,
2017-12-31T01:11Z or 2017-12-31T01Z or 2017-12-31 """
accepted_date_formats = ['%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%MZ',
'%Y-%m-%dT%HZ', '%Y-%m-%d']
for form in accepted_date_formats:
try:
return datetime.strptime(string, form)
except ValueError: # checks next format
pass
raise ValueError("Input '{}' not valid. Valid example: 2000-12-31T12:59:59Z".format(string))
def vault_base_url_type(name):
from azure.cli.core._profile import CLOUD
suffix = CLOUD.suffixes.keyvault_dns
return 'https://{}{}'.format(name, suffix)
| [
"noreply@github.com"
] | enterstudio.noreply@github.com |
558c4e8fc77a378de68de3e0159d6c9081411d0c | 1be4ed08d06d998ebd881bbfbc71869009a8145a | /nobel.py | 83408fdf7b47c7e5e78f2d49c2edfe4874e8eb97 | [] | no_license | sachniv1023/nobelrepo | 6284632ac5c61d118787459cf616b9a7f97f959e | a274dd1a2c18afcbbb5a3d9d8cf2d9ce3142a1b7 | refs/heads/master | 2023-06-21T23:32:44.756488 | 2021-07-28T19:11:46 | 2021-07-28T19:11:46 | 389,779,357 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,953 | py | from flask import Flask, json, render_template, request, redirect, url_for
import os
#create instance of Flask app
app = Flask(__name__)
#decorator
@app.route("/")
def echo_hello():
return "<p>Hello Nobel Prize Homepage - latest !</p>"
@app.route("/all")
def all():
json_url = os.path.join(app.static_folder,"","nobel.json")
data_json = json.load(open(json_url))
#render_template is always looking in templates folder
#return render_template('user_nobel.html',data=data_json)
return json.jsonify({"Nobel Prizes Data":data_json})
@app.route("/<year>", methods = ["GET","POST"])
def nobel_year(year):
json_url = os.path.join(app.static_folder,"","nobel.json")
data_json = json.load(open(json_url))
data = data_json['prizes']
year = request.view_args['year']
if request.method == "GET":
output_data = [x for x in data if x['year']==year]
#render_template is always looking in templates folder
return render_template('user_nobel.html',data=output_data)
#return json.jsonify({"Nobel Prizes Data by year":output_data})
elif request.method == "POST":
category = request.form['category']
id = request.form['id']
firstname = request.form['firstname']
surname = request.form['surname']
motivation = request.form['motivation']
share = request.form['share']
create_row_data= {'year': year, 'category': category, 'laurates': [{'id': id, 'firstname': firstname, 'surname': surname, 'motivation': motivation, 'share': share }]}
print (create_row_data)
filename='./static/nobel.json'
with open(filename,'r+') as file:
file_data = json.load(file)
file_data['prizes'].append(create_row_data)
file.seek(0)
json.dump(file_data, file, indent = 4)
return render_template('user_nobel.html',data=create_row_data)
if __name__ == "__main__":
app.run(debug=True)
| [
"sachniv1023@gmail.com"
] | sachniv1023@gmail.com |
90c1d58f868f907872d48955fb52e985cab10b2d | c4faec674beef1eeda556d0c5204a60100b2bfe8 | /00 pylec/00 samplecode/twspider.py | 0b0e59edd0fd22e3e7fb5ad41c68b9ab3d55cf15 | [
"MIT"
] | permissive | blueicy/Python-achieve | d6f410f57939ed6450f41d4e90974b7395a20bc1 | cbe7a0f898bef5f1d951d69cef0c305a62faaaf8 | refs/heads/master | 2020-04-12T14:27:28.222075 | 2019-01-03T13:40:46 | 2019-01-03T13:40:46 | 162,553,006 | 0 | 0 | MIT | 2018-12-20T10:07:45 | 2018-12-20T08:57:47 | Python | UTF-8 | Python | false | false | 1,975 | py | from urllib.request import urlopen
import urllib.error
import twurl
import json
import sqlite3
import ssl
TWITTER_URL = 'https://api.twitter.com/1.1/friends/list.json'
conn = sqlite3.connect('spider.sqlite')
cur = conn.cursor()
cur.execute('''
CREATE TABLE IF NOT EXISTS Twitter
(name TEXT, retrieved INTEGER, friends INTEGER)''')
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
while True:
acct = input('Enter a Twitter account, or quit: ')
if (acct == 'quit'): break
if (len(acct) < 1):
cur.execute('SELECT name FROM Twitter WHERE retrieved = 0 LIMIT 1')
try:
acct = cur.fetchone()[0]
except:
print('No unretrieved Twitter accounts found')
continue
url = twurl.augment(TWITTER_URL, {'screen_name': acct, 'count': '5'})
print('Retrieving', url)
connection = urlopen(url, context=ctx)
data = connection.read().decode()
headers = dict(connection.getheaders())
print('Remaining', headers['x-rate-limit-remaining'])
js = json.loads(data)
# Debugging
# print json.dumps(js, indent=4)
cur.execute('UPDATE Twitter SET retrieved=1 WHERE name = ?', (acct, ))
countnew = 0
countold = 0
for u in js['users']:
friend = u['screen_name']
print(friend)
cur.execute('SELECT friends FROM Twitter WHERE name = ? LIMIT 1',
(friend, ))
try:
count = cur.fetchone()[0]
cur.execute('UPDATE Twitter SET friends = ? WHERE name = ?',
(count+1, friend))
countold = countold + 1
except:
cur.execute('''INSERT INTO Twitter (name, retrieved, friends)
VALUES (?, 0, 1)''', (friend, ))
countnew = countnew + 1
print('New accounts=', countnew, ' revisited=', countold)
conn.commit()
cur.close()
| [
"mba1@MacBook-Air.local"
] | mba1@MacBook-Air.local |
22b7fb52d07a5c1c4b7a3ae8b025922bce3fccd6 | cbdbb05b91a4463639deefd44169d564773cd1fb | /djangoproj/djangoproj/urls.py | b37249a73b0db9f156fd9c54b59a0984d3a60382 | [] | no_license | blazprog/py3 | e26ef36a485809334b1d5a1688777b12730ebf39 | e15659e5d5a8ced617283f096e82135dc32a8df1 | refs/heads/master | 2020-03-19T20:55:22.304074 | 2018-06-11T12:25:18 | 2018-06-11T12:25:18 | 136,922,662 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 279 | py | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'djangoproj.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| [
"blaz.korosec@mentis.si"
] | blaz.korosec@mentis.si |
f8f7d41c6d7b8cd7ab66ab93d49bfbf94732ddce | 551599f7fe9e25dcff975866c5f96e3bbaed01aa | /testchild.py | 880394b42a3df26730fbb2bd59a6fdbf119070d7 | [] | no_license | ayeshasohail/testrepo | 44afde8775fa0d6beec3d3a4df7c6b316388e91f | baa6276ae67c7b4e17bac8e5bacb87deb17f409b | refs/heads/main | 2023-02-07T13:55:39.866564 | 2020-12-29T05:30:13 | 2020-12-29T05:30:13 | 325,193,301 | 0 | 0 | null | 2020-12-29T05:30:14 | 2020-12-29T05:20:07 | Python | UTF-8 | Python | false | false | 60 | py | ##Add file to the child branch
print(inside child branch)
| [
"noreply@github.com"
] | ayeshasohail.noreply@github.com |
2e74bf30d621cab8f44f17a276f8b431edb8fc82 | 701fb9aa5dc1d542064a26d525da46a4d0df7279 | /Python/DjangoAssignments/portfolio/apps/portfolio_app/views.py | f5ce54737b1a00c5a9b7d3d1820aa70774dbddc7 | [] | no_license | cahrock/DojoAssignment | 4611c6f0cf0bd8170398da3c00fd68f7607d3dcb | 5bd27f6f6ac9532c7cddae27b9bc3448f8d7b1ea | refs/heads/master | 2021-01-19T20:53:49.715577 | 2017-07-25T19:42:43 | 2017-07-25T19:42:43 | 88,570,144 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 454 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'portfolio_app/index.html')
def testimonials(request):
return render(request, 'portfolio_app/testimonials.html')
def about(request):
return render(request, 'portfolio_app/about.html')
def projects(request):
return render(request, 'portfolio_app/projects.html')
| [
"a.mustofa@gmail.com"
] | a.mustofa@gmail.com |
5753a55d0680745aa4502c9861778d315a83e807 | d788440376da3595f220aec43720aeac8716cb93 | /test_subject_matching_untrained_opentapioca.py | 7b1ef30c84982a44d7d34ca01f934b0dace7f496 | [
"Apache-2.0"
] | permissive | napoler/Wikidata2Text | ad2cb71a3402543f032b4ee97d976e607392a0c5 | 722b528451e92b3072bf57260fdb8f0962a89929 | refs/heads/main | 2023-07-22T19:03:23.665843 | 2021-08-28T13:55:50 | 2021-08-28T13:55:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 227 | py | from mapping_estimation import *
input_file_name = 'data/output_common2.csv'
df = pd.read_csv(input_file_name, delimiter='#', dtype=dtypes, usecols=list(dtypes))
evaluate_subject_matching('opentapioca', df) # untrained
| [
"noreply@github.com"
] | napoler.noreply@github.com |
185b80d2c50f32d5cb5f2960d1ede0e9449ad5ef | a5a1e8d2957e4f6d5eeeacd259f2fd2adf04d76b | /HelixStudios.bundle/Contents/Code/__init__.py | 0067cec15c81a11a524b45b050279fe15ea9b628 | [
"MIT"
] | permissive | KobaTwelve/pgma | 4be7b07284c595bc3cece99cc2e4fa10a7d13d45 | 4c36ea4cf9ec9b5259f119417b764514fa383f87 | refs/heads/master | 2021-02-12T02:35:41.175665 | 2020-03-01T01:30:12 | 2020-03-01T01:30:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 17,511 | py | # HelixStudios
# Matches Scenes, Unsearchable Scenes, and DVDs (dvd's not the same)
#| Sk8 Boys.mp4 | 3392.mp4 | HXM087.mp4 |
#All metadata imported, with HD stills (yippee!)
import re, os, platform, urllib
from difflib import SequenceMatcher
#Fix HTTPS errors when connecting to Facebox (neural.vigue.me) and Thumbor CDN (cdn.vigue.me)
import certifi
import requests
PLUGIN_LOG_TITLE = 'Helix Studios' # Log Title
VERSION_NO = '2019.11.03.107'
# Delay used when requesting HTML, may be good to have to prevent being
# banned from the site
REQUEST_DELAY = 0
# URLS
BASE_URL = 'https://www.helixstudios.net%s'
# Example Video Details URL
# https://www.helixstudios.net/video/3437/hosing-him-down.html
BASE_VIDEO_DETAILS_URL = 'https://www.helixstudios.net/video/%s'
BASE_MODEL_DETAILS_URL = 'https://www.helixstudios.net/model/%s/index.html'
# Example Search URL:
# https://www.helixstudios.net/videos/?q=Hosing+Him+Down
BASE_SEARCH_URL = 'https://www.helixstudios.net/videos/?q=%s'
# File names to match for this agent
file_name_pattern = re.compile(Prefs['regex'])
# Example File Name:
# https://media.helixstudios.com/scenes/hx111_scene2/hx111_scene2_member_1080p.mp4
# FILENAME_PATTERN = re.compile("")
# TITLE_PATTERN = re.compile("")
def Start():
HTTP.CacheTime = CACHE_1WEEK
HTTP.Headers['User-agent'] = 'Mozilla/4.0 (compatible; MSIE 8.0; ' \
'Windows NT 6.2; Trident/4.0; SLCC2; .NET CLR 2.0.50727; ' \
'.NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)'
class HelixStudios(Agent.Movies):
name = 'Helix Studios'
languages = [Locale.Language.NoLanguage, Locale.Language.English]
primary_provider = False
fallback_agent = ['com.plexapp.agents.gayporncollector']
contributes_to = ['com.plexapp.agents.cockporn']
def Log(self, message, *args):
if Prefs['debug']:
Log(PLUGIN_LOG_TITLE + ' - ' + message, *args)
def noNegative(self, value):
if(value < 0):
return 0
else:
return value
def intTest(self, s):
try:
int(s)
return int(s)
except ValueError:
return False
def similar(self, a, b):
return SequenceMatcher(None, a, b).ratio()
def search(self, results, media, lang, manual):
self.Log('-----------------------------------------------------------------------')
self.Log('SEARCH CALLED v.%s', VERSION_NO)
self.Log('SEARCH - Platform: %s %s', platform.system(), platform.release())
self.Log('SEARCH - media.title - %s', media.title)
self.Log('SEARCH - media.items[0].parts[0].file - %s', media.items[0].parts[0].file)
self.Log('SEARCH - media.primary_metadata.title - %s', media.primary_metadata.title)
self.Log('SEARCH - media.items - %s', media.items)
self.Log('SEARCH - media.filename - %s', media.filename)
self.Log('SEARCH - lang - %s', lang)
self.Log('SEARCH - manual - %s', manual)
self.Log('SEARCH - Prefs->cover - %s', Prefs['cover'])
self.Log('SEARCH - Prefs->folders - %s', Prefs['folders'])
self.Log('SEARCH - Prefs->regex - %s', Prefs['regex'])
if not media.items[0].parts[0].file:
return
path_and_file = media.items[0].parts[0].file.lower()
self.Log('SEARCH - File Path: %s', path_and_file)
(file_dir, basename) = os.path.split(os.path.splitext(path_and_file)[0])
final_dir = os.path.split(file_dir)[1]
self.Log('SEARCH - Enclosing Folder: %s', final_dir)
if Prefs['folders'] != "*":
folder_list = re.split(',\s*', Prefs['folders'].lower())
if final_dir not in folder_list:
self.Log('SEARCH - Skipping %s because the folder %s is not in the acceptable folders list: %s', basename, final_dir, ','.join(folder_list))
return
m = file_name_pattern.search(basename)
if not m:
self.Log('SEARCH - Skipping %s because the file name is not in the expected format.', basename)
return
self.Log('SEARCH - File Name: %s', basename)
groups = m.groupdict()
clip_name = groups['clip_name']
movie_url_name = re.sub('\s+', '+', clip_name)
if "hxm" in basename:
#DVD release, use special indexer
movie_url_name = movie_url_name.upper()
video_url = "/movie/" + movie_url_name + "/index.html"
self.Log('SEARCH - DIRECT DVD MATCH: %s', video_url);
self.rating = 5
html = HTML.ElementFromURL("https://www.helixstudios.net" + video_url, sleep=REQUEST_DELAY)
video_title = html.xpath('//*[@id="rightcolumn"]/div/div/h3/text()')[0]
results.Append(MetadataSearchResult(id = video_url, name = video_title, score = 100, lang = lang))
return
if basename.isdigit():
#add direct video match & skip search
video_url = "/video/" + movie_url_name + "/index.html"
self.Log('SEARCH - DIRECT SCENE MATCH: %s', video_url);
self.rating = 5
html = HTML.ElementFromURL("https://www.helixstudios.net" + video_url, sleep=REQUEST_DELAY)
video_title = html.xpath('//div[@class="scene-title"]/span/text()')[0]
results.Append(MetadataSearchResult(id = video_url, name = video_title, score = 100, lang = lang))
return
movie_url = BASE_SEARCH_URL % movie_url_name
search_query_raw = list()
for piece in clip_name.split(' '):
if re.search('^[0-9A-Za-z]*$', piece.replace('!', '')) is not None:
search_query_raw.append(piece)
self.Log('SEARCH - Video URL: %s', movie_url)
html = HTML.ElementFromURL(movie_url, sleep=REQUEST_DELAY)
search_results = html.xpath('//*[@class="video-gallery"]/li')
score=10
# Enumerate the search results looking for an exact match. The hope is that by eliminating special character words from the title and searching the remainder that we will get the expected video in the results.
if search_results:
for result in search_results:
video_title = result.find('a').find("img").get("alt")
video_title = re.sub("[\:\?\|]", '', video_title)
video_title = re.sub("\s{2,4}", ' ', video_title)
video_title = video_title.rstrip(' ')
self.Log('SEARCH - video title percentage: %s', self.similar(video_title.lower(), clip_name.lower()))
self.Log('SEARCH - video title: %s', video_title)
# Check the alt tag which includes the full title with special characters against the video title. If we match we nominate the result as the proper metadata. If we don't match we reply with a low score.
#if video_title.lower() == clip_name.lower():
if self.similar(video_title.lower(), clip_name.lower()) > 0.90:
video_url=result.find('a').get('href')
self.Log('SEARCH - video url: %s', video_url)
self.rating = result.find('.//*[@class="current-rating"]').text.strip('Currently ').strip('/5 Stars')
self.Log('SEARCH - rating: %s', self.rating)
self.Log('SEARCH - Exact Match "' + clip_name.lower() + '" == "%s"', video_title.lower())
results.Append(MetadataSearchResult(id = video_url, name = video_title, score = 100, lang = lang))
return
else:
self.Log('SEARCH - Title not found "' + clip_name.lower() + '" != "%s"', video_title.lower())
score=score-1
results.Append(MetadataSearchResult(id = '', name = media.filename, score = score, lang = lang))
else:
search_query="+".join(search_query_raw[-2:])
self.Log('SEARCH - Search Query: %s', search_query)
html=HTML.ElementFromURL(BASE_SEARCH_URL % search_query, sleep=REQUEST_DELAY)
search_results=html.xpath('//*[@class="video-gallery"]/li')
if search_results:
for result in search_results:
video_title = result.find('a').find("img").get("alt")
video_title = re.sub("[\:\?\|]", '', video_title)
video_title = video_title.rstrip(' ')
self.Log('SEARCH - video title: %s', video_title)
if video_title.lower() == clip_name.lower():
video_url=result.find('a').get('href')
self.Log('SEARCH - video url: %s', video_url)
self.rating = result.find('.//*[@class="current-rating"]').text.strip('Currently ').strip('/5 Stars')
self.Log('SEARCH - rating: %s', self.rating)
self.Log('SEARCH - Exact Match "' + clip_name.lower() + '" == "%s"', video_title.lower())
results.Append(MetadataSearchResult(id = video_url, name = video_title, score = 100, lang = lang))
return
else:
self.Log('SEARCH - Title not found "' + clip_name.lower() + '" != "%s"', video_title.lower())
score=score-1
results.Append(MetadataSearchResult(id = '', name = media.filename, score = score, lang = lang))
else:
search_query="+".join(search_query_raw[:2])
self.Log('SEARCH - Search Query: %s', search_query)
html=HTML.ElementFromURL(BASE_SEARCH_URL % search_query, sleep=REQUEST_DELAY)
search_results=html.xpath('//*[@class="video-gallery"]/li')
if search_results:
for result in search_results:
video_title=result.find('a').find("img").get("alt")
video_title = re.sub("[\:\?\|]", '', video_title)
video_title = video_title.rstrip(' ')
self.Log('SEARCH - video title: %s', video_title)
if video_title.lower() == clip_name.lower():
video_url=result.find('a').get('href')
self.Log('SEARCH - video url: %s', video_url)
self.rating = result.find('.//*[@class="current-rating"]').text.strip('Currently ').strip('/5 Stars')
self.Log('SEARCH - rating: %s', self.rating)
self.Log('SEARCH - Exact Match "' + clip_name.lower() + '" == "%s"', video_title.lower())
results.Append(MetadataSearchResult(id = video_url, name = video_title, score = 100, lang = lang))
return
else:
self.Log('SEARCH - Title not found "' + clip_name.lower() + '" != "%s"', video_title.lower())
results.Append(MetadataSearchResult(id = '', name = media.filename, score = 1, lang = lang))
else:
score=1
self.Log('SEARCH - Title not found "' + clip_name.lower() + '" != "%s"', video_title.lower())
return
def update(self, metadata, media, lang, force=False):
self.Log('UPDATE CALLED')
if not media.items[0].parts[0].file:
return
file_path = media.items[0].parts[0].file
self.Log('UPDATE - File Path: %s', file_path)
self.Log('UPDATE - Video URL: %s', metadata.id)
url = BASE_URL % metadata.id
# Fetch HTML
html = HTML.ElementFromURL(url, sleep=REQUEST_DELAY)
# Set tagline to URL
metadata.tagline = url
valid_image_names = list()
valid_art_names = list()
if "HXM" in url:
#movie logic
#movie title
metadata.title = html.xpath('//*[@id="rightcolumn"]/div/div/h3/text()')[0]
#Movie poster
mov_cover_lores = html.xpath('//div[@id="rightcolumn"]/a/img')[0].get("src")
mov_cover_hires = mov_cover_lores.replace("320w","1920w")
valid_image_names.append(mov_cover_hires)
metadata.posters[mov_cover_hires]=Proxy.Media(HTTP.Request(mov_cover_hires), sort_order = 1)
#Background art
mov_id = str(filter(str.isdigit, url))
art_url = "https://cdn.helixstudios.com/media/titles/hxm" + mov_id + "_trailer.jpg";
valid_art_names.append(art_url)
metadata.art[art_url] = Proxy.Media(HTTP.Request(art_url), sort_order=1)
metadata.art.validate_keys(valid_art_names)
#Description
metadata.summary = html.xpath("//p[@class='description']/text()")[0]
#Release date
raw_date = html.xpath('//*[@id="rightcolumn"]/div/div/div[1]/text()')[0]
metadata.originally_available_at = Datetime.ParseDate(raw_date).date()
metadata.year = metadata.originally_available_at.year
#Cast images
metadata.roles.clear()
rolethumbs = list();
headshot_list = html.xpath('//ul[@id="scene-models"]/li/a/img')
for headshot_obj in headshot_list:
headshot_url_lo_res = headshot_obj.get("src")
headshot_url_hi_res = headshot_url_lo_res.replace("150w","480w")
result = requests.post('https://neural.vigue.me/facebox/check', json={"url": headshot_url_hi_res}, verify=certifi.where())
Log(result.json()["facesCount"])
if result.json()["facesCount"] == 1:
box = result.json()["faces"][0]["rect"]
cropped_headshot = "https://cdn.vigue.me/unsafe/" + str(self.noNegative(box["left"] - 100)) + "x" + str(self.noNegative(box["top"] - 100)) + ":" + str(self.noNegative((box["left"]+box["width"])+100)) + "x" + str(self.noNegative((box["top"]+box["height"])+100)) + "/" + headshot_url_hi_res
else:
cropped_headshot = headshot_url_hi_res
rolethumbs.append(cropped_headshot)
index = 0
#Cast names
cast_text_list = html.xpath('//ul[@id="scene-models"]/li/a/div/text()')
for cast in cast_text_list:
cname = cast.strip()
if (len(cname) > 0):
role = metadata.roles.new()
role.name = cname
role.photo = rolethumbs[index]
index += 1
metadata.posters.validate_keys(valid_image_names)
metadata.art.validate_keys(valid_art_names)
metadata.collections.add("Helix Studios")
metadata.content_rating = 'X'
metadata.studio = "Helix Studios"
return
video_title = html.xpath('//div[@class="scene-title"]/span/text()')[0]
self.Log('UPDATE - video_title: "%s"', video_title)
metadata.title = video_title
# External https://cdn.helixstudios.com/img/300h/media/stills/hx109_scene52_001.jpg
# Member https://cdn.helixstudios.com/img/1920w/media/stills/hx109_scene52_001.jpg
i = 0
video_image_list = html.xpath('//*[@id="scene-just-gallery"]/a/img')
# self.Log('UPDATE - video_image_list: "%s"', video_image_list)
try:
coverPrefs = Prefs['cover']
for image in video_image_list:
if i <= (self.intTest(coverPrefs)-1) or coverPrefs == "all available":
i = i + 1
thumb_url = image.get('src')
poster_url = thumb_url.replace('300h', '1920w')
valid_image_names.append(poster_url)
if poster_url not in metadata.posters:
try:
metadata.posters[poster_url]=Proxy.Preview(HTTP.Request(thumb_url), sort_order = i)
except Exception as e:
pass
except Exception as e:
self.Log('UPDATE - Error getting posters: %s', e)
pass
#Try to get scene background art
try:
bg_image = html.xpath('//*[@id="container"]/div[3]/img')[0].get("src")
valid_art_names.append(bg_image)
metadata.art[bg_image] = Proxy.Media(HTTP.Request(bg_image), sort_order=1)
self.Log("UPDATE- Art: %s", bg_image)
except Exception as e:
self.Log('UPDATE - Error getting art: %s', e)
pass
# Try to get description text
try:
raw_about_text=html.xpath('//*[@id="main"]/div[1]/div[1]/div[2]/table/tr/td/p')
self.Log('UPDATE - About Text - RAW %s', raw_about_text)
about_text=' '.join(str(x.text_content().strip()) for x in raw_about_text)
metadata.summary=about_text
except Exception as e:
self.Log('UPDATE - Error getting description text: %s', e)
pass
# Try to get release date
try:
release_date=html.xpath('//*[@id="main"]/div[1]/div[1]/div[2]/table/tr[1]/td[1]/text()')[1].strip()
self.Log('UPDATE - Release Date - New: %s', release_date)
metadata.originally_available_at = Datetime.ParseDate(release_date).date()
metadata.year = metadata.originally_available_at.year
except Exception as e:
self.Log('UPDATE - Error getting release date: %s', e)
pass
# Try to get and process the video cast
metadata.roles.clear()
rolethumbs = list();
cast_list = html.xpath('//td/a[contains(@href,"model")]')
for cast_obj in cast_list:
model_href = BASE_URL % cast_obj.get('href')
model_page = HTML.ElementFromURL(model_href, sleep=REQUEST_DELAY)
model_headshot_lo_res = model_page.xpath('//div[@id="modelHeadshot"]/img')[0].get('src')
headshot_url_hi_res = model_headshot_lo_res.replace("320w","320w")
#Ask facebox to query image for face bounding boxes
Log(headshot_url_hi_res);
result = requests.post('https://neural.vigue.me/facebox/check', json={"url": headshot_url_hi_res}, verify=certifi.where())
Log(result.json()["facesCount"])
if result.json()["facesCount"] == 1:
box = result.json()["faces"][0]["rect"]
cropped_headshot = "https://cdn.vigue.me/unsafe/" + str(abs(box["left"] - 50)) + "x" + str(abs(box["top"] - 50)) + ":" + str(abs((box["left"]+box["width"])+50)) + "x" + str(abs((box["top"]+box["height"])+50)) + "/" + headshot_url_hi_res
else:
cropped_headshot = headshot_url_hi_res
#Create new image url from Thumbor CDN with facial bounding box
self.Log("UPDATE - Cropped headshot: %s", cropped_headshot)
rolethumbs.append(cropped_headshot)
index = 0
htmlcast = html.xpath('//td/a[contains(@href,"model")]/text()')
for cast in htmlcast:
cname = cast.strip()
if (len(cname) > 0):
role = metadata.roles.new()
role.name = cname
role.photo = rolethumbs[index]
index += 1
# Try to get and process the video genres
try:
metadata.genres.clear()
genres = html.xpath('//*[@id="main"]/div[1]/div[1]/div[2]/table/tr[4]/td/a/text()')
self.Log('UPDATE - video_genres: "%s"', genres)
for genre in genres:
genre = genre.strip()
if (len(genre) > 0):
metadata.genres.add(genre)
except Exception as e:
self.Log('UPDATE - Error getting video genres: %s', e)
pass
metadata.posters.validate_keys(valid_image_names)
metadata.art.validate_keys(valid_art_names)
metadata.rating = float(self.rating)*2
metadata.collections.add("Helix Studios")
metadata.content_rating = 'X'
metadata.title = video_title
metadata.studio = "Helix Studios"
| [
"acvigue@me.com"
] | acvigue@me.com |
7607199a480742182d3f45fef42297b97f7b2389 | e27333261b8e579564016c71d2061cc33972a8b8 | /.history/api/UnigramLanguageModelImplementation_20210809164353.py | 67ed4d1f068dd2d9a970c478e1d7c34e0ffdf7d3 | [] | no_license | Dustyik/NewsTweet_InformationRetrieval | 882e63dd20bc9101cbf48afa6c3302febf1989b1 | d9a6d92b51c288f5bcd21ea1cc54772910fa58f7 | refs/heads/master | 2023-07-01T09:12:53.215563 | 2021-08-12T08:28:33 | 2021-08-12T08:28:33 | 382,780,359 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,899 | py | import math
from IPython.display import display
from BM25implementation import QueryParsers
ALPHA = 0.75
NORMALIZE_PROBABILITY = True
class UnigramLanguageModel:
def __init__(self, tweets_data): #tweets is a pandas dataframe
self.tweets_data = tweets_data
self.wordsCollectionFrequencyDictionary = self.create_words_frequency_dict(tweets_data)
def create_words_frequency_dict(self, tweets_data, collection = True):
word_frequency_dictionary = {}
if collection:
tweets = tweets_data.clean_text.tolist()
for sentence in tweets:
sentence_list = list(sentence.split(" "))
for word in sentence_list:
if word in word_frequency_dictionary:
word_frequency_dictionary[word] += 1
else:
word_frequency_dictionary[word] = 1
else:
for word in tweets_data:
if word in word_frequency_dictionary:
word_frequency_dictionary[word] += 1
else:
word_frequency_dictionary[word] = 1
return word_frequency_dictionary
def calculate_total_no_of_words(self, wordsCollectionFrequencyDictionary):
values = wordsCollectionFrequencyDictionary.values()
total = sum(values)
return values
def calculate_unigram_probability(self, word: str, wordCollectionFrequencyDictionary):
totalNumberOfWords = self.calculate_total_no_of_words(wordCollectionFrequencyDictionary)
value = wordCollectionFrequencyDictionary[word]/totalNumberOfWords
return value
def calculate_interpolated_sentence_probability(self, querySentence, document, alpha=ALPHA, normalize_probability=NORMALIZE_PROBABILITY):
querySentenceList = QueryParsers(querySentence)
print (querySentenceList)
return
total_score = 1
list_of_strings = list(document.split(" "))
print (list_of_strings)
documentWordFrequencyDictionary = self.create_words_frequency_dict(list_of_strings, collection = False)
for word in querySentence:
score_of_word = alpha*(self.calculate_unigram_probability(word, documentWordFrequencyDictionary)) + (1 - alpha)*(self.calculate_unigram_probability(word, self.wordsCollectionFrequencyDictionary))
total_score *= score_of_word
if normalize_probability == True:
return total_score
else:
return (math.log(total_score)/math.log(2))
def getQueryLikelihoodModelScore(self, querySentence:list):
self.tweets_data["QueryLikelihoodModelScore"] = self.tweets_data.apply(lambda row: self.calculate_interpolated_sentence_probability(querySentence, row.clean_text), axis = 1)
#display(self.tweets_data)
return
| [
"chiayik_tan@mymail.sutd.edu.sg"
] | chiayik_tan@mymail.sutd.edu.sg |
594d38fa5e7c8b9c128496097f1f95439d847b5d | 81c395850e2c2e853d452d163ac5a81b99c73e3f | /Dotest2.py | a779c55f37f3807b2c97c1ab878a68b9aec70414 | [] | no_license | zyywinner123/python | 1caf82be5b6fd5c8c75b2d351efe871933f9f1e8 | a6c5e312bd4dde8b7a2e0a248cad2ab67c7dc4cf | refs/heads/master | 2020-04-03T01:45:22.644317 | 2020-03-24T02:59:31 | 2020-03-24T02:59:31 | 154,938,691 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,525 | py |
# coding:utf8
import os
import sys
import cv2
import numpy as np
import tensorflow as tf
sys.path.append("..")
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
from flask import Flask , make_response, request,json
class TOD(object):
def __init__(self):
self.MODEL_NAME= 'E:\\111111\herpesV1\com.test\graph'
# Path to frozen detection graph. This is the actual model that is used for the object detection.
self.PATH_TO_CKPT = self.MODEL_NAME + '/frozen_inference_graph.pb'
# List of the strings that is used to add correct label for each box.
self.PATH_TO_LABELS = os.path.join('E:\\111111\herpesV1\com.test\data', 'herpes_label_map.pbtxt')
self.NUM_CLASSES = 1
self.detection_graph = self._load_model()
self.category_index = self._load_label_map()
def _load_model(self):
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(self.PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
return detection_graph
def _load_label_map(self):
label_map = label_map_util.load_labelmap(self.PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=self.NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)
return category_index
def detect(self, image):
with self.detection_graph.as_default():
with tf.Session(graph=self.detection_graph) as sess:
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image, axis=0)
image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected.
boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
classes = self.detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = self.detection_graph.get_tensor_by_name('num_detections:0')
# Actual detection.
(boxes, scores, classes, num_detections) = sess.run(
[boxes, scores, classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
image,
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
self.category_index,
use_normalized_coordinates=True,
line_thickness=8)
print(np.squeeze(scores)[0]) # 第一个检测区域的识别分数,>0.5可判断为异常
return np.squeeze(scores)[0]
# cv2.namedWindow("detection", cv2.WINDOW_NORMAL)
# cv2.imshow("detection", image)
# cv2.waitKey(0)
app = Flask(__name__)
@app.route('/upload', methods=['POST', 'GET'])
def file_upload():
print(request.files)
print(request.form)
print(request.args)
print(request.values)
print(request.values.get('asda'))
print(request.values.get('aa'))
f = request.files['skFile']
f.save("e://flask//"+f.filename);
# image = Image.open(f.filepath)
image = cv2.imread("e://flask//"+f.filename)
detecotr = TOD()
result = detecotr.detect(image)
return '计算的值 ' + str(result)
user = User('bbb', 456)
response = make_response(json.dumps(user, default=lambda obj: obj.__dict__, sort_keys=True, indent=4))
response.headers['Content-Type'] = 'application/json'
return response
if __name__ == '__main__':
app.run()
# if __name__ == '__main__':
# image = cv2.imread("E:\\111111\herpesV1\com.test\\testimage\pi.jpg")
# detecotr = TOD()
# detecotr.detect(image)
| [
"574187554@qq.com"
] | 574187554@qq.com |
4267cf89e7b07731e078fee2a40119beef5a98c1 | 04df47fc60e16d3df1fdc9a19c2630b6c587c021 | /第10套/简单应用题/10-44.demo.py | 6d9b0a3fac9c9748f8b16a45c893b7b4b971d40b | [] | no_license | fxw97/NCRE2python | e7f464cf842bdb2919db55225b1db69e59acb947 | 2c412e77447053ddd4ee7179d84a0eed1716255b | refs/heads/main | 2023-08-02T21:18:09.168977 | 2021-09-24T05:29:45 | 2021-09-24T05:29:45 | 407,850,013 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 186 | py | for i in range(0,4):
for j in range(0,4-i):
print(' ',end='')
print('*'*i)
for i in range(0,4):
for k in range(0,i):
print(' ', end = '')
print('*'*(4-i)) | [
"1550505935@qq.com"
] | 1550505935@qq.com |
d8f7d5c44d24c984e5949f45384627d0098dc78c | fa04f3cb23367d5bb0255170dbbff0f1697b16fa | /dymos/test/test_upgrade_guide.py | 81923054a49b06cd0ea2a5a306adf26d3cec1537 | [
"Apache-2.0"
] | permissive | johnjasa/dymos | 47895b23524d0bcdf5942a483a214aacec90903a | b6ecb8a24903271ba4681e3bd7471b79e5470e14 | refs/heads/master | 2023-08-28T16:33:16.414142 | 2023-03-07T23:00:44 | 2023-03-07T23:00:44 | 173,784,047 | 0 | 0 | Apache-2.0 | 2019-03-04T16:47:21 | 2019-03-04T16:47:20 | null | UTF-8 | Python | false | false | 34,041 | py | import os
import unittest
import openmdao.api as om
import dymos as dm
from openmdao.utils.assert_utils import assert_near_equal
from openmdao.utils.testing_utils import use_tempdirs, require_pyoptsparse
@use_tempdirs
class TestUpgrade_0_16_0(unittest.TestCase):
@require_pyoptsparse(optimizer='SLSQP')
def test_parameters(self):
"""
# upgrade_doc: begin set_val
p.set_val('traj.phase0.design_parameters:thrust', 2.1, units='MN')
# upgrade_doc: end set_val
# upgrade_doc: begin parameter_timeseries
thrust = p.get_val('traj.phase0.timeseries.design_parameters:thrust')
# upgrade_doc: end parameter_timeseries
"""
import numpy as np
import openmdao.api as om
import dymos as dm
#
# Setup and solve the optimal control problem
#
p = om.Problem(model=om.Group())
p.driver = om.pyOptSparseDriver()
p.driver.declare_coloring(tol=1.0E-12)
from dymos.examples.ssto.launch_vehicle_ode import LaunchVehicleODE
#
# Initialize our Trajectory and Phase
#
traj = dm.Trajectory()
phase = dm.Phase(ode_class=LaunchVehicleODE,
transcription=dm.GaussLobatto(num_segments=12, order=3, compressed=False))
traj.add_phase('phase0', phase)
p.model.add_subsystem('traj', traj)
#
# Set the options for the variables
#
phase.set_time_options(fix_initial=True, duration_bounds=(10, 500))
phase.add_state('x', fix_initial=True, ref=1.0E5, defect_ref=10000.0,
rate_source='xdot')
phase.add_state('y', fix_initial=True, ref=1.0E5, defect_ref=10000.0,
rate_source='ydot')
phase.add_state('vx', fix_initial=True, ref=1.0E3, defect_ref=1000.0,
rate_source='vxdot')
phase.add_state('vy', fix_initial=True, ref=1.0E3, defect_ref=1000.0,
rate_source='vydot')
phase.add_state('m', fix_initial=True, ref=1.0E3, defect_ref=100.0,
rate_source='mdot')
phase.add_control('theta', units='rad', lower=-1.57, upper=1.57)
phase.add_parameter('thrust', units='N', opt=False, val=2100000.0)
#
# Set the options for our constraints and objective
#
phase.add_boundary_constraint('y', loc='final', equals=1.85E5, linear=True)
phase.add_boundary_constraint('vx', loc='final', equals=7796.6961)
phase.add_boundary_constraint('vy', loc='final', equals=0)
phase.add_objective('time', loc='final', scaler=0.01)
p.model.linear_solver = om.DirectSolver()
#
# Setup and set initial values
#
p.setup(check=True)
p.set_val('traj.phase0.t_initial', 0.0)
p.set_val('traj.phase0.t_duration', 150.0)
p.set_val('traj.phase0.states:x', phase.interpolate(ys=[0, 1.15E5], nodes='state_input'))
p.set_val('traj.phase0.states:y', phase.interpolate(ys=[0, 1.85E5], nodes='state_input'))
p.set_val('traj.phase0.states:vx', phase.interpolate(ys=[0, 7796.6961], nodes='state_input'))
p.set_val('traj.phase0.states:vy', phase.interpolate(ys=[1.0E-6, 0], nodes='state_input'))
p.set_val('traj.phase0.states:m', phase.interpolate(ys=[117000, 1163], nodes='state_input'))
p.set_val('traj.phase0.controls:theta', phase.interpolate(ys=[1.5, -0.76], nodes='control_input'))
# upgrade_doc: begin set_val
p.set_val('traj.phase0.parameters:thrust', 2.1, units='MN')
# upgrade_doc: end set_val
#
# Solve the Problem
#
dm.run_problem(p)
#
# Check the results.
#
assert_near_equal(p.get_val('traj.phase0.timeseries.time')[-1], 143, tolerance=0.05)
assert_near_equal(p.get_val('traj.phase0.timeseries.states:y')[-1], 1.85E5, 1e-4)
assert_near_equal(p.get_val('traj.phase0.timeseries.states:vx')[-1], 7796.6961, 1e-4)
assert_near_equal(p.get_val('traj.phase0.timeseries.states:vy')[-1], 0, 1e-4)
# upgrade_doc: begin parameter_timeseries
thrust = p.get_val('traj.phase0.timeseries.parameters:thrust')
# upgrade_doc: end parameter_timeseries
nn = phase.options['transcription'].grid_data.num_nodes
assert_near_equal(thrust, 2.1E6 * np.ones([nn, 1]))
def test_parameter_no_timeseries(self):
import openmdao.api as om
import dymos as dm
from dymos.examples.brachistochrone.brachistochrone_ode import BrachistochroneODE
p = om.Problem(model=om.Group())
p.driver = om.ScipyOptimizeDriver()
p.driver.declare_coloring()
phase = dm.Phase(ode_class=BrachistochroneODE,
transcription=dm.GaussLobatto(num_segments=8, order=3, compressed=True))
p.model.add_subsystem('phase0', phase)
phase.set_time_options(fix_initial=True, duration_bounds=(.5, 10))
phase.add_state('x', fix_initial=True, fix_final=True, solve_segments=False)
phase.add_state('y', fix_initial=True, fix_final=True, solve_segments=False)
phase.add_state('v', fix_initial=True, fix_final=False, solve_segments=False)
phase.add_control('theta', continuity=True, rate_continuity=True, opt=True,
units='deg', lower=0.01, upper=179.9, ref=1, ref0=0)
# upgrade_doc: begin parameter_no_timeseries
phase.add_parameter('g', opt=False, units='m/s**2', include_timeseries=False)
# upgrade_doc: end parameter_no_timeseries
# Minimize time at the end of the phase
phase.add_objective('time_phase', loc='final', scaler=10)
p.model.linear_solver = om.DirectSolver()
p.setup(check=True)
p['phase0.t_initial'] = 0.0
p['phase0.t_duration'] = 2.0
p['phase0.states:x'] = phase.interpolate(ys=[0, 10], nodes='state_input')
p['phase0.states:y'] = phase.interpolate(ys=[10, 5], nodes='state_input')
p['phase0.states:v'] = phase.interpolate(ys=[0, 9.9], nodes='state_input')
p['phase0.controls:theta'] = phase.interpolate(ys=[5, 100], nodes='control_input')
p['phase0.parameters:g'] = 9.80665
p.run_driver()
with self.assertRaises(KeyError):
p.get_val('phase0.timeseries.parameters:g}')
def test_simplified_ode_timeseries_output(self):
"""
# upgrade_doc: begin simplified_ode_output_timeseries
phase.add_timeseries_output('tas_comp.TAS', shape=(1,), units='m/s')
# upgrade_doc: end simplified_ode_output_timeseries
"""
import openmdao.api as om
import dymos as dm
from dymos.examples.aircraft_steady_flight.aircraft_ode import AircraftODE
p = om.Problem(model=om.Group())
p.driver = om.ScipyOptimizeDriver()
p.driver.declare_coloring()
transcription = dm.GaussLobatto(num_segments=1,
order=13,
compressed=False)
phase = dm.Phase(ode_class=AircraftODE, transcription=transcription)
p.model.add_subsystem('phase0', phase)
# Pass Reference Area from an external source
assumptions = p.model.add_subsystem('assumptions', om.IndepVarComp())
assumptions.add_output('S', val=427.8, units='m**2')
assumptions.add_output('mass_empty', val=1.0, units='kg')
assumptions.add_output('mass_payload', val=1.0, units='kg')
phase.set_time_options(fix_initial=True,
duration_bounds=(3600, 3600),
duration_ref=3600)
phase.set_time_options(fix_initial=True,
duration_bounds=(3600, 3600),
duration_ref=3600)
phase.add_state('range', units='km', fix_initial=True, fix_final=False, scaler=0.01,
rate_source='range_rate_comp.dXdt:range',
defect_scaler=0.01)
phase.add_state('mass_fuel', units='kg', fix_final=True, upper=20000.0, lower=0.0,
rate_source='propulsion.dXdt:mass_fuel',
scaler=1.0E-4, defect_scaler=1.0E-2)
phase.add_state('alt',
rate_source='climb_rate',
units='km', fix_initial=True)
phase.add_control('mach', targets=['tas_comp.mach', 'aero.mach'], units=None, opt=False)
phase.add_control('climb_rate', targets=['gam_comp.climb_rate'], units='m/s', opt=False)
phase.add_parameter('S',
targets=['aero.S', 'flight_equilibrium.S', 'propulsion.S'],
units='m**2')
phase.add_parameter('mass_empty', targets=['mass_comp.mass_empty'], units='kg')
phase.add_parameter('mass_payload', targets=['mass_comp.mass_payload'], units='kg')
phase.add_path_constraint('propulsion.tau', lower=0.01, upper=1.0, shape=(1,))
# upgrade_doc: begin simplified_ode_output_timeseries
phase.add_timeseries_output('tas_comp.TAS')
# upgrade_doc: end simplified_ode_output_timeseries
p.model.connect('assumptions.S', 'phase0.parameters:S')
p.model.connect('assumptions.mass_empty', 'phase0.parameters:mass_empty')
p.model.connect('assumptions.mass_payload', 'phase0.parameters:mass_payload')
phase.add_objective('time', loc='final', ref=3600)
p.model.linear_solver = om.DirectSolver()
p.setup()
p['phase0.t_initial'] = 0.0
p['phase0.t_duration'] = 1.515132 * 3600.0
p['phase0.states:range'] = phase.interpolate(ys=(0, 1296.4), nodes='state_input')
p['phase0.states:mass_fuel'] = phase.interpolate(ys=(12236.594555, 0), nodes='state_input')
p['phase0.states:alt'] = 5.0
p['phase0.controls:mach'] = 0.8
p['phase0.controls:climb_rate'] = 0.0
p['assumptions.S'] = 427.8
p['assumptions.mass_empty'] = 0.15E6
p['assumptions.mass_payload'] = 84.02869 * 400
dm.run_problem(p)
time = p.get_val('phase0.timeseries.time')
tas = p.get_val('phase0.timeseries.TAS', units='km/s')
range = p.get_val('phase0.timeseries.states:range')
assert_near_equal(range, tas*time, tolerance=1.0E-4)
exp_out = phase.simulate()
time = exp_out.get_val('phase0.timeseries.time')
tas = exp_out.get_val('phase0.timeseries.TAS', units='km/s')
range = exp_out.get_val('phase0.timeseries.states:range')
assert_near_equal(range, tas*time, tolerance=1.0E-4)
@require_pyoptsparse(optimizer='SLSQP')
def test_glob_timeseries_outputs(self):
"""
# upgrade_doc: begin glob_timeseries_outputs
phase.add_timeseries_output('aero.mach', shape=(1,), units=None)
phase.add_timeseries_output('aero.CD0', shape=(1,), units=None)
phase.add_timeseries_output('aero.kappa', shape=(1,), units=None)
phase.add_timeseries_output('aero.CLa', shape=(1,), units=None)
phase.add_timeseries_output('aero.CL', shape=(1,), units=None)
phase.add_timeseries_output('aero.CD', shape=(1,), units=None)
phase.add_timeseries_output('aero.q', shape=(1,), units='N/m**2')
phase.add_timeseries_output('aero.f_lift', shape=(1,), units='N')
phase.add_timeseries_output('aero.f_drag', shape=(1,), units='N')
# upgrade_doc: end glob_timeseries_outputs
"""
from dymos.examples.min_time_climb.min_time_climb_ode import MinTimeClimbODE
p = om.Problem(model=om.Group())
p.driver = om.pyOptSparseDriver()
p.driver.options['optimizer'] = 'SLSQP'
p.driver.declare_coloring(tol=1.0E-12)
traj = dm.Trajectory()
phase = dm.Phase(ode_class=MinTimeClimbODE,
transcription=dm.GaussLobatto(num_segments=15, compressed=True))
traj.add_phase('phase0', phase)
p.model.add_subsystem('traj', traj)
phase.set_time_options(fix_initial=True, duration_bounds=(50, 400),
duration_ref=100.0)
phase.add_state('r', fix_initial=True, lower=0, upper=1.0E6,
ref=1.0E3, defect_ref=1.0E3, units='m',
rate_source='flight_dynamics.r_dot')
phase.add_state('h', fix_initial=True, lower=0, upper=20000.0,
ref=1.0E2, defect_ref=1.0E2, units='m',
rate_source='flight_dynamics.h_dot')
phase.add_state('v', fix_initial=True, lower=10.0,
ref=1.0E2, defect_ref=1.0E2, units='m/s',
rate_source='flight_dynamics.v_dot')
phase.add_state('gam', fix_initial=True, lower=-1.5, upper=1.5,
ref=1.0, defect_ref=1.0, units='rad',
rate_source='flight_dynamics.gam_dot')
phase.add_state('m', fix_initial=True, lower=10.0, upper=1.0E5,
ref=1.0E3, defect_ref=1.0E3, units='kg',
rate_source='prop.m_dot')
phase.add_control('alpha', units='deg', lower=-8.0, upper=8.0, scaler=1.0,
rate_continuity=True, rate_continuity_scaler=100.0,
rate2_continuity=False, targets=['alpha'])
phase.add_parameter('S', val=49.2386, units='m**2', opt=False, targets=['S'])
phase.add_parameter('Isp', val=1600.0, units='s', opt=False, targets=['Isp'])
phase.add_parameter('throttle', val=1.0, opt=False, targets=['throttle'])
phase.add_boundary_constraint('h', loc='final', equals=20000, scaler=1.0E-3, units='m')
phase.add_boundary_constraint('aero.mach', loc='final', equals=1.0, shape=(1,))
phase.add_boundary_constraint('gam', loc='final', equals=0.0, units='rad')
phase.add_path_constraint(name='h', lower=100.0, upper=20000, ref=20000)
phase.add_path_constraint(name='aero.mach', lower=0.1, upper=1.8, shape=(1,))
phase.add_objective('time', loc='final', ref=1.0)
p.model.linear_solver = om.DirectSolver()
# upgrade_doc: begin glob_timeseries_outputs
phase.add_timeseries_output('aero.*')
# upgrade_doc: end glob_timeseries_outputs
p.setup(check=True)
p['traj.phase0.t_initial'] = 0.0
p['traj.phase0.t_duration'] = 500
p['traj.phase0.states:r'] = phase.interpolate(ys=[0.0, 50000.0], nodes='state_input')
p['traj.phase0.states:h'] = phase.interpolate(ys=[100.0, 20000.0], nodes='state_input')
p['traj.phase0.states:v'] = phase.interpolate(ys=[135.964, 283.159], nodes='state_input')
p['traj.phase0.states:gam'] = phase.interpolate(ys=[0.0, 0.0], nodes='state_input')
p['traj.phase0.states:m'] = phase.interpolate(ys=[19030.468, 10000.], nodes='state_input')
p['traj.phase0.controls:alpha'] = phase.interpolate(ys=[0.0, 0.0], nodes='control_input')
#
# Solve for the optimal trajectory
#
p.run_model()
outputs = p.model.list_outputs(units=True, out_stream=None, prom_name=True)
op_dict = {options['prom_name']: options['units'] for abs_name, options in outputs}
for name, units in [('mach', None), ('CD0', None), ('kappa', None), ('CLa', None),
('CL', None), ('CD', None), ('q', 'N/m**2'), ('f_lift', 'N'),
('f_drag', 'N')]:
self.assertEqual(op_dict[f'traj.phase0.timeseries.{name}'], units)
@require_pyoptsparse(optimizer='SLSQP')
def test_sequence_timeseries_outputs(self):
"""
# upgrade_doc: begin sequence_timeseries_outputs
phase.add_timeseries_output('aero.mach', shape=(1,), units=None)
phase.add_timeseries_output('aero.CD0', shape=(1,), units=None)
phase.add_timeseries_output('aero.kappa', shape=(1,), units=None)
phase.add_timeseries_output('aero.CLa', shape=(1,), units=None)
phase.add_timeseries_output('aero.CL', shape=(1,), units=None)
phase.add_timeseries_output('aero.CD', shape=(1,), units=None)
phase.add_timeseries_output('aero.q', shape=(1,), units='N/m**2')
phase.add_timeseries_output('aero.f_lift', shape=(1,), units='lbf')
phase.add_timeseries_output('aero.f_drag', shape=(1,), units='N')
phase.add_timeseries_output('prop.thrust', shape=(1,), units='lbf')
# upgrade_doc: end sequence_timeseries_outputs
# upgrade_doc: begin state_endpoint_values
final_range = p.get_val('traj.phase0.final_conditions.states:x0++')
final_alpha = p.get_val('traj.phase0.final_conditions.controls:alpha++')
# upgrade_doc: end state_endpoint_values
"""
from dymos.examples.min_time_climb.min_time_climb_ode import MinTimeClimbODE
p = om.Problem(model=om.Group())
p.driver = om.pyOptSparseDriver()
p.driver.options['optimizer'] = 'SLSQP'
p.driver.declare_coloring(tol=1.0E-12)
traj = dm.Trajectory()
phase = dm.Phase(ode_class=MinTimeClimbODE,
transcription=dm.GaussLobatto(num_segments=15, compressed=True))
traj.add_phase('phase0', phase)
p.model.add_subsystem('traj', traj)
phase.set_time_options(fix_initial=True, duration_bounds=(50, 400),
duration_ref=100.0)
phase.add_state('r', fix_initial=True, lower=0, upper=1.0E6,
ref=1.0E3, defect_ref=1.0E3, units='m',
rate_source='flight_dynamics.r_dot')
phase.add_state('h', fix_initial=True, lower=0, upper=20000.0,
ref=1.0E2, defect_ref=1.0E2, units='m',
rate_source='flight_dynamics.h_dot')
phase.add_state('v', fix_initial=True, lower=10.0,
ref=1.0E2, defect_ref=1.0E2, units='m/s',
rate_source='flight_dynamics.v_dot')
phase.add_state('gam', fix_initial=True, lower=-1.5, upper=1.5,
ref=1.0, defect_ref=1.0, units='rad',
rate_source='flight_dynamics.gam_dot')
phase.add_state('m', fix_initial=True, lower=10.0, upper=1.0E5,
ref=1.0E3, defect_ref=1.0E3, units='kg',
rate_source='prop.m_dot')
phase.add_control('alpha', units='deg', lower=-8.0, upper=8.0, scaler=1.0,
rate_continuity=True, rate_continuity_scaler=100.0,
rate2_continuity=False, targets=['alpha'])
phase.add_parameter('S', val=49.2386, units='m**2', opt=False, targets=['S'])
phase.add_parameter('Isp', val=1600.0, units='s', opt=False, targets=['Isp'])
phase.add_parameter('throttle', val=1.0, opt=False, targets=['throttle'])
phase.add_boundary_constraint('h', loc='final', equals=20000, scaler=1.0E-3, units='m')
phase.add_boundary_constraint('aero.mach', loc='final', equals=1.0, shape=(1,))
phase.add_boundary_constraint('gam', loc='final', equals=0.0, units='rad')
phase.add_path_constraint(name='h', lower=100.0, upper=20000, ref=20000)
phase.add_path_constraint(name='aero.mach', lower=0.1, upper=1.8, shape=(1,))
phase.add_objective('time', loc='final', ref=1.0)
p.model.linear_solver = om.DirectSolver()
# upgrade_doc: begin sequence_timeseries_outputs
phase.add_timeseries_output(['aero.*', 'prop.thrust'],
units={'aero.f_lift': 'lbf', 'prop.thrust': 'lbf'})
# upgrade_doc: end sequence_timeseries_outputs
p.setup(check=True)
p['traj.phase0.t_initial'] = 0.0
p['traj.phase0.t_duration'] = 500
p['traj.phase0.states:r'] = phase.interpolate(ys=[0.0, 50000.0], nodes='state_input')
p['traj.phase0.states:h'] = phase.interpolate(ys=[100.0, 20000.0], nodes='state_input')
p['traj.phase0.states:v'] = phase.interpolate(ys=[135.964, 283.159], nodes='state_input')
p['traj.phase0.states:gam'] = phase.interpolate(ys=[0.0, 0.0], nodes='state_input')
p['traj.phase0.states:m'] = phase.interpolate(ys=[19030.468, 10000.], nodes='state_input')
p['traj.phase0.controls:alpha'] = phase.interpolate(ys=[0.0, 0.0], nodes='control_input')
p.run_model()
# upgrade_doc: begin state_endpoint_values
final_range = p.get_val('traj.phase0.timeseries.states:r')[-1, ...]
final_alpha = p.get_val('traj.phase0.timeseries.controls:alpha')[-1, ...]
# upgrade_doc: end state_endpoint_values
self.assertEqual(final_range, 50000.0)
self.assertEqual(final_alpha, 0.0)
outputs = p.model.list_outputs(units=True, out_stream=None, prom_name=True)
op_dict = {options['prom_name']: options['units'] for abs_name, options in outputs}
for name, units in [('mach', None), ('CD0', None), ('kappa', None), ('CLa', None),
('CL', None), ('CD', None), ('q', 'N/m**2'), ('f_lift', 'lbf'),
('f_drag', 'N'), ('thrust', 'lbf')]:
self.assertEqual(op_dict[f'traj.phase0.timeseries.{name}'], units)
@use_tempdirs
class TestUpgrade_0_17_0(unittest.TestCase):
def test_tags(self):
"""
# upgrade_doc: begin tag_rate_source
self.add_output('xdot', val=np.zeros(nn), desc='velocity component in x', units='m/s')
self.add_output('ydot', val=np.zeros(nn), desc='velocity component in y', units='m/s')
self.add_output('vdot', val=np.zeros(nn), desc='acceleration magnitude', units='m/s**2')
# upgrade_doc: end tag_rate_source
# upgrade_doc: begin declare_rate_source
phase.add_state('x', rate_source='xdot', fix_initial=True, fix_final=True)
phase.add_state('y', rate_source='ydot', fix_initial=True, fix_final=True)
phase.add_state('v', rate_source='vdot', fix_initial=True, fix_final=False)
# upgrade_doc: end declare_rate_source
"""
import numpy as np
import openmdao.api as om
class BrachistochroneODE(om.ExplicitComponent):
def initialize(self):
self.options.declare('num_nodes', types=int)
self.options.declare('static_gravity', types=(bool,), default=False,
desc='If True, treat gravity as a static (scalar) input, rather than '
'having different values at each node.')
def setup(self):
nn = self.options['num_nodes']
g_default_val = 9.80665 if self.options['static_gravity'] else 9.80665 * np.ones(nn)
# Inputs
self.add_input('v', val=np.zeros(nn), desc='velocity', units='m/s')
self.add_input('g', val=g_default_val, desc='grav. acceleration', units='m/s/s')
self.add_input('theta', val=np.ones(nn), desc='angle of wire', units='rad')
# upgrade_doc: begin tag_rate_source
self.add_output('xdot', val=np.zeros(nn), desc='velocity component in x', units='m/s',
tags=['dymos.state_rate_source:x', 'dymos.state_units:m'])
self.add_output('ydot', val=np.zeros(nn), desc='velocity component in y', units='m/s',
tags=['dymos.state_rate_source:y', 'dymos.state_units:m'])
self.add_output('vdot', val=np.zeros(nn), desc='acceleration magnitude', units='m/s**2',
tags=['dymos.state_rate_source:v', 'dymos.state_units:m/s'])
# upgrade_doc: end tag_rate_source
self.add_output('check', val=np.zeros(nn), desc='check solution: v/sin(theta) = constant',
units='m/s')
# Setup partials
arange = np.arange(self.options['num_nodes'])
self.declare_partials(of='vdot', wrt='theta', rows=arange, cols=arange)
self.declare_partials(of='xdot', wrt='v', rows=arange, cols=arange)
self.declare_partials(of='xdot', wrt='theta', rows=arange, cols=arange)
self.declare_partials(of='ydot', wrt='v', rows=arange, cols=arange)
self.declare_partials(of='ydot', wrt='theta', rows=arange, cols=arange)
self.declare_partials(of='check', wrt='v', rows=arange, cols=arange)
self.declare_partials(of='check', wrt='theta', rows=arange, cols=arange)
if self.options['static_gravity']:
c = np.zeros(self.options['num_nodes'])
self.declare_partials(of='vdot', wrt='g', rows=arange, cols=c)
else:
self.declare_partials(of='vdot', wrt='g', rows=arange, cols=arange)
def compute(self, inputs, outputs):
theta = inputs['theta']
cos_theta = np.cos(theta)
sin_theta = np.sin(theta)
g = inputs['g']
v = inputs['v']
outputs['vdot'] = g * cos_theta
outputs['xdot'] = v * sin_theta
outputs['ydot'] = -v * cos_theta
outputs['check'] = v / sin_theta
def compute_partials(self, inputs, partials):
theta = inputs['theta']
cos_theta = np.cos(theta)
sin_theta = np.sin(theta)
g = inputs['g']
v = inputs['v']
partials['vdot', 'g'] = cos_theta
partials['vdot', 'theta'] = -g * sin_theta
partials['xdot', 'v'] = sin_theta
partials['xdot', 'theta'] = v * cos_theta
partials['ydot', 'v'] = -cos_theta
partials['ydot', 'theta'] = v * sin_theta
partials['check', 'v'] = 1 / sin_theta
partials['check', 'theta'] = -v * cos_theta / sin_theta ** 2
import openmdao.api as om
from openmdao.utils.assert_utils import assert_near_equal
import dymos as dm
#
# Initialize the Problem and the optimization driver
#
p = om.Problem(model=om.Group())
p.driver = om.ScipyOptimizeDriver()
p.driver.declare_coloring()
#
# Create a trajectory and add a phase to it
#
traj = p.model.add_subsystem('traj', dm.Trajectory())
phase = traj.add_phase('phase0',
dm.Phase(ode_class=BrachistochroneODE,
transcription=dm.GaussLobatto(num_segments=10)))
#
# Set the variables
#
phase.set_time_options(fix_initial=True, duration_bounds=(.5, 10))
# upgrade_doc: begin declare_rate_source
phase.add_state('x', fix_initial=True, fix_final=True)
phase.add_state('y', fix_initial=True, fix_final=True)
phase.add_state('v', fix_initial=True, fix_final=False)
# upgrade_doc: end declare_rate_source
phase.add_control('theta', continuity=True, rate_continuity=True,
units='deg', lower=0.01, upper=179.9)
phase.add_parameter('g', units='m/s**2', val=9.80665)
#
# Minimize time at the end of the phase
#
phase.add_objective('time', loc='final', scaler=10)
p.model.linear_solver = om.DirectSolver()
#
# Setup the Problem
#
p.setup()
#
# Set the initial values
#
p['traj.phase0.t_initial'] = 0.0
p['traj.phase0.t_duration'] = 2.0
p['traj.phase0.states:x'] = phase.interpolate(ys=[0, 10], nodes='state_input')
p['traj.phase0.states:y'] = phase.interpolate(ys=[10, 5], nodes='state_input')
p['traj.phase0.states:v'] = phase.interpolate(ys=[0, 9.9], nodes='state_input')
p['traj.phase0.controls:theta'] = phase.interpolate(ys=[5, 100.5], nodes='control_input')
#
# Solve for the optimal trajectory
#
dm.run_problem(p)
# Test the results
assert_near_equal(p.get_val('traj.phase0.timeseries.time')[-1], 1.8016, tolerance=1.0E-3)
@use_tempdirs
class TestUpgrade_0_19_0(unittest.TestCase):
def tearDown(self):
if os.path.exists('dymos_solution.db'):
os.remove('dymos_solution.db')
if os.path.exists('dymos_simulation.db'):
os.remove('dymos_simulation.db')
@require_pyoptsparse(optimizer='SLSQP')
def _make_problem(self, transcription='gauss-lobatto', num_segments=8, transcription_order=3,
compressed=True, optimizer='SLSQP', run_driver=True,
force_alloc_complex=False,
solve_segments=False):
p = om.Problem(model=om.Group())
p.driver = om.pyOptSparseDriver()
p.driver.options['optimizer'] = optimizer
p.driver.declare_coloring(tol=1.0E-12)
if transcription == 'gauss-lobatto':
t = dm.GaussLobatto(num_segments=num_segments,
order=transcription_order,
compressed=compressed)
elif transcription == 'radau-ps':
t = dm.Radau(num_segments=num_segments,
order=transcription_order,
compressed=compressed)
# upgrade_doc: begin exec_comp_ode
def ode(num_nodes):
return om.ExecComp(['vdot = g * cos(theta)',
'xdot = v * sin(theta)',
'ydot = -v * cos(theta)'],
g={'val': 9.80665, 'units': 'm/s**2'},
v={'shape': (num_nodes,), 'units': 'm/s'},
theta={'shape': (num_nodes,), 'units': 'rad'},
vdot={'shape': (num_nodes,), 'units': 'm/s**2'},
xdot={'shape': (num_nodes,), 'units': 'm/s'},
ydot={'shape': (num_nodes,), 'units': 'm/s'},
has_diag_partials=True)
phase = dm.Phase(ode_class=ode, transcription=t)
# upgrade_doc: end declare_rate_source
traj = dm.Trajectory()
p.model.add_subsystem('traj0', traj)
traj.add_phase('phase0', phase)
phase.set_time_options(fix_initial=True, duration_bounds=(.5, 10))
phase.add_state('x', fix_initial=True, fix_final=False, solve_segments=solve_segments,
rate_source='xdot')
phase.add_state('y', fix_initial=True, fix_final=False, solve_segments=solve_segments,
rate_source='ydot')
# Note that by omitting the targets here Dymos will automatically attempt to connect
# to a top-level input named 'v' in the ODE, and connect to nothing if it's not found.
phase.add_state('v', fix_initial=True, fix_final=False, solve_segments=solve_segments,
rate_source='vdot')
phase.add_control('theta',
continuity=True, rate_continuity=True,
units='deg', lower=0.01, upper=179.9)
phase.add_parameter('g', units='m/s**2', static_target=True)
phase.add_boundary_constraint('x', loc='final', equals=10)
phase.add_boundary_constraint('y', loc='final', equals=5)
# Minimize time at the end of the phase
phase.add_objective('time_phase', loc='final', scaler=10)
p.setup(check=['unconnected_inputs'], force_alloc_complex=force_alloc_complex)
p['traj0.phase0.t_initial'] = 0.0
p['traj0.phase0.t_duration'] = 2.0
p['traj0.phase0.states:x'] = phase.interpolate(ys=[0, 10], nodes='state_input')
p['traj0.phase0.states:y'] = phase.interpolate(ys=[10, 5], nodes='state_input')
p['traj0.phase0.states:v'] = phase.interpolate(ys=[0, 9.9], nodes='state_input')
p['traj0.phase0.controls:theta'] = phase.interpolate(ys=[5, 100], nodes='control_input')
p['traj0.phase0.parameters:g'] = 9.80665
dm.run_problem(p, run_driver=run_driver, simulate=True)
return p
def run_asserts(self):
for db in ['dymos_solution.db', 'dymos_simulation.db']:
p = om.CaseReader(db).get_case('final')
t_initial = p.get_val('traj0.phase0.timeseries.time')[0]
tf = p.get_val('traj0.phase0.timeseries.time')[-1]
x0 = p.get_val('traj0.phase0.timeseries.states:x')[0]
xf = p.get_val('traj0.phase0.timeseries.states:x')[-1]
y0 = p.get_val('traj0.phase0.timeseries.states:y')[0]
yf = p.get_val('traj0.phase0.timeseries.states:y')[-1]
v0 = p.get_val('traj0.phase0.timeseries.states:v')[0]
vf = p.get_val('traj0.phase0.timeseries.states:v')[-1]
g = p.get_val('traj0.phase0.timeseries.parameters:g')[0]
thetaf = p.get_val('traj0.phase0.timeseries.controls:theta')[-1]
assert_near_equal(t_initial, 0.0)
assert_near_equal(x0, 0.0)
assert_near_equal(y0, 10.0)
assert_near_equal(v0, 0.0)
assert_near_equal(tf, 1.8016, tolerance=0.01)
assert_near_equal(xf, 10.0, tolerance=0.01)
assert_near_equal(yf, 5.0, tolerance=0.01)
assert_near_equal(vf, 9.902, tolerance=0.01)
assert_near_equal(g, 9.80665, tolerance=0.01)
assert_near_equal(thetaf, 100.12, tolerance=0.01)
def test_ex_brachistochrone_radau_uncompressed(self):
self._make_problem(transcription='radau-ps', compressed=False)
self.run_asserts()
def test_ex_brachistochrone_gl_uncompressed(self):
self._make_problem(transcription='gauss-lobatto', compressed=False)
self.run_asserts()
| [
"noreply@github.com"
] | johnjasa.noreply@github.com |
523751e6e8961a085fb1b5cf1bba096980c6d848 | 8a56a194ccd95f761e75cf321e17cfa4e022672e | /Day1/HelloPython.py | 65831feb52e29334048c34ae869d671b5512cc95 | [] | no_license | Nagadath-Gummadi/Python | ac65242228f6d4dbff7b92f6f81e92224d819ae7 | be06d09f398b65c76da4a14e1d999b2b0344b823 | refs/heads/main | 2023-04-06T02:05:30.617549 | 2021-04-21T16:12:42 | 2021-04-21T16:12:42 | 355,996,691 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 48 | py | print('Hello Python')
print('This is Nagadath')
| [
"noreply@github.com"
] | Nagadath-Gummadi.noreply@github.com |
b482070fbae3637bb4dd0ca363734f2f956ecc0b | da900dd1e472a9f97cef1fce2248071003ba7afd | /networks/legacy_resnet.py | fd411275083114560b1c03a78a86589ec1a4f006 | [] | no_license | Kitsunetic/motion-classification-dacon | aa6a7964107bc22380b646cd279f2cb460f8d098 | b9a20af6e2e10a8a86e8860b7533cce7cf8e24a1 | refs/heads/master | 2023-05-26T18:24:56.953163 | 2021-06-09T07:47:51 | 2021-06-09T07:47:51 | 334,885,231 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,971 | py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .resnet import BasicBlock, BottleNeck
from .common import Activation
class LegacyResNet(nn.Module):
def __init__(self, block, layers):
super().__init__()
self.inchannels = 32
self.conv = nn.Sequential(
nn.Conv1d(18, self.inchannels, 3, padding=1, bias=False),
nn.BatchNorm1d(self.inchannels),
Activation(),
)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1])
self.layer3 = self._make_layer(block, 256, layers[2])
self.layer4 = self._make_layer(block, 512, layers[3])
self.fc = nn.Sequential(
nn.AdaptiveAvgPool1d(1),
nn.Flatten(),
nn.Linear(self.inchannels, 61),
)
def forward(self, x):
x = self.conv(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.fc(x)
return x
def _make_layer(self, block, channels, blocks, stride=1):
layers = []
layers.append(block(self.inchannels, channels, stride=stride))
self.inchannels = channels * block.expansion
for _ in range(1, blocks):
layers.append(block(self.inchannels, channels))
return nn.Sequential(*layers)
class LegacyResNet18(LegacyResNet):
def __init__(self):
super().__init__(BasicBlock, [2, 2, 2, 2])
class LegacyResNet34(LegacyResNet):
def __init__(self):
super().__init__(BasicBlock, [3, 4, 6, 3])
class LegacyResNet50(LegacyResNet):
def __init__(self):
super().__init__(BottleNeck, [3, 4, 6, 3])
class LegacyResNet101(LegacyResNet):
def __init__(self):
super().__init__(BottleNeck, [3, 4, 23, 3])
class LegacyResNet152(LegacyResNet):
def __init__(self):
super().__init__(BottleNeck, [3, 8, 36, 3])
| [
"kitsune.guru@gmail.com"
] | kitsune.guru@gmail.com |
0a7597e3d236cf1e48f13a9f3922e70e10cccc71 | 1d1bf4a38e497980b659959ba198034d12ef07da | /BinPacking_v2/main_tabu_search.py | c0b1392a5affaf0f95f35e34508f4c7714301584 | [] | no_license | IdrissHmz/Opt-BinPack-Resolver | b6542fffbb166cf818331251b9730b5aa3be9d96 | 558228bddefa2722d373eb67402fdc0aca2d0584 | refs/heads/main | 2023-07-31T17:48:58.993458 | 2021-09-21T14:12:30 | 2021-09-21T14:12:30 | 408,844,471 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,920 | py | from TabuSearch import TabuSearch
from GeneticAlgorithm import Item
from random import shuffle
from datetime import datetime
import json
def log(message, end=None):
print(message, flush=True, end=end)
if __name__ == '__main__':
datasets = [
{"name": "instances/Difficile/T_Moyenne_200/HARD0.txt", "solution":56, "results": {}},
# {"name": "HARD0.txt", "solution":56, "results": {}},
# {"name": "HARD6.txt", "solution":57, "results": {}},
# {"name": "HARD7.txt", "solution":55, "results": {}},
# {"name": "N1C1W4_E.txt", "solution":35, "results": {}},
# {"name": "N1C2W2_H.txt", "solution":23, "results": {}},
# {"name": "N1C3W1_C.txt", "solution":17, "results": {}},
# {"name": "N2C1W1_G.txt", "solution":60, "results": {}},
# {"name": "N2C2W1_F.txt", "solution":49, "results": {}},
# {"name": "N2C3W1_Q.txt", "solution":34, "results": {}},
# {"name": "N3C1W1_K.txt", "solution":102, "results": {}},
# {"name": "N1W4B2R3.txt", "solution":6, "results": {}},
# {"name": "N2W1B3R8.txt", "solution":34, "results": {}},
# {"name": "N3W3B3R1.txt", "solution":27, "results": {}},
# {"name": "N4W4B3R9.txt", "solution":56, "results": {}},
]
# Loop through each data set.
for dataset in datasets:
# Read the data into memory
with open('datasets/{}'.format(dataset["name"]), 'r') as file:
data = file.read().splitlines()
num_items, capacity, items = int(data[0]), int(data[1]), data[2:]
log("\n\nDATASET {}: num_items {} capacity {} items_read {}".format(dataset["name"], num_items, capacity, len(items)))
items = [Item(size=int(i)) for i in items]
log(" Iteration", end=" ")
# Perform 30 independent iterations.
for iteration in range(1):
log(iteration+1, end=" ")
# Randomize the order of the items in the item list.
shuffle(items)
thing = TabuSearch(capacity, items)
start_time = datetime.now()
total_iterations, stagnation, combination = thing.run()
execution_time = datetime.now() - start_time
# Record the relevant data for analysis
summary = {
"execution_time": str(execution_time),
"num_bins": len(thing.bins),
"fitness": sum(b.fitness() for b in thing.bins) / len(thing.bins),
"iterations": total_iterations,
"stagnation": stagnation,
"combination": combination,
"tabu_list": list(thing.tabu_list)
}
dataset["results"].setdefault("TabuSearch", []).append(summary)
# Write the captured data to disk.
with open("./resultats/results_tabu_search.json", "w") as file:
file.write(json.dumps(datasets, indent=2))
| [
"noreply@github.com"
] | IdrissHmz.noreply@github.com |
2fda4647c5ff8473a142c6167a9441fd04805d55 | b9565415aba7b0e2e1d69c6f137b14718491ec9c | /picture.py | 45c5f5a8f286b7c44a77f2b23a85ed8940979578 | [] | no_license | JaclynNoga/Relativity_word_problems_2014 | d52258eecaa5556f18ca9cea0e2056fd72a67bdd | 4f7003d463d383089cb71b34b760187d0eada780 | refs/heads/master | 2016-09-13T04:13:48.113326 | 2016-05-23T22:20:01 | 2016-05-23T22:20:01 | 59,521,942 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,198 | py | from tkinter import *
import math
import sys
class Picture():
def __init__(self, param, param2=0, TITLE=None):
self.root = Tk()
if TITLE != None:
self.root.wm_title(TITLE)
self.frame = Frame(self.root, None, borderwidth=0)
self.frame.grid()
global canvas
# Check if parameter is the right type, because we can't
# overload functions
if isinstance(param, tuple) and len(param) == 2:
canvas = Canvas(self.root, width=param[0], height=param[1],
background="white", bd=0,
highlightthickness=0)
canvas.grid()
elif isinstance(param, int):
canvas = Canvas(self.root, width=param, height=param2,
background="white", bd=0,
highlightthickness=0)
canvas.grid()
elif isinstance(param, str):
self.image = PhotoImage(file=param)
canvas = Canvas(self.root, width=self.image.width(),
height=self.image.height(), bd=0,
highlightthickness=0)
canvas.grid()
canvas.create_image(0, 0, image=self.image)
else:
raise TypeError('Parameter to Picture() should be' + 'string of a .gif/pgm/ppm file name or 2-tuple!')
global outlineColor
outlineColor = "black"
global fillColor
fillColor = "white"
global penWidth
penWidth = 1
global pen_position
pen_position = (0, 0)
global pen_rotation
pen_rotation = 0
def setPosition(self, x, y):
global pen_position
pen_position = (x, y)
def setPenX(self, x):
global pen_position
pen_position = (x, pen_position[1])
def setPenY(self, y):
global pen_position
pen_position = (pen_position[0], y)
def getPosition(self):
return pen_position
def rotate(self, theta):
global pen_rotation
pen_rotation += theta
pen_rotation %= 360
def setDirection(self, theta):
global pen_rotation
pen_rotation = theta
pen_rotation %= 360
def getDirection(self):
return pen_rotation
def drawForward(self, distance):
global pen_position
radian = math.radians(pen_rotation)
startX = pen_position[0]
startY = pen_position[1]
endX = startX + math.cos(radian) * distance
endY = startY + math.sin(radian) * distance
end = (endX, endY)
pen_position = end
return self.drawLine(startX, startY, endX, endY)
def setFillColor(self, color, g=0, b=0):
global fillColor
if isinstance(color,tuple) :
fillColor = color_to_hex(color)
else :
fillColor = color_to_hex((color,g,b))
def getFillColor(self):
return fillColor
def setOutlineColor(self, color, g=0, b=0):
global outlineColor
if isinstance(color,tuple) :
outlineColor = color_to_hex(color)
else :
outlineColor = color_to_hex((color,g,b))
def getOutlineColor(self):
return outlineColor
def setPenWidth(self, width):
global penWidth
penWidth = width
def getPenWidth(self):
return penWidth
def drawOval(self, x, y, hrad, vrad):
return Oval(x, y, hrad, vrad, False)
def drawOvalFill(self, x, y, hrad, vrad):
return Oval(x, y, hrad, vrad, True)
def drawCircle(self, x, y, r):
return Circle(x, y, r, False)
def drawCircleFill(self, x, y, r):
return Circle(x, y, r, True)
def drawRect(self, x, y, w, h):
return Rectangle(x, y, w, h, False)
def drawRectFill(self, x, y, w, h):
return Rectangle(x, y, w, h, True)
def drawSquare(self, x, y, side):
return Square(x, y, side, False)
def drawSquareFill(self, x, y, side):
return Square(x, y, side, True)
def drawPolygon(self, vertices):
return Polygon(vertices, False)
def drawPolygonFill(self, vertices):
return Polygon(vertices, True)
def drawLine(self, x1, y1, x2, y2):
return Line(x1, y1, x2, y2)
def drawText(self, x, y, TEXT, font_name, font_size):
return Text(x, y, TEXT, font_name, font_size)
def changeCanvasSize(self, newWidth, newHeight):
canvas.config(width=newWidth, height=newHeight)
def display(self):
canvas.update()
def delay(self, millisecond):
canvas.after(millisecond)
def pixel(self, x, y, color):
canvas.create_line(x, y, x + 1, y + 1, fill=color_to_hex(color))
class Shape:
def __init__(self, vertices):
self.vertices = vertices
self.my_shape = None
def getLocation(self):
return (self.vertices[0][0], self.vertices[0][1])
def changeFillColor(self, color):
canvas.itemconfigure(self.my_shape, fill = color_to_hex(color))
def changeOutlineColor(self, color):
canvas.itemconfigure(self.my_shape, outline = color_to_hex(color))
def moveby(self, dx, dy):
canvas.move(self.my_shape, dx, dy)
for point in self.vertices:
point[0] = point[0] + dx
point[1] = point[1] + dy
def moveto(self, x, y):
[a, b] = self.vertices[0]
dx = x - a
dy = y - b
self.moveby(dx, dy)
class Rectangle(Shape):
def __init__(self, x, y, w, h, fill=False):
Shape.__init__(self, [[x, y], [x + w, y + h]])
if fill == True:
self.my_shape = canvas.create_rectangle(x, y, x + w, y + h, fill=fillColor,
outline=outlineColor,
width=penWidth)
else:
self.my_shape = canvas.create_rectangle(x, y, x + w, y + h,
outline=outlineColor,
width=penWidth)
class Square(Rectangle):
def __init__(self, x, y, side, fill):
Rectangle.__init__(self, x, y, x + side, y + side, fill)
class Oval(Shape):
def __init__(self, x, y, hrad, vrad, fill=False):
Shape.__init__(self,[[x - hrad, y - vrad], [x + hrad, y + vrad]])
if fill == True:
self.my_shape = canvas.create_oval(x - hrad, y - vrad, x + hrad, y + vrad,
fill=fillColor, outline=outlineColor,
width=penWidth)
else:
self.my_shape = canvas.create_oval(x - hrad, y - vrad, x + hrad, y + vrad,
outline=outlineColor,
width=penWidth)
class Circle(Oval):
def __init__(self, x, y, r, fill):
Oval.__init__(self, x, y, r, r, fill)
class Polygon(Shape):
def __init__(self, vertices, fill=False):
Shape.__init__(self, vertices)
if fill == True:
self.my_shape = canvas.create_polygon(vertices, fill=fillColor,
outline=outlineColor,
width=penWidth)
else:
self.my_shape = canvas.create_polygon(vertices,
outline=outlineColor,
width=penWidth)
class Line(Shape):
def __init__(self, x1, y1, x2, y2):
Shape.__init__(self, [[x1, y1], [x2, y2]])
self.my_shape = canvas.create_line(x1, y1, x2, y2,
fill=outlineColor, width=penWidth)
#font_name and font_size are STRINGS, e.g. "Helvectica" and "16"
class Text(Shape):
def __init__(self, x, y, TEXT, font_name, font_size):
Shape.__init__(self, [[x, y]])
self.my_shape = canvas.create_text(x, y, text = TEXT,
font=(font_name, font_size), fill=fillColor)
def color_to_hex(color):
return '#%02x%02x%02x'.upper() % (color[0], color[1], color[2]) | [
"you@example.com"
] | you@example.com |
7f9fc2e64fb08cb1368a761ce9e1462217c76337 | 38c98758d1920411a148b137677f3de3a5baf2e1 | /lab3/imdbspider.py | bc3b5a9077e3facfc79fbdd047ed1b3e6034d6f5 | [] | no_license | ZombieCait/DR_DK | 253d91a4f281ef6ce5d8b10fce595860db552e50 | 2442acbe9ccd94c17cceb7596ec417cff869f061 | refs/heads/master | 2020-05-03T16:38:49.319347 | 2019-05-16T10:15:27 | 2019-05-16T10:15:27 | 178,727,697 | 0 | 0 | null | 2019-03-31T18:41:04 | 2019-03-31T18:41:03 | null | UTF-8 | Python | false | false | 1,372 | py | import scrapy
class ImdbSpider(scrapy.Spider):
name = 'imdbspider'
#Здесь нужно или получить массив фильмов из бд\файла, или получить параметр из командной строки
#и собрать URI
#Для примера подойдёт и константа
start_urls = ['https://www.imdb.com/title/tt0113243/']
def parse(self, response):
for title in response.css('.title_wrapper>h1'):
yield {'title': title.css('h1 ::text').get().replace(u'\xa0', u'')}
yield {'year': title.css('a ::text').get()}
#Пример xpath селекторов
for rating in response.css('.ratingValue>strong>span'):
yield {'rating': rating.css('span ::text').get()}
yield {'ratingXPath': rating.xpath('string(.)').extract()}
for plot_page in response.css('#titleStoryLine > span:nth-child(4) > a:nth-child(3)'):
#Пример перехода по ссылкам
yield response.follow(plot_page, self.parseSyno)#Если ссылка найдётся то мы переёдм по ней и вызовем метод parsSyno
def parseSyno(self, response):
for syno in response.css('#plot-synopsis-content>li'):
yield {'synopsys': syno.xpath('text()').extract()}
~
| [
"caitzombie@gmail.com"
] | caitzombie@gmail.com |
2e421842c61db0a90cfcaab5402ef0c457e78b09 | ab0315bcded75c10c591076b22ed8ff664ee76af | /fig4/config_scf_10mods_merfish_200213.py | ba6e77af2db7ec33e2b3695646b1eb7070940d82 | [] | no_license | mukamel-lab/BICCN-Mouse-MOp | 389f62492986a2ffe4278ed16f59fc17dc75b767 | 8058ab8ae827c6e019fff719903b0ba5b400931d | refs/heads/master | 2021-07-06T11:14:25.401628 | 2020-09-30T04:54:27 | 2020-09-30T04:54:27 | 189,758,115 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,740 | py | #!/usr/bin/env python3
"""An example configuration file
"""
import sys
import os
# # Configs
name = 'mop_10mods_merfish_200213'
outdir = '/cndd/fangming/CEMBA/data/MOp_all/results'
output_pcX_all = outdir + '/pcX_all_{}.npy'.format(name)
output_cells_all = outdir + '/cells_all_{}.npy'.format(name)
output_imputed_data_format = outdir + '/imputed_data_{}_{{}}.npy'.format(name)
output_clst_and_umap = outdir + '/intg_summary_{}.tsv'.format(name)
output_figures = outdir + '/figures/{}_{{}}.{{}}'.format(name)
output_cluster_centroids = outdir + '/centroids_{}.pkl'.format(name)
DATA_DIR = '/cndd/fangming/CEMBA/data/MOp_all/data_freeze_l5pt'
# fixed dataset configs
sys.path.insert(0, DATA_DIR)
from __init__datasets import *
meta_f = os.path.join(DATA_DIR, '{0}_metadata.tsv')
hvftrs_f = os.path.join(DATA_DIR, '{0}_hvfeatures.{1}')
hvftrs_gene = os.path.join(DATA_DIR, '{0}_hvfeatures.gene')
hvftrs_cell = os.path.join(DATA_DIR, '{0}_hvfeatures.cell')
mods_selected = [
'snmcseq_gene',
'snatac_gene',
'smarter_cells',
'smarter_nuclei',
'10x_cells_v2',
'10x_cells_v3',
'10x_nuclei_v3',
'10x_nuclei_v3_macosko',
'merfish',
'epi_retro',
]
features_selected = ['merfish']
# check features
for features_modality in features_selected:
assert (features_modality in mods_selected)
# within modality
ps = {'mc': 0.9,
'atac': 0.1,
'rna': 0.7,
'merfish': 1,
}
drop_npcs = {
'mc': 0,
'atac': 0,
'rna': 0,
'merfish': 0,
}
# across modality
cross_mod_distance_measure = 'correlation' # cca
knn = 20
relaxation = 3
n_cca = 30
# PCA
npc = 50
# clustering
k = 30
resolutions = [0.1, 0.2, 0.4, 0.8]
# umap
umap_neighbors = 60
min_dist = 0.5
| [
"fmxie1993@gmail.com"
] | fmxie1993@gmail.com |
8e0869aa2e541a6c21a734341235e05957391c2f | 102fe58b8e9f3e89a5574516f235571683671b3e | /accounting_pdf_reports/reports/report_partner_ledger.py | ac41d6a174dfca1199d91d8204475af0fc819da0 | [] | no_license | kri-odoo/KRISTINACERT | 5febe050d1a289f6b76873c5dfa419eba8b21f0d | 3650e5bde431513c24f87917be5e06b6b61a744c | refs/heads/main | 2023-04-05T04:37:30.888377 | 2021-03-23T17:28:31 | 2021-03-23T17:28:31 | 341,990,378 | 2 | 0 | null | 2021-03-23T18:09:41 | 2021-02-24T18:06:18 | HTML | UTF-8 | Python | false | false | 6,117 | py | # -*- coding: utf-8 -*-
import time
from odoo import api, models, _
from odoo.exceptions import UserError
class ReportPartnerLedger(models.AbstractModel):
_name = 'report.accounting_pdf_reports.report_partnerledger'
_description = 'Partner Ledger Report'
def _lines(self, data, partner):
full_account = []
currency = self.env['res.currency']
query_get_data = self.env['account.move.line'].with_context(data['form'].get('used_context', {}))._query_get()
reconcile_clause = "" if data['form']['reconciled'] else ' AND "account_move_line".full_reconcile_id IS NULL '
params = [partner.id, tuple(data['computed']['move_state']), tuple(data['computed']['account_ids'])] + query_get_data[2]
query = """
SELECT "account_move_line".id, "account_move_line".date, j.code, acc.code as a_code, acc.name as a_name, "account_move_line".ref, m.name as move_name, "account_move_line".name, "account_move_line".debit, "account_move_line".credit, "account_move_line".amount_currency,"account_move_line".currency_id, c.symbol AS currency_code
FROM """ + query_get_data[0] + """
LEFT JOIN account_journal j ON ("account_move_line".journal_id = j.id)
LEFT JOIN account_account acc ON ("account_move_line".account_id = acc.id)
LEFT JOIN res_currency c ON ("account_move_line".currency_id=c.id)
LEFT JOIN account_move m ON (m.id="account_move_line".move_id)
WHERE "account_move_line".partner_id = %s
AND m.state IN %s
AND "account_move_line".account_id IN %s AND """ + query_get_data[1] + reconcile_clause + """
ORDER BY "account_move_line".date"""
self.env.cr.execute(query, tuple(params))
res = self.env.cr.dictfetchall()
sum = 0.0
lang_code = self.env.context.get('lang') or 'en_US'
lang = self.env['res.lang']
lang_id = lang._lang_get(lang_code)
date_format = lang_id.date_format
for r in res:
r['date'] = r['date']
r['displayed_name'] = '-'.join(
r[field_name] for field_name in ('move_name', 'ref', 'name')
if r[field_name] not in (None, '', '/')
)
sum += r['debit'] - r['credit']
r['progress'] = sum
r['currency_id'] = currency.browse(r.get('currency_id'))
full_account.append(r)
return full_account
def _sum_partner(self, data, partner, field):
if field not in ['debit', 'credit', 'debit - credit']:
return
result = 0.0
query_get_data = self.env['account.move.line'].with_context(data['form'].get('used_context', {}))._query_get()
reconcile_clause = "" if data['form']['reconciled'] else ' AND "account_move_line".full_reconcile_id IS NULL '
params = [partner.id, tuple(data['computed']['move_state']), tuple(data['computed']['account_ids'])] + query_get_data[2]
query = """SELECT sum(""" + field + """)
FROM """ + query_get_data[0] + """, account_move AS m
WHERE "account_move_line".partner_id = %s
AND m.id = "account_move_line".move_id
AND m.state IN %s
AND account_id IN %s
AND """ + query_get_data[1] + reconcile_clause
self.env.cr.execute(query, tuple(params))
contemp = self.env.cr.fetchone()
if contemp is not None:
result = contemp[0] or 0.0
return result
@api.model
def _get_report_values(self, docids, data=None):
if not data.get('form'):
raise UserError(_("Form content is missing, this report cannot be printed."))
data['computed'] = {}
obj_partner = self.env['res.partner']
query_get_data = self.env['account.move.line'].with_context(data['form'].get('used_context', {}))._query_get()
data['computed']['move_state'] = ['draft', 'posted']
if data['form'].get('target_move', 'all') == 'posted':
data['computed']['move_state'] = ['posted']
result_selection = data['form'].get('result_selection', 'customer')
if result_selection == 'supplier':
data['computed']['ACCOUNT_TYPE'] = ['payable']
elif result_selection == 'customer':
data['computed']['ACCOUNT_TYPE'] = ['receivable']
else:
data['computed']['ACCOUNT_TYPE'] = ['payable', 'receivable']
self.env.cr.execute("""
SELECT a.id
FROM account_account a
WHERE a.internal_type IN %s
AND NOT a.deprecated""", (tuple(data['computed']['ACCOUNT_TYPE']),))
data['computed']['account_ids'] = [a for (a,) in self.env.cr.fetchall()]
params = [tuple(data['computed']['move_state']), tuple(data['computed']['account_ids'])] + query_get_data[2]
reconcile_clause = "" if data['form']['reconciled'] else ' AND "account_move_line".full_reconcile_id IS NULL '
query = """
SELECT DISTINCT "account_move_line".partner_id
FROM """ + query_get_data[0] + """, account_account AS account, account_move AS am
WHERE "account_move_line".partner_id IS NOT NULL
AND "account_move_line".account_id = account.id
AND am.id = "account_move_line".move_id
AND am.state IN %s
AND "account_move_line".account_id IN %s
AND NOT account.deprecated
AND """ + query_get_data[1] + reconcile_clause
self.env.cr.execute(query, tuple(params))
partner_ids = [res['partner_id'] for res in self.env.cr.dictfetchall()]
partners = obj_partner.browse(partner_ids)
partners = sorted(partners, key=lambda x: (x.ref or '', x.name or ''))
return {
'doc_ids': partner_ids,
'doc_model': self.env['res.partner'],
'data': data,
'docs': partners,
'time': time,
'lines': self._lines,
'sum_partner': self._sum_partner,
}
| [
"75452389+kri-odoo@users.noreply.github.com"
] | 75452389+kri-odoo@users.noreply.github.com |
5316d909ad741bbc04a75ff44c8e12b383a2a949 | 3e5b2eb741f5ae52752328274a616b475dbb401a | /services/nris-api/backend/app/config.py | 3eca18d43e5b1ffb47a603ac32051306f6a22b77 | [
"Apache-2.0"
] | permissive | bcgov/mds | 165868f97d0002e6be38680fe4854319a9476ce3 | 60277f4d71f77857e40587307a2b2adb11575850 | refs/heads/develop | 2023-08-29T22:54:36.038070 | 2023-08-29T05:00:28 | 2023-08-29T05:00:28 | 131,050,605 | 29 | 63 | Apache-2.0 | 2023-09-14T21:40:25 | 2018-04-25T18:54:47 | JavaScript | UTF-8 | Python | false | false | 5,830 | py | import os
from dotenv import load_dotenv, find_dotenv
class Config(object):
# Environment config
SECRET_KEY = os.environ.get('SECRET_KEY', 'dev')
BASE_PATH = os.environ.get('BASE_PATH', '')
DB_HOST = os.environ.get('DB_HOST', 'localhost')
DB_USER = os.environ.get('DB_USER', 'user')
DB_PASS = os.environ.get('DB_PASS', 'pass')
DB_PORT = os.environ.get('DB_PORT', 5432)
DB_NAME = os.environ.get('DB_NAME', 'db_name')
DB_URL = f"postgres://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
ENVIRONMENT_NAME = os.environ.get('ENVIRONMENT_NAME', 'dev')
# SqlAlchemy config
SQLALCHEMY_DATABASE_URI = DB_URL
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ENGINE_OPTIONS = {"pool_pre_ping": True}
JWT_OIDC_WELL_KNOWN_CONFIG = os.environ.get(
'JWT_OIDC_WELL_KNOWN_CONFIG',
'https://localhost:8080/auth/realms/mds/.well-known/openid-configuration')
JWT_OIDC_AUDIENCE = os.environ.get('JWT_OIDC_AUDIENCE', 'mds')
JWT_OIDC_ALGORITHMS = os.environ.get('JWT_OIDC_ALGORITHMS', 'RS256')
NRIS_DB_USER = os.environ.get('NRIS_DB_USER', 'localhost')
NRIS_DB_PASSWORD = os.environ.get('NRIS_DB_PASSWORD', 'localhost')
NRIS_DB_PORT = os.environ.get('NRIS_DB_PORT', 'localhost')
NRIS_DB_SERVICENAME = os.environ.get('NRIS_DB_SERVICENAME', 'localhost')
NRIS_DB_HOSTNAME = os.environ.get('NRIS_DB_HOSTNAME', 'localhost')
NRIS_SERVER_CERT_DN = os.environ.get('NRIS_SERVER_CERT_DN', 'localhost')
# Cache settings
CACHE_TYPE = os.environ.get('CACHE_TYPE', 'redis')
CACHE_REDIS_HOST = os.environ.get('CACHE_REDIS_HOST', 'redis')
CACHE_REDIS_PORT = os.environ.get('CACHE_REDIS_PORT', 6379)
CACHE_REDIS_PASS = os.environ.get('CACHE_REDIS_PASS', 'redis-password')
CACHE_REDIS_URL = 'redis://:{0}@{1}:{2}'.format(CACHE_REDIS_PASS, CACHE_REDIS_HOST,
CACHE_REDIS_PORT)
def JWT_ROLE_CALLBACK(jwt_dict):
return (jwt_dict.get('client_roles') or [])
class TestConfig(Config):
TESTING = os.environ.get('TESTING', True)
DB_NAME = os.environ.get('DB_NAME_TEST', 'db_name_test')
DB_URL = f"postgres://{Config.DB_USER}:{Config.DB_PASS}@{Config.DB_HOST}:{Config.DB_PORT}/{DB_NAME}"
SQLALCHEMY_DATABASE_URI = DB_URL
NRIS_DB_USER = os.environ.get('NRIS_DB_USER', 'localhost')
NRIS_DB_PASSWORD = os.environ.get('NRIS_DB_PASSWORD', 'localhost')
NRIS_DB_PORT = os.environ.get('NRIS_DB_PORT', 'localhost')
NRIS_DB_SERVICENAME = os.environ.get('NRIS_DB_SERVICENAME', 'localhost')
NRIS_DB_HOSTNAME = os.environ.get('NRIS_DB_HOSTNAME', 'localhost')
NRIS_SERVER_CERT_DN = os.environ.get('NRIS_SERVER_CERT_DN', 'localhost')
JWT_OIDC_TEST_MODE = True
JWT_OIDC_TEST_AUDIENCE = "test_audience"
JWT_OIDC_TEST_CLIENT_SECRET = "test_secret"
JWT_OIDC_TEST_ISSUER = "test_issuer"
# Dummy Private Keys for testing purposes, can replace these keys with any other generated key.
JWT_OIDC_TEST_KEYS = {
"keys": [{
"kid": "flask-jwt-oidc-test-client",
"kty": "RSA",
"alg": "RS256",
"use": "sig",
"n":
"AN-fWcpCyE5KPzHDjigLaSUVZI0uYrcGcc40InVtl-rQRDmAh-C2W8H4_Hxhr5VLc6crsJ2LiJTV_E72S03pzpOOaaYV6-TzAjCou2GYJIXev7f6Hh512PuG5wyxda_TlBSsI-gvphRTPsKCnPutrbiukCYrnPuWxX5_cES9eStR",
"e": "AQAB"
}]
}
# Dummy Private Keys for testing purposes.
JWT_OIDC_TEST_PRIVATE_KEY_JWKS = {
"keys": [{
"kid":
"flask-jwt-oidc-test-client",
"kty":
"RSA",
"alg":
"RS256",
"use":
"sig",
"kty":
"RSA",
"n":
"AN-fWcpCyE5KPzHDjigLaSUVZI0uYrcGcc40InVtl-rQRDmAh-C2W8H4_Hxhr5VLc6crsJ2LiJTV_E72S03pzpOOaaYV6-TzAjCou2GYJIXev7f6Hh512PuG5wyxda_TlBSsI-gvphRTPsKCnPutrbiukCYrnPuWxX5_cES9eStR",
"e":
"AQAB",
"d":
"C0G3QGI6OQ6tvbCNYGCqq043YI_8MiBl7C5dqbGZmx1ewdJBhMNJPStuckhskURaDwk4-8VBW9SlvcfSJJrnZhgFMjOYSSsBtPGBIMIdM5eSKbenCCjO8Tg0BUh_xa3CHST1W4RQ5rFXadZ9AeNtaGcWj2acmXNO3DVETXAX3x0",
"p":
"APXcusFMQNHjh6KVD_hOUIw87lvK13WkDEeeuqAydai9Ig9JKEAAfV94W6Aftka7tGgE7ulg1vo3eJoLWJ1zvKM",
"q":
"AOjX3OnPJnk0ZFUQBwhduCweRi37I6DAdLTnhDvcPTrrNWuKPg9uGwHjzFCJgKd8KBaDQ0X1rZTZLTqi3peT43s",
"dp":
"AN9kBoA5o6_Rl9zeqdsIdWFmv4DB5lEqlEnC7HlAP-3oo3jWFO9KQqArQL1V8w2D4aCd0uJULiC9pCP7aTHvBhc",
"dq":
"ANtbSY6njfpPploQsF9sU26U0s7MsuLljM1E8uml8bVJE1mNsiu9MgpUvg39jEu9BtM2tDD7Y51AAIEmIQex1nM",
"qi":
"XLE5O360x-MhsdFXx8Vwz4304-MJg-oGSJXCK_ZWYOB_FGXFRTfebxCsSYi0YwJo-oNu96bvZCuMplzRI1liZw"
}]
}
# Dummy Private Key, for testing purposes.
JWT_OIDC_TEST_PRIVATE_KEY_PEM = """
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDfn1nKQshOSj8xw44oC2klFWSNLmK3BnHONCJ1bZfq0EQ5gIfg
tlvB+Px8Ya+VS3OnK7Cdi4iU1fxO9ktN6c6TjmmmFevk8wIwqLthmCSF3r+3+h4e
ddj7hucMsXWv05QUrCPoL6YUUz7Cgpz7ra24rpAmK5z7lsV+f3BEvXkrUQIDAQAB
AoGAC0G3QGI6OQ6tvbCNYGCqq043YI/8MiBl7C5dqbGZmx1ewdJBhMNJPStuckhs
kURaDwk4+8VBW9SlvcfSJJrnZhgFMjOYSSsBtPGBIMIdM5eSKbenCCjO8Tg0BUh/
xa3CHST1W4RQ5rFXadZ9AeNtaGcWj2acmXNO3DVETXAX3x0CQQD13LrBTEDR44ei
lQ/4TlCMPO5bytd1pAxHnrqgMnWovSIPSShAAH1feFugH7ZGu7RoBO7pYNb6N3ia
C1idc7yjAkEA6Nfc6c8meTRkVRAHCF24LB5GLfsjoMB0tOeEO9w9Ous1a4o+D24b
AePMUImAp3woFoNDRfWtlNktOqLel5PjewJBAN9kBoA5o6/Rl9zeqdsIdWFmv4DB
5lEqlEnC7HlAP+3oo3jWFO9KQqArQL1V8w2D4aCd0uJULiC9pCP7aTHvBhcCQQDb
W0mOp436T6ZaELBfbFNulNLOzLLi5YzNRPLppfG1SRNZjbIrvTIKVL4N/YxLvQbT
NrQw+2OdQACBJiEHsdZzAkBcsTk7frTH4yGx0VfHxXDPjfTj4wmD6gZIlcIr9lZg
4H8UZcVFN95vEKxJiLRjAmj6g273pu9kK4ymXNEjWWJn
-----END RSA PRIVATE KEY-----"""
| [
"noreply@github.com"
] | bcgov.noreply@github.com |
6b627b68b15a32b93f2b8954a731967727cf0f25 | df6369a5788deb67909529799057ed752d9f0a6a | /druckfeder.py | 70835819d2f5257311de2a01fc28a01b5469f71c | [
"MIT"
] | permissive | reox/cupspring_calculator | 7d3e1bba7a91c719d7b9917ae3384645a1e310a7 | 32adcad3a6b6865742733d2fe73bb9a82383870b | refs/heads/master | 2020-06-10T06:17:31.301187 | 2017-08-28T12:10:32 | 2017-08-28T12:10:32 | 76,056,252 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 582 | py | #!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser(description='Druckfedern')
parser.add_argument('-d', type=float, help='Drahtdurchmesser')
parser.add_argument('-D', type=float, help='Áussendurchmesser')
parser.add_argument('-n', type=float, help='Windungen')
parser.add_argument('-L', type=float, help='enstpannte Länge')
args = parser.parse_args()
# Assume cold worked
n_t = args.n + 2
# Minimal Length: S_a + L_c = L_n
L_c = n_t * args.d
S_a = (0.0015 * (args.D ** 2 / args.d) + 0.1 * args.d) * args.n
print("minimale Länge: {}".format(L_c + S_a))
| [
"me@free-minds.net"
] | me@free-minds.net |
3c1e7add6c081f205dd8fc5b45407cb372444311 | 03add099b03a81f196c6376c29ddb3d6bc0f33a7 | /Atividade Continua 03/1282impacTube.py | 795187c037a448484c9c3b1fe6884e12bd06457e | [] | no_license | felipperodri/Impacta-ads1D-lp-uri | 4d4852490577b2fa416abe1e3cd1e9a2fa4704cc | 58a52305a223b382d5f2ccd6d36ba6ce1fa6e74a | refs/heads/main | 2023-09-03T15:40:32.309268 | 2021-10-19T17:01:54 | 2021-10-19T17:01:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 853 | py | n = int(input())
temp = []
tabela = []
for canais in range(1, n + 1):
nome, inscritos, monet, premium = input().split(";")
inscritos = int(inscritos)
monet = float(monet)
temp.extend([nome, inscritos, monet, premium])
temp.append(0)
tabela.append(temp)
temp = []
fixo1 = float(input())
fixo2 = float(input())
print(f'-----')
print(f'BÔNUS')
print(f'-----')
qtd_bonus = 0
for cont in range(len(tabela)):
qtd_bonus = 0
aux = tabela[cont][1]
while aux >= 1000:
aux -= 1000
qtd_bonus += 1
tabela[cont][4] = qtd_bonus
for i in range(len(tabela)):
if 'sim' in tabela[i]:
bonus = tabela[i][2] + (tabela[i][4] * fixo1)
print(f'{tabela[i][0]}: R$ {bonus:.2f}')
else:
bonus = tabela[i][2] + (tabela[i][4] * fixo2)
print(f'{tabela[i][0]}: R$ {bonus:.2f}') | [
"felipperodri@outlook.com"
] | felipperodri@outlook.com |
9b5e64bf554c4371804f8c6bd214ecb12aa4d700 | c797c2cf0de87f99ce67a5441d31950aab687bea | /15_flask-sess/app.py | 61285c7e94c021bb487bfb7b9e3e15ddd94571bd | [] | no_license | Saqif-Abedin/sabedin10 | 68135866623062aa0657d038362d18ab716bdb4a | 811874100cc2cd52068e58005e2258a8d3def06b | refs/heads/master | 2023-05-02T20:20:08.175971 | 2021-05-18T01:52:03 | 2021-05-18T01:52:03 | 298,570,595 | 0 | 0 | null | 2020-09-25T12:58:46 | 2020-09-25T12:46:36 | null | UTF-8 | Python | false | false | 1,557 | py | # Third Huge Freckled Elephant
# Ethan Shenker, Constance Chen, Andrew Jiang, Saqif Abedin
# K15 - Sessions Greetings
# 2020-12-12
from flask import Flask, render_template, request, session
import os
app = Flask(__name__)
app.secret_key = os.urandom(32)
username = "elephant"
password = "123pass"
@app.route("/")
def root():
if session.get('username'):
return render_template("welcome.html", user=session.get('username'))
else:
return render_template("login.html")
@app.route("/auth")
def auth():
if request.args['username'] == username and request.args['password'] == password:
session['username'] = request.args['username']
return render_template("confirm.html")
else:
if not request.args['username'] or not request.args['password']:
return render_template("error.html", error="Please input a valid username and password.")
elif request.args['username'] != username:
return render_template("error.html", error="Please input a valid username.")
elif request.args['password'] != password:
return render_template("error.html", error="Please input a valid password.")
return render_template("error.html", error="Something else went wrong, sorry.")
@app.route("/logout")
def logout():
session.pop('username')
return render_template("logout.html")
if __name__ == "__main__": #false if this file imported as module
#enable debugging, auto-restarting of server when this file is modified
app.debug = True
app.run() | [
"57577209+Saqif-Abedin@users.noreply.github.com"
] | 57577209+Saqif-Abedin@users.noreply.github.com |
4a6e91b943b782e5aa145a70215ce37d67232dbe | 5da3246edb630f99582cf14f869e052bcc2192b1 | /wordhelper.py | 6c56b5792aa3236607e36c655672e12b2fea6e53 | [] | no_license | neonfrontier/wordhelper | e388b7c0fbb38fe8c1262770da26cee3a8b725e5 | fdf34d6df796c40d9a16f28db67757f991d6ab94 | refs/heads/master | 2020-04-27T00:56:28.995602 | 2014-08-13T00:11:13 | 2014-08-13T00:11:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,428 | py | """This is a module to facilitate iterative reading of letters in a list of words based on certain parameters, and match them to all in the master list.
In other words, it's a crossword etc word helper/finder.
The word list is courtesy of: http://en.wikipedia.org/wiki/Moby_Project"""
print("This is a word finder app designed to help you on a crossword puzzle or something similar.")
print("Instructions: Enter total amount of letters, and we will go through each letter and enter any clues. Just press enter to go to the next letter, if you have none.")
print("DISCLAIMER: I am not responsible if this thing fails.")
#assign variable to master file of words
wordslist = open('master.txt')
master = list(wordslist)
#assign variable to number of letters needed
letter_amount = int(input("Enter total number of letters: "))
#declare a list for the purpose of storing selected words
temp_words = []
#declare the count variable here so it can be used outside of the for loop.
count = 0
#seek out words with above required length. assign those words to a list.
for line in master:
line = line.rstrip()
count = len(line)
if count == letter_amount:
temp_words.append(line)
#declare external list for using to store letters in the word.
chosen_letters = []
#declare var for number of real letters entered.
total_letters = 0
#enter variables to list according to length of the word.
for i in range(1, letter_amount+1):
c = input("Enter letter %s: " %i)
if c.isalpha():
chosen_letters.append(c)
total_letters += 1
elif c == '':
chosen_letters.append("0")
#create function that compares two lists of letters, giving total of matched letters.
def compare_letters(lista, listb):
pairs = 0
for i in range(min(len(lista), len(listb))):
if lista[i] == listb[i]:
pairs += 1
return pairs
#declare list for final words.
final_words = []
#split word list into letters, compare to letter list, append positive words to list.
for a in temp_words:
split_letters = list(a)
amount = compare_letters(chosen_letters, split_letters)
if amount == total_letters:
final_words.append(a)
#print final deduced words list.
#optional. display links to dictionary/wiki/google next to each word for added bonus of word meanings.
print("Printing potential words! Possible wiktionary links have also been made available:")
for i in final_words:
print(i+" ( link: "+"http://en.wiktionary.org/wiki/"+i+" )")
wordslist.close()
| [
"enu1985@gmail.com"
] | enu1985@gmail.com |
8e5e6f6b19be1be8b32832473d53ac0cc01adc08 | c5872ecd38eb53c808deee5614c3ad5a2370e36b | /ssb-drive.py | 960b1194b0fc9d3580cd04aa7d46ae74114c832e | [
"MIT"
] | permissive | cn-uofbasel/ssbdrv | b880f4bc1ccac1d5e96a626de07c979e09baab82 | 1f7e6b11373ef6f73415f0e9c62f1ade29739251 | refs/heads/master | 2020-03-27T20:22:58.335522 | 2018-09-07T21:18:05 | 2018-09-07T21:18:05 | 147,065,346 | 68 | 1 | null | null | null | null | UTF-8 | Python | false | false | 8,206 | py | #!/usr/bin/env python3
# ssb-drive.py
# 2018-08-31 (c) <christian.tschudin@unibas.ch>
import array
from asyncio import gather, ensure_future, Task, get_event_loop
from datetime import datetime
import sys
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.document import Document
from prompt_toolkit.eventloop import use_asyncio_event_loop
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.layout.containers import VSplit, HSplit
from prompt_toolkit.layout.layout import Layout
from prompt_toolkit.widgets import Label, TextArea, HorizontalLine
import logging
logger = logging.getLogger('packet_stream')
logger.setLevel(logging.INFO)
import ssb.adt.lfs
import ssb.app.drive
import ssb.peer.session
import ssb.local.config
import ssb.local.worm
# ---------------------------------------------------------------------------
# prompt_toolkit config:
use_asyncio_event_loop()
kb = KeyBindings()
@kb.add('c-q')
def _(event):
event.app.exit()
@kb.add('c-c')
def _(event):
event.app.cli.text = ''
@kb.add('c-l')
def _(event):
event.app.renderer.clear()
@kb.add('c-i')
def _(event):
event.app.layout.focus_next()
# ---------------------------------------------------------------------------
def make_app(fs):
global append_to_log
class PTK_STDOUT(): # our stdout
def __init__(self, out):
self.out = out
def write(self, s):
append(s, self.out)
return len(s)
def flush(self):
pass
class PTK_LOGGER(logging.StreamHandler):
def __init__(self, level=logging.NOTSET, out=None):
super().__init__(level)
self.out = out
def handle(self, record):
append(record.getMessage(), self.out)
def get_screen_size():
import fcntl
import termios
# Buffer for the C call
buf = array.array(u'h', [0, 0, 0, 0])
fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, buf)
return (buf[0], buf[1])
def my_on_resize(old_rs_handler, fs):
fill_top(fs)
return old_rs_handler()
# ----------------------------------------------------------------------
# prepare the layout
rows,_ = get_screen_size()
top = Label('', style='reverse')
log = TextArea(height=int((rows-4)/2), scrollbar=True)
out = TextArea(text='\n^c: clear input, ^l: redraw, ^q: quit\n',
scrollbar=True)
msg = Label('cwd is /', style='reverse')
cli_args = [] # for cli_accept(), filled later
def append(s, c=out):
if not c:
c.text += '\n---\n'
if c == log:
s = s.split('\n')[0][:get_screen_size()[1]-2] + '\n'
t = c.text + s
c.buffer.document = Document(text=t, cursor_position=len(t)-1)
def cli_accept(buf):
app, cli, fs = cli_args
append('\n---\n> ' + cli.text + '\n')
app.cmd.onecmd(cli.text)
msg.text = 'cwd is ' + fs.getcwd()
cli.buffer.history.append_string(cli.text)
cli.text = ''
def fill_top(fs):
s1 = ' SSB Drive' # (v20180831)'
s2 = '[uuid ' + fs.uuid() + '] '
w = get_screen_size()[1]
top.text = s1 + ' '*(w-len(s1)-len(s2)) + s2
cli = TextArea(multiline=False, accept_handler=cli_accept)
bot = VSplit([ Label('> ', dont_extend_width=True), cli ])
top_container = HSplit([ top,
log, HorizontalLine(),
out, msg, bot ])
app = Application(Layout(top_container), key_bindings=kb, full_screen=True)
cli_args += [app, cli, fs] # for cli_accept()
app.cli = cli # for retrieving it in the keyboard handler
app.layout.focus(cli)
fill_top(fs)
old_rs_resize = app._on_resize
app._on_resize = lambda : my_on_resize(old_rs_resize, fs)
app.stdout = PTK_STDOUT(out) # used for cmd
logging.getLogger('packet_stream').addHandler(PTK_LOGGER(out=log))
return app
# ---------------------------------------------------------------------------
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='SSB-Drive client')
parser.add_argument('-del', dest='delete', action='store_true',
help="del drive")
parser.add_argument('-list', action='store_true',
help='list all active drives')
parser.add_argument('-new', action='store_true',
help='create new drive ')
parser.add_argument('-peer', metavar='IP:PORT:ID',
help="remote's ip:port:id " + \
"(default is localhost:8008:default_id")
parser.add_argument('-port',
help="local port (i.e. become a server)")
parser.add_argument('-sync', action='store_true',
help="sync log and exit")
parser.add_argument('-tty', action='store_true',
help='run in line mode (instead of fullscreen terminal)')
parser.add_argument('-user', type=str, metavar='USERNAME', dest='username',
help='username (default is ~/.ssb user)')
parser.add_argument('-udel', action='store_true',
help="undelete drive")
parser.add_argument('uuid', type=str, metavar='UUID', nargs='?',
help="ssb-drive's uuid (default is youngest drive)")
args = parser.parse_args()
sess = ssb.peer.session.SSB_SESSION(args.username)
if args.sync:
if args.port:
print("** cannot be server for syncing, aborting")
else:
logger.addHandler(logging.StreamHandler())
theLoop = get_event_loop()
try:
theLoop.run_until_complete(ssb.peer.session.main(args, sess))
finally:
sess.worm.flush()
for t in Task.all_tasks():
t.cancel()
theLoop.close()
sys.exit(0)
if args.uuid:
ref = ssb.adt.lfs.get_lfs_by_uuid(sess.worm, args.uuid)
if not ref:
print("** no such drive")
sys.exit(0)
fs = ssb.adt.lfs.SSB_LFS(sess.worm, ref)
if args.udel:
print("** not implemented")
sys.exit(0)
if args.delete:
fs.close()
sess.worm.flush()
print("**", args.uuid, "was deleted")
sys.exit(0)
else:
if args.delete or args.udel:
print("** must specify a drive")
sys.exit(0)
if args.list:
print("Available SSB drives:")
for ref in ssb.adt.lfs.find_lfs_root_iter(sess.worm):
m = sess.worm.readMsg(ref[1])
t = datetime.utcfromtimestamp(m['value']['timestamp']/1000)
u = ssb.adt.lfs.uuid_from_key(sess.worm, ref[1])
print(" uuid=%s (%s)" % (u, str(t)[:19]))
sys.exit(0)
if args.new:
fs = ssb.adt.lfs.SSB_LFS(sess.worm)
sess.worm.flush()
print("** new drive created, uuid=" + fs.uuid())
sys.exit(0)
myroot = ssb.adt.lfs.find_lfs_mostRecent(sess.worm)
if not myroot:
print("** no drive found, aborting")
sys.exit(0)
fs = ssb.adt.lfs.SSB_LFS(sess.worm, myroot)
sess.worm.flush()
if args.tty:
d = ssb.app.drive.DRIVE_CMD(fs)
try:
d.cmdloop()
except KeyboardInterrupt:
print('^C')
sess.worm.flush()
else:
app = make_app(fs)
app.cmd = ssb.app.drive.DRIVE_CMD(fs, stdout=app.stdout,
prefetchBlob= lambda k: \
ensure_future(ssb.peer.session.fetch_blob(sess, k)))
theLoop = get_event_loop()
ensure_future(ssb.peer.session.main(args, sess))
try:
theLoop.run_until_complete(app.run_async().to_asyncio_future())
finally:
sess.worm.flush()
for t in Task.all_tasks():
t.cancel()
theLoop.close()
# eof
| [
"christian.tschudin@unibas.ch"
] | christian.tschudin@unibas.ch |
7283f193ecceac6428e1525188c272cfae1a4fd4 | 81d2e3b6fe042e70cc2abb7f549f60ba44928fdf | /nowcoder/company/0918-平安/02.py | 27e131270611e5cd79aafba5b6d5e0a7a36b61fb | [] | no_license | weizhixiaoyi/leetcode | a506faed3904342ed65234864df52071977d544d | 6114ebacc939f48a39a56d366646b0f28b4f6c1a | refs/heads/master | 2022-12-22T03:52:07.936800 | 2020-09-29T07:49:52 | 2020-09-29T07:49:52 | 202,662,720 | 5 | 2 | null | 2019-08-17T09:24:49 | 2019-08-16T05:16:08 | C++ | UTF-8 | Python | false | false | 1,064 | py | # -*- coding:utf-8 -*-
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# @param p float浮点型一维数组 第一个概率分布
# @param q float浮点型一维数组 四二个概率分布
# @return float浮点型
#
class Solution:
def cross_entropy(self, p, q):
# write code here
import math
nums_len = len(p)
sum = 0
hq = 0
for i in range(nums_len):
cur = -q[i] * math.log10(q[i])
hq += cur
hq = hq / 3
hpq = 0
for i in range(nums_len):
cur = -p[i] * math.log10(hq)
hpq += cur
hpq = hpq / 3
return hpq
if __name__ == '__main__':
p = [0, 0.5, 0.5]
q = [0.2, 0.2, 0.6]
# nums = input().split('],[')
# p, q = nums
# p = p.replace('[', '')
# q = q.replace(']', '')
# p = p.split(',')
# q = q.split(',')
# p = list(map(float, p))
# q = list(map(float, q))
ans = Solution().cross_entropy(p, q)
print(ans)
| [
"zhenhai.gl@gmail.com"
] | zhenhai.gl@gmail.com |
8dd33c1ba10039f3970d8ecca17789419a2127a2 | f9012c8e1d366b1158465604acf013b86632d02e | /42Gouraud/main.py | 3cde472a7885f922d7b13842d8d82f52ae79af20 | [] | no_license | pppppass/CGAssign | c549182dff10558c147c801a3979b2c1a73918c1 | 3c00238099bd355a1af706a5b6553c5ba6b92bfd | refs/heads/master | 2020-03-23T23:22:14.627296 | 2018-05-15T16:56:39 | 2018-05-15T16:56:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,494 | py | #! /usr/bin/env python3
import math
from time import time
import argparse
import numpy
import scipy.linalg
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
parser = argparse.ArgumentParser(description="Show comparision about different shading models, including Gouraud shading")
parser.add_argument("n", metavar="N", type=int, help="Number of iterations of subdivision")
args = parser.parse_args()
n = args.n
delta_angle = 0.05
view_matrix = numpy.eye(4)
light_pos = numpy.array([1.0, 1.0, 1.0, 1.0])
light_amb = numpy.array([0.5, 0.0, 0.0, 1.0])
light_diff = numpy.array([0.0, 0.0, 1.0, 1.0])
light_spec = numpy.array([0.0, 1.0, 0.0, 1.0])
mat_amb = numpy.array([0.2, 0.2, 0.2, 1.0])
mat_diff = numpy.array([0.8, 0.8, 0.8, 1.0])
mat_spec = numpy.array([1.0, 1.0, 1.0, 1.0])
mat_shin = numpy.array([20.0])
tetra_verts = [
numpy.array([0.0, 0.0, -1.0]),
numpy.array([0.0, 2.0*math.sqrt(2)/3.0, 1.0/3.0]),
numpy.array([-math.sqrt(6)/3.0, -math.sqrt(2)/3.0, 1.0/3.0]),
numpy.array([math.sqrt(6)/3.0, -math.sqrt(2)/3.0, 1.0/3.0]),
]
tetra_edges = [
[1, 2, 3],
[2, 3],
[3],
[]
]
tetra_surfs = []
tetra_norms = []
vert_norms = []
def sub_div():
global tetra_verts, tetra_edges
leng_lst = []
for i, lst in enumerate(tetra_edges):
leng_lst.append(len(tetra_verts))
for j in lst:
new_vert = tetra_verts[i] + tetra_verts[j]
new_vert /= numpy.linalg.norm(new_vert)
tetra_verts.append(new_vert)
new_edges = [[] for i in range(len(tetra_verts))]
for i, lst in enumerate(tetra_edges):
for j_ in range(len(lst)):
j = lst[j_]
for k_ in range(j_+1, len(lst)):
k = lst[k_]
if k not in tetra_edges[j]:
continue
ij, ik, jk = leng_lst[i] + j_, leng_lst[i] + k_, leng_lst[j] + tetra_edges[j].index(k)
new_edges[i].append(ij)
new_edges[i].append(ik)
new_edges[j].append(ij)
new_edges[j].append(jk)
new_edges[k].append(ik)
new_edges[k].append(jk)
new_edges[ij].append(ik)
new_edges[ij].append(jk)
new_edges[ik].append(jk)
for i in range(len(new_edges)):
new_edges[i] = list(set(new_edges[i]))
new_edges[i].sort()
tetra_edges = new_edges
def gen_surfs():
global tetra_surfs, vert_norms
vert_norms = [numpy.zeros(3) for i in range(len(tetra_verts))]
surf_ctrs = [0 for i in range(len(tetra_verts))]
for i, lst in enumerate(tetra_edges):
for j_ in range(len(lst)):
j = lst[j_]
for k_ in range(j_+1, len(lst)):
k = lst[k_]
if k not in tetra_edges[j]:
continue
normal = tetra_verts[i]
vi, vj, vk = (tetra_verts[t] for t in (i, j, k))
sign = numpy.dot(vi, numpy.cross(vj, vk))
if sign >= 0.0:
tetra_surfs.append((i, j, k))
else:
tetra_surfs.append((i, k, j))
norm = numpy.cross(vj - vi, vk - vi) * sign
norm /= numpy.linalg.norm(norm)
tetra_norms.append(norm)
for u in (i, j, k):
vert_norms[u] += norm
surf_ctrs[u] += 1
for i in range(len(tetra_verts)):
vert_norms[i] /= surf_ctrs[i]
def display():
glClear(GL_COLOR_BUFFER_BIT)
glClear(GL_DEPTH_BUFFER_BIT)
glEnable(GL_LIGHTING)
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glTranslated(-1.5, 0.0, 0.0)
glScaled(0.45, 0.45, 0.45)
set_lights()
glShadeModel(GL_FLAT)
glCallList(3)
glPopMatrix()
glPushMatrix()
glTranslated(-0.5, 0.0, 0.0)
glScaled(0.45, 0.45, 0.45)
set_lights()
glShadeModel(GL_SMOOTH)
glCallList(3)
glPopMatrix()
glPushMatrix()
glTranslated(0.5, 0.0, 0.0)
glScaled(0.45, 0.45, 0.45)
set_lights()
glCallList(4)
glPopMatrix()
glPushMatrix()
glTranslated(1.5, 0.0, 0.0)
glScaled(0.45, 0.45, 0.45)
set_lights()
glCallList(5)
glPopMatrix()
glDisable(GL_LIGHTING)
glCallList(1)
glPushMatrix()
glTranslated(*light_pos[:3])
glCallList(2)
glPopMatrix()
glutSwapBuffers()
glutPostRedisplay()
def initialize():
for i in range(n):
sub_div()
glEnable(GL_DEPTH_TEST)
glEnable(GL_BLEND)
glEnable(GL_LINE_SMOOTH)
glEnable(GL_POLYGON_SMOOTH)
glEnable(GL_LIGHT0)
glEnable(GL_NORMALIZE)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glClearColor(0.0, 0.0, 0.0, 1.0)
glClearDepth(1.0)
glPointSize(2.5)
glLineWidth(3.5)
glMatrixMode(GL_PROJECTION)
glOrtho(-2.0, 2.0, -2.0, 2.0, -2.0, 2.0)
gen_surfs()
def set_lights():
glLightfv(GL_LIGHT0, GL_POSITION, light_pos)
glLightfv(GL_LIGHT0, GL_AMBIENT, light_amb)
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diff)
glLightfv(GL_LIGHT0, GL_SPECULAR, light_spec)
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_amb)
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diff)
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_spec)
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shin)
def make():
glNewList(1, GL_COMPILE)
glBegin(GL_LINES)
glColor3d(0.3, 0.0, 0.0)
glVertex3d(-1.0, 0.0, 0.0)
glColor3d(1.0, 0.0, 0.0)
glVertex3d(1.0, 0.0, 0.0)
glColor3d(0.0, 0.3, 0.0)
glVertex3d(0.0, -1.0, 0.0)
glColor3d(0.0, 1.0, 0.0)
glVertex3d(0.0, 1.0, 0.0)
glColor3d(0.0, 0.0, 0.3)
glVertex3d(0.0, 0.0, -1.0)
glColor3d(0.0, 0.0, 1.0)
glVertex3d(0.0, 0.0, 1.0)
glColor3d(1.0, 1.0, 1.0)
glEnd()
glEndList()
glNewList(2, GL_COMPILE)
glColor3d(1.0, 1.0, 1.0)
glutSolidSphere(0.1, 20, 20)
glEndList()
glNewList(3, GL_COMPILE)
glBegin(GL_TRIANGLES)
for lst, norm in zip(tetra_surfs, tetra_norms):
glNormal3dv(norm)
for i in range(3):
glVertex3dv(tetra_verts[lst[i]])
glEnd()
glEndList()
glNewList(4, GL_COMPILE)
glBegin(GL_TRIANGLES)
for lst, norm in zip(tetra_surfs, tetra_norms):
for i in range(3):
glNormal3dv(vert_norms[lst[i]])
glVertex3dv(tetra_verts[lst[i]])
glEnd()
glEndList()
glNewList(5, GL_COMPILE)
glBegin(GL_TRIANGLES)
for lst, norm in zip(tetra_surfs, tetra_norms):
for i in range(3):
glNormal3dv(tetra_verts[lst[i]])
glVertex3dv(tetra_verts[lst[i]])
glEnd()
glEndList()
def redraw(w, h):
glutPostRedisplay()
def rotate(k, x, y):
global view_matrix
if k in {b'd', b'a', b'w', b's'}:
if k == b'd':
rot = scipy.linalg.expm(numpy.cross(
numpy.eye(3), numpy.array([0.0, -1.0, 0.0]) * delta_angle))
elif k == b'a':
rot = scipy.linalg.expm(numpy.cross(
numpy.eye(3), numpy.array([0.0, +1.0, 0.0]) * delta_angle))
elif k == b'w':
rot = scipy.linalg.expm(numpy.cross(
numpy.eye(3), numpy.array([+1.0, 0.0, 0.0]) * delta_angle))
elif k == b's':
rot = scipy.linalg.expm(numpy.cross(
numpy.eye(3), numpy.array([-1.0, 0.0, 0.0]) * delta_angle))
view_matrix[:3, :3] = view_matrix[:3, :3].dot(rot)
glMatrixMode(GL_MODELVIEW)
glLoadMatrixd(view_matrix)
elif k in {b'h', b'j', b'n', b'm'}:
if k == b'h':
rot = scipy.linalg.expm(numpy.cross(
numpy.eye(3), numpy.array([0.0, -1.0, 0.0]) * delta_angle))
elif k == b'j':
rot = scipy.linalg.expm(numpy.cross(
numpy.eye(3), numpy.array([0.0, +1.0, 0.0]) * delta_angle))
elif k == b'n':
rot = scipy.linalg.expm(numpy.cross(
numpy.eye(3), numpy.array([+1.0, 0.0, 0.0]) * delta_angle))
elif k == b'm':
rot = scipy.linalg.expm(numpy.cross(
numpy.eye(3), numpy.array([-1.0, 0.0, 0.0]) * delta_angle))
light_pos[:3] = rot.dot(light_pos[:3])
glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_ALPHA)
glutInitWindowSize(800, 800)
glutCreateWindow("Python Gouraud Shading")
glutDisplayFunc(display)
glutReshapeFunc(redraw)
glutKeyboardFunc(rotate)
initialize()
make()
glutMainLoop()
| [
"lzh2016p@pku.edu.cn"
] | lzh2016p@pku.edu.cn |
3b35f1ac431f0f9b548f5e57cf6eef5321337655 | d67f75664303b9b01642294de69b2e25cbce5601 | /api/schemas/match.py | 515dfda7e1b36cabc4c6e9acda28af73dc122581 | [] | no_license | ianwestfall/tourneyman-fast | a60d3a9ce1ef4157df092956d7b40516d972f4fd | 08ab62a5e5b9415608d27eeafdbf72d76199e61a | refs/heads/master | 2023-04-23T13:36:37.761333 | 2021-05-02T23:25:53 | 2021-05-02T23:25:53 | 294,995,934 | 0 | 0 | null | 2021-02-21T23:52:55 | 2020-09-12T17:46:04 | Python | UTF-8 | Python | false | false | 408 | py | from typing import Optional
from pydantic import BaseModel
from api.schemas.competitor import Competitor
class Match(BaseModel):
id: int
ordinal: int
competitor_1: Optional[Competitor]
competitor_1_score: Optional[int]
competitor_2: Optional[Competitor]
competitor_2_score: Optional[int]
next_match_id: Optional[int]
status: int
class Config:
orm_mode = True
| [
"ian.d.westfall@gmail.com"
] | ian.d.westfall@gmail.com |
7df91ac54c4e5eb6c3816105e95aa0dbb3414cae | 00a99462d65dc1fd950f9eab82e5139ddc211577 | /ZePMS/settings.py | a7001e45e7298cda64e6e6cd70605c3327e4c700 | [] | no_license | tkiran/ZePMS | 2cbf8d7f29b7ad01f59c9e6025080f0ef3d2cdb6 | fd221fd8c4c60ee667e726e524135a7ad952b4d7 | refs/heads/master | 2021-03-12T20:37:22.584514 | 2015-09-09T09:50:47 | 2015-09-09T09:50:47 | 42,112,432 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,635 | py | """
Django settings for ZePMS project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'j(3t&xmxr+m#k=$31sgzzi_u5zys+#u_g3t%v+^hlh3r=u(w#0'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'ZePMS.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ZePMS.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
| [
"tkiran@zeomega.com"
] | tkiran@zeomega.com |
e2a9622cde9d4a844a91ce9f7cb6c0aa4f350b1e | 93269e34160244fa3a61dc051def95a65f6e7569 | /Mark_2.py | 5e9d2f28a0156201f25dfb558b7e08f8add81e37 | [] | no_license | sgundu-doosratake/Python_Coding | 50e1959c640d6852d99d7cad95f27758c4c76c4e | 5faec8a4f11b3c5f4395ccb31915a459da023d2a | refs/heads/master | 2021-01-14T14:58:07.163661 | 2020-02-24T05:24:20 | 2020-02-24T05:24:20 | 242,653,194 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 46 | py | x=10
y=5
x=x+y
y=x-y
x=x-y
print(x)
print(y)
| [
"saith.kumar@doosratake.com"
] | saith.kumar@doosratake.com |
74aa7974e8e788af2a8feac8d6626b6188b7ba99 | 3ce4c8195136b758a6ca20c34ded458fb21843dc | /dataset/qqpy/tradehk.py | 45cb1544e0564592a0cd308567b0898c73f00d99 | [] | no_license | davischan3168/packages | 4f280d8b054f67189392919bce2f30f492e9bf2f | 2136958cf4560cc183b072d89b756fad60e306bb | refs/heads/master | 2020-04-15T15:47:31.880065 | 2019-08-26T11:42:08 | 2019-08-26T11:42:08 | 164,808,713 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,475 | py | #!/usr/bin/env python3
# -*-coding:utf-8-*-
"""
获得公司的基本信息和财务信息
"""
import requests,json
from io import StringIO
import re,sys,os
from bs4 import BeautifulSoup
import pandas as pd
import lxml.html
from lxml import etree
import datetime as dt
import webdata.puse.qqpy.cont as wt
from webdata.util.hds import user_agent as hds
#,start=1990,end=dt.datetime.today().year,mtype='bs')
def HK_trademin_qq(tick):
"""
获取某家上市公司的财务数据,资产负债表,利润表、现金流量表
-------------------------------
tick: 五位数的香港上市公司代码,如00005
--
return :
DataFrame
price:价格
volume:累计成交量
dvolume:5min 的成交量
"""
tick='hk%s'%tick
url='http://web.ifzq.gtimg.cn/appstock/app/hkMinute/query?_var=min_data_{0}&code={0}'.format(tick)
r=requests.get(url,headers=hds())
text=r.text.split("=")[1]
data=json.loads(text)
lines=data['data'][tick]['data']['data']
dataset=[]
for l in lines:
dataset.append(l.split(' '))
df=pd.DataFrame(dataset)
df.columns=['time','price','volume']
df['time']=df['time'].map(lambda x:'%s:%s'%(x[:2],x[2:]))
df=df.set_index('time')
df=df.applymap(lambda x:float(x))
df['dvolume']=df['volume'] - df['volume'].shift()
return df
if __name__=="__main__":
#tick='01203'
dd=HK_trademin_qq(sys.argv[1])
| [
"racheal123@163.com"
] | racheal123@163.com |
9bdf8ef6748e5a686675673fb78fcc28c5f0ecf9 | 927923c2c750525dece887b4064036b6c4516d1d | /neural_net_class.py | bc0fcbde449acc99bb21eb0c55aff1792469040b | [] | no_license | adikr24/nn_from_scratch | 0c9b65aef897fbb308fad5f39b8b71097c1cf85c | 83add350c9448069d123b0d5056701e7bca932ca | refs/heads/master | 2020-05-03T06:51:47.896948 | 2019-03-30T03:44:26 | 2019-03-30T03:44:26 | 178,483,897 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,366 | py | import math
import numpy as np
X1 = 5
X1= np.array([X1])
#W1= np.random.rand(X1.shape[0])
W1= np.array([0.3])
A1= W1.dot([X1])
y_pred= sigmoid(A1)
Error = y_act - y_pred
lr =0.005
print(y_pred,W1)
y_act=1
##################################class
#### 5 layer NN
import numpy as np
X= np.array([[3],[2]])
W1 = np.random.random((3,2))
A1= sigmoid(W1.dot(X))
W2= np.random.random((5,3))
A2= sigmoid(W2.dot(A1))
W3= np.random.random((3,5))
A3= sigmoid(W3.dot(A2))
W4 = np.random.random((2,3))
A4= sigmoid(W4.dot(A3))
W5= np.random.random((1,2))
Y_pred= sigmoid(W5.dot(A4))
Y_act= 1
## backprop
E= Y_act- Y_pred
DE_Y_pred = E * - Y_pred * sd(Y_pred)
DE_DW5 = DE_DY_pred * A4.T
DE_DA4= W5.T.dot(E * - Y_pred * sd(Y_pred)) * sd(A4)
DE_DW4= DE_DA4 * A3.T
assert(W4.shape ==DE_DW4.shape)
DE_DA3 = W4.T.dot(W5.T.dot(E * - Y_pred * sd(Y_pred)) * sd(A4)) *sd(A3)
DE_DW3= DE_DA3 * A2.T
DE_DA2 =W3.T.dot (W4.T.dot(E * -Y_pred *sd(Y_pred)*W5.T *sd(A4)) * sd(A3)) * sd(A2)
DE_DW2= DE_DA2 * A1.T
DE_DA1= W2.T.dot(W2.dot (W4.T.dot(E * -Y_pred *sd(Y_pred)*W5.T *sd(A4)) * sd(A3)) * sd(A2)) * sd(A1)
DE_DW1 =DE_DA1 * X.T
#### backprop_II
DE_Y_pred = E * - Y_pred *sd(Y_pred)
DE_DW5 = DE_DY_pred * A4.T
DE_DA4= W5.T.dot(DE_Y_pred)*sd(A4)
DE_DW4= DE_DA4 * A3.T
DE_DA3= W4.T.dot(DE_DA4)* sd(A3)
DE_DW3= DE_DA3* A2.T
DE_DA2= W3.T.dot(DE_DA3)*sd(A2)
DE_DW2 = DE_DA2 * A1.T
DE_DA1= W2.T.dot(DE_DA2) * sd(A1)
DE_Dw1= DE_DA1 * X.T
for i in range(10):
DE_Y_pred = E * - Y_pred *sd(Y_pred)
DE_DW5 = DE_Y_pred * A4.T
DE_DA4= W5.T.dot(DE_Y_pred)*sd(A4)
DE_DW4= DE_DA4 * A3.T
DE_DA3= W4.T.dot(DE_DA4)* sd(A3)
DE_DW3= DE_DA3* A2.T
DE_DA2= W3.T.dot(DE_DA3)*sd(A2)
DE_DW2 = DE_DA2 * A1.T
DE_DA1= W2.T.dot(DE_DA2) * sd(A1)
DE_DW1= DE_DA1 * X.T
W5 = W5 - lr * DE_DW5
W4 = W4- lr* DE_DW4
W3 = W3 - lr* DE_DW3
W2 = W2 - lr* DE_DW2
W1 = W1 - lr* DE_DW1
A1= sigmoid(W1.dot(X))
A2= sigmoid(W2.dot(A1))
A3= sigmoid(W3.dot(A2))
A4= sigmoid(W4.dot(A3))
A5= sigmoid(W5.dot(A4))
E= Y_act - A5
difference= abs(Y_act- A5)
print(E)
################################################################################
import numpy as np
class nn:
def __init__(self,input_layer, hidden_layer, output_size,Y_act,learning_rate):
self.input_layer= input_layer
self.hidden_layer = hidden_layer
self.output_size= output_size
self.Y_act= Y_act
self.weights_dict={}
self.act_layer= {}
self.backprop_A={}
self.backprop_W={}
self.learning_rate= learning_rate
def sigmoid(self,x):
return 1/(1+np.exp(-x))
def sd(self,x):
return self.sigmoid(x)* (1-self.sigmoid(x))
def initweights(self):
for i in range(len(self.hidden_layer)+1):
if i ==0:
ww= np.random.random((self.hidden_layer[i],self.input_layer.shape[0]))
self.weights_dict.update({'W'+str(i+1):ww})
elif i > 0:
try:
ww= np.random.random((self.hidden_layer[i],self.hidden_layer[i-1]))
self.weights_dict.update({'W'+str(i+1):ww})
except IndexError:
ww= np.random.random((self.output_size,self.hidden_layer[i-1]))
self.weights_dict.update({'W'+str(i+1):ww})
def activation(self):
for i in range(len(self.hidden_layer)+1):
if i==0:
A= self.weights_dict['W'+str(i+1)].dot(self.input_layer)
A= self.sigmoid(A)
self.act_layer.update({'A'+str(i):A})
elif i >0:
A = self.weights_dict['W'+str(i+1)].dot(self.act_layer['A'+str(i-1)])
A= self.sigmoid(A)
self.act_layer.update({'A'+str(i):A})
def error(self):
Y_pred=self.act_layer['A'+str(len(self.hidden_layer))]
E = self.Y_act - Y_pred
return abs(E)
def returnweights(self):
return self.weights_dict
def returnactive(self):
return self.act_layer
def backprop(self):
Y_pred= self.act_layer['A'+str(len(self.hidden_layer))]
E = self.Y_act-Y_pred
for i in range(len(self.hidden_layer),-1,-1):
if i == len(self.hidden_layer):
DE_DA= E*-Y_pred *self.sd(self.act_layer['A'+str(i)])
self.backprop_A.update({'DE_DA'+str(i):DE_DA})
elif i<len(hidden_layer):
try:
DE_DA = self.weights_dict['W'+str(i+2)].T.dot(self.backprop_A['DE_DA'+str(i+1)]) * sd(activation_l['A'+str(i)])
self.backprop_A.update({'DE_DA'+str(i):DE_DA})
except IndexError:
pass
for i in range(len(self.hidden_layer),-1,-1):
if i ==len(self.hidden_layer):
DE_DW = self.backprop_A['DE_DA'+str(i)] * self.act_layer['A'+str(i-1)].T
self.backprop_W.update({'DE_DW'+str(i+1):DE_DW})
elif i <= len(self.hidden_layer):
try:
DE_DW = self.backprop_A['DE_DA'+str(i)] * self.act_layer['A'+str(i-1)].T
self.backprop_W.update({'DE_DW'+str(i+1):DE_DW})
except KeyError:
DE_DW = self.backprop_A['DE_DA'+str(i)]*self.input_layer.T
self.backprop_W.update({'DE_DW'+str(i+1):DE_DW})
def updateweights(self):
for i in range(len(weights_dict)):
self.weights_dict['W'+str(i+1)] = self.weights_dict['W'+str(i+1)]- self.learning_rate * self.backprop_W['DE_DW'+str(i+1)]
def activation_updated(self):
return self.backprop_A
def return_weights(self):
return self.weights_dict
X=np.array([[1],[2]])
inputs=X
X.shape[0]
hidden_layer =[4,3,5,7,2]
output_size= 2
Y_act= [[1],[0]]
learning_rate= 0.05
mm = nn(X,hidden_layer,output_size,Y_act,learning_rate)
mm.initweights()
mm.activation()
weights_dict= mm.returnweights()
activation_l=mm.returnactive()
#mm.activation_updated()
for i in range(100):
mm.backprop()
mm.updateweights()
mm.activation()
print(mm.error())
#################################testing the neural net
#################################testing the neural net
| [
"akumar24@uncc.edu"
] | akumar24@uncc.edu |
56d685f07100b7f4a857869f14e4508ceab47e75 | 0ff6f0242176bc80a5165e4bba21999df20d59bc | /17_String ends with.py | 61fa89e8737f9d6bf917cebd5c29c0ff119a58f7 | [] | no_license | Martin-Schnebbe/Coding_Challenges | b2358188827ff41dbf648850e89b45b3d2d6d300 | 5df097b9aad48f38ca7f30bab486cbdec7760f69 | refs/heads/master | 2020-09-04T16:30:24.957870 | 2020-01-20T14:36:00 | 2020-01-20T14:36:00 | 219,802,619 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 148 | py | def solution(string, ending):
return string[len(string)-len(ending):] == ending
print(solution('abcde', 'cde'))
print(solution('abcde', 'abc')) | [
"martin.schnebbe@gmail.com"
] | martin.schnebbe@gmail.com |
970f2a170dcfb38b916b1907283370b221a1b0e0 | 129783d5c860eaea03c581d52f5efd41be0d8f59 | /main.py | 3fa256c73b8874a9a37cd2d6e694776cb6afe4d6 | [
"MIT"
] | permissive | msilvestro/dupin | 59b1206cc462f1ce81341cde1c124bac7b300220 | db06432cab6910c6965b9c35baaef96eb84f0d81 | refs/heads/main | 2023-04-14T07:53:24.227140 | 2021-04-28T22:23:07 | 2021-04-28T22:26:03 | 107,972,731 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,935 | py | """Extract the story graph of DoPPioGioco and perform some analysis."""
# pylint: disable=C0103
# %% Import all necessary modules.
from collections import defaultdict
import statistics
from interactive_story.dg_story_graph import DoppioGiocoStoryGraph
import matplotlib.pyplot as plt # to display plots
from IPython.display import HTML # to display HTML pages
doppiogioco = DoppioGiocoStoryGraph()
# %% Display the graph visually.
g = doppiogioco.get_graphviz_graph()
g.render('export/story_graph')
# %% Get all linear stories and show some statistics.
linear_stories = doppiogioco.get_linear_stories()
# %% Story number and story ends statistics.
print("Number of units:\t{}".format(len(doppiogioco.get_nodes())))
print("Number of stories:\t{}".format(len(linear_stories)))
print("Story beninnings:\t{}".format(len(doppiogioco.get_initial_units())))
print("Story endings:\t\t{}".format(len(doppiogioco.get_final_units())))
counts = defaultdict(int)
for story in linear_stories:
end = story[-1]
counts[end] += 1
plt.bar(range(len(counts)), counts.values(), align='center')
plt.xticks(range(len(counts)), counts.keys(), rotation='vertical')
# plt.title("Distribution of linear stories among possible endings")
plt.savefig('export/distr_endings.pdf')
plt.show()
# %% Story lengths statistics.
story_lengths = [len(story) for story in linear_stories]
print("Story length average:\t{}".format(statistics.mean(story_lengths)))
print("Story length mode:\t{}".format(statistics.mode(story_lengths)))
print("Story length max:\t{}".format(max(story_lengths)))
print("Story length min:\t{}".format(min(story_lengths)))
plt.hist(story_lengths, bins=range(5, 14), align='left', edgecolor='black')
# plt.title("Histogram of story lengths distribution")
plt.savefig('export/hist_lengths.pdf')
plt.show()
# %% Distribution of linear stories among units.
counts = defaultdict(int)
for story in linear_stories:
for unit in story:
counts[unit] += 1
plt.bar(range(len(counts)), counts.values(), align='center')
plt.xticks(range(len(counts)), counts.keys(), rotation='vertical')
plt.title("Distribution of linear stories among units")
plt.show()
# %% Analyze some tension curves.
# remove the first unit, since it is always the starting one, 000, and has
# no emotion associated (hence the first tension value will always be 0)
random_story = doppiogioco.get_random_story()[1:]
print(random_story)
tension_curve = doppiogioco.get_tension_curve_for_story(random_story)
print(tension_curve)
x_grid = range(len(tension_curve))
plt.plot(x_grid, tension_curve, ':o')
plt.grid(True)
plt.xticks(x_grid, random_story, rotation='vertical')
plt.yticks([-2, -1, 0, 1, 2])
plt.title("Tension curve of a random story")
plt.savefig('export/tension_curve.pdf')
plt.show()
# %% Display a random linear story.
random_story = doppiogioco.get_random_story()
HTML(doppiogioco.get_html_linear_story(random_story))
# %% Get all tension curves.
tension_curves = [doppiogioco.get_tension_curve_for_story(story)
for story in linear_stories]
# %% Write all linear stories in a text file.
stories_str = ""
for story in linear_stories:
stories_str += ','.join(story) + '\n'
with open('data/linear_stories.txt', 'w') as text_file:
text_file.write(stories_str)
# %% Write tension curves in a text file.
curves_str_full = "" # linear story and tension curve associated
curves_str = "" # only tension curves
# the first is mainly to check corrispondence between linear stories and
# tension curves
for i, story in enumerate(linear_stories):
curves_str_full += "{:};{:}\n".format(
','.join(story),
','.join(str(x) for x in tension_curves[i])
)
curves_str += ','.join(str(x) for x in tension_curves[i]) + '\n'
with open('data/tension_curves_full.txt', 'w') as text_file:
text_file.write(curves_str_full)
with open('data/tension_curves.txt', 'w') as text_file:
text_file.write(curves_str)
| [
"matteosilvestro@live.it"
] | matteosilvestro@live.it |
9e0dadddf8dcbe20c41a8217b3cf734f64324ffa | d069323121fc238a0d37c44ff831f30eaa12e8fe | /tjbot/template_helper.py | 07b26b90a50b94bec907affd354f45b7998484cf | [
"Apache-2.0"
] | permissive | m4scosta/TJBot | 6b6cf54ae7b48c191bdc90c4c5472637f69acc63 | e7e61bcfa892240aac0ca263e815bdf1d635436d | refs/heads/master | 2023-06-11T14:39:21.268913 | 2018-04-25T01:43:08 | 2018-04-25T01:43:08 | 79,977,725 | 0 | 0 | Apache-2.0 | 2021-07-02T08:14:15 | 2017-01-25T02:54:55 | Python | UTF-8 | Python | false | false | 415 | py | # coding: utf-8
from jinja2 import Template
from os import path
SRC_DIR = path.dirname(__file__)
TEMPLATE_DIR = path.join(SRC_DIR, 'templates')
def load_template(template_name):
with open(path.join(TEMPLATE_DIR, template_name)) as tpl:
return Template(tpl.read().decode('utf-8'))
def render(template_name, **kwargs):
template = load_template(template_name)
return template.render(**kwargs)
| [
"costa.marcos.pro@gmail.com"
] | costa.marcos.pro@gmail.com |
2ee57090f97077d485e3927207d18c1f25b34416 | 34cba926e11f19e91495bb6fa304d007a2fa1372 | /pandasProject.py | d4658efeb1a5747798a317035ef9d2da37c6128a | [] | no_license | Tirupathi123/myProject | 5e5e2d5c8a47cb676fb3202e7e3580e22732ba5b | 9f65f527ff26a956fba718a99d93c6348a8ce1ec | refs/heads/master | 2020-07-31T00:23:06.414441 | 2019-09-24T10:22:08 | 2019-09-24T10:22:08 | 210,415,173 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 699 | py | import pandas as pd
Data_frame=pd.read_csv('housing.csv')
a=Data_frame
#print(a) #to read and get all the dataframe
print('1 >',a.head(6)) #to get starting rows
print('2 >',a.tail(4)) #to get last rows
print('3 >',a[10:20]) #to get particular inBetween rows
print('4 >',a.price.mean()) #to get mean of particular int column values #df['salary'].mean()
print('5 >',a.bedrooms.dtype) #series #prints type of the column
print('6 >',a[['bedrooms','price']]) #data frame #prints particular columns
print('7 >',a.groupby('bedrooms')[['price']].mean())
print('8 >',a[a['price']<25000])
print('9 >',a.describe())
| [
"noreply@github.com"
] | Tirupathi123.noreply@github.com |
5b8834be26df45996be97bd6406f26e940bca6a3 | 6614eaf58b6dee7a45181b584d93e3697983ddd0 | /utils/sendEmail.py | 7075dd10fa43de42a173d94386bf0d8cdc18cf49 | [] | no_license | simon-Hero/WAF | efa5e066a732b711366c57678554487ba6ed88bd | f04197b7c53ee00d6a289f89bee858262fe48dc1 | refs/heads/main | 2023-06-09T10:07:43.598561 | 2021-07-02T11:05:24 | 2021-07-02T11:05:24 | 380,387,523 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,279 | py | import smtplib
import time
from email.header import Header
from email.mime.text import MIMEText
class SendEmail():
def send_email(self, new_report):
# 读取测试报告中的内容作为邮件的内容
with open(new_report, 'r', encoding='utf8') as f:
mail_body = f.read()
# 发件人地址
send_addr = '3381350680@qq.com'
# 收件人地址
reciver_addr = '3381350680@qq.com'
# 发送邮箱的服务器地址 qq邮箱是'smtp.qq.com', 136邮箱是'smtp.136.com'
mail_server = 'smtp.qq.com'
now = time.strftime("%Y-%m-%d %H_%M_%S")
# 邮件标题
subject = 'web自动化测试报告测试报告' + now
# 发件人的邮箱及邮箱授权码
username = '3381350680@qq.com'
password = '***' # 注意这里是邮箱的授权码而不是邮箱密码
# 邮箱的内容和标题
message = MIMEText(mail_body, 'html', 'utf8')
message['Subject'] = Header(subject, charset='utf8')
# 发送邮件,使用的使smtp协议
smtp = smtplib.SMTP()
smtp.connect(mail_server)
smtp.login(username, password)
smtp.sendmail(send_addr, reciver_addr.split(','), message.as_string())
smtp.quit()
| [
"2021037848@qq.com"
] | 2021037848@qq.com |
a3547f80e12607a57a895741736a1ed802ff72bb | 8b77caceda0387fb8c309e4768f0484dd796b5eb | /dev/TTSE/TimeComp.py | b812d2eda85af2e3bd86a1d25c3a0df14f94f9b7 | [
"MIT"
] | permissive | postmath/CoolProp | c51c70dfd5505e12c496bc49f4f639910d07113a | 4cb169ff6956268e8fa96c96dbddfe3b426a1bf4 | refs/heads/master | 2021-01-15T10:51:21.730069 | 2015-04-22T11:07:33 | 2015-04-22T11:07:33 | 34,334,674 | 0 | 0 | null | 2015-04-21T15:11:44 | 2015-04-21T15:11:44 | null | UTF-8 | Python | false | false | 66,979 | py | #!/usr/bin/python
# -*- coding: ascii -*-
#
from __future__ import print_function, division
import os, sys
from os import path
import numpy as np
import CoolProp
import glob
from warnings import warn
from time import clock
import CoolProp.constants
from CoolProp.CoolProp import PropsSI,generate_update_pair,get_parameter_index,set_debug_level,get_phase_index
from CoolProp import AbstractState as State
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import copy
from itertools import cycle
from matplotlib import gridspec, ticker
from jopy.dataPlotters import roundList, range_brace
try:
from jopy.dataPlotters import BasePlotter
bp = BasePlotter()
except:
bp = None
# The basic settings for he plots
xypoints = 1000
loops = 1
repeat = 1
runs = 0
maxruns = 100
plot = True
calc = False
check = False
folder = "dataDESKTOP"
figures = "figures"
#np.random.seed(1984)
fluids = ["CO2","Pentane","R134a","Water","Air","LiBr-0%"]
#glskeys = [r"\glsentryshort{co2}",r"\glsentryshort{pentane}",r"\glsentryshort{r134a}",r"\glsentryshort{water}",r"\glsentryshort{air}",r"\glsentryshort{libr} \SI{0}{\percent}"]
#glskeys = [r"\ce{CO2}",r"n-Ppentane",r"R134a",r"Water",r"Air",r"\glsentryshort{libr} \SI{0}{\percent}"]
repList = []
#for i in range(len(fluids)):
# repList.append(fluids[i])
# repList.append(glskeys[i])
backends = ["INCOMP","HEOS","REFPROP"]
#repList.append("HEOS")
#repList.append(r"\glsentryshort{cp}")
#repList.append("REFPROP")
#repList.append(r"\glsentryshort{rp}")
#CoolProp.CoolProp.set_debug_level(51)
pStr = path.dirname(path.abspath(__file__))
fStr = path.splitext(path.basename(__file__))[0]
def getFolderName():
folderName = path.join(pStr,folder)
if not path.isdir(folderName):
print("Creating data directory "+folderName)
os.makedirs(folderName)
return folderName
def getFigureFolder():
folderName = path.join(pStr,figures)
if not path.isdir(folderName):
print("Creating data directory "+folderName)
os.makedirs(folderName)
return folderName
repList.append("TimeComp-")
repList.append("chapters/FluidProperties/"+path.basename(getFigureFolder())+"/TimeComp-")
def getFileName(qualifiers=[]):
fileName = path.join(getFolderName(),"-".join(qualifiers))
return fileName
# Some file handling
def loadNpzData(backend,fluid):
dicts = {}
globber = getFileName([backend,fluid])+'_[0-9][0-9][0-9].npz'
for fname in glob.glob(globber):
dataDict = dict(np.load(fname))
dicts[str(dataDict["name"])] = dataDict
#if len(dicts)<1:
# #print("No readable file found for {0}".format(globber))
# dataDict = dict(name=str(0).zfill(3))
# dicts[str(dataDict["name"])] = dataDict
return dicts
def saveNpzData(backend,fluid,dicts,start=0,stop=-1):
keys = dicts.keys()
keys.sort()
for k in keys[start:stop]:
data = dicts[k]
fname = getFileName([backend,fluid])+'_{0}.npz'.format(str(data['name']).zfill(3))
np.savez(fname, **data)
return True
def splitFluid(propsfluid):
fld = propsfluid.split("::")
if len(fld)==2:
backend = fld[0]
fld = fld[1]
else:
backend = None
fld = fld[0]
fld = fld.split("-")
if len(fld)==2:
conc = float(fld[1].strip('%'))/100.0
fld = fld[0]
else:
conc = None
fld = fld[0]
return backend,fld,conc
def getInpList(backend):
if backend=="HEOS": return ["DT","HP"]
elif backend=="REFPROP": return ["DT","HP"]
elif backend=="INCOMP": return ["PT","HP"]
else: raise ValueError("Unknown backend.")
def getOutList(inp=None):
if inp == "HP":
return [["Tmax"],["D"],["S"],["T"],["D","S","T"]]
elif inp == "DT":
return [["Tmax"],["H"],["P"],["S"],["H","P","S"]]
elif inp == "PT":
return [["Tmax"],["H"],["D"],["S"],["H","D","S"]]
else:
raise ValueError("Unknown inputs.")
#def getPhaseString(iPhase):
# for i in range(11):
# if getPhaseString(i)==sPhase:
# return i
# if iPhase==1: return "liquid"
# elif iPhase==2: return "supercritical"
# elif iPhase==3: return "supercritical_gas"
# elif iPhase==4: return "supercritical_liquid"
# elif iPhase==5: return "critical_point"
# elif iPhase==6: return "gas"
# elif iPhase==7: return "twophase"
# elif iPhase==8: return "unknown"
# elif iPhase==9: return "not_imposed"
# else: raise ValueError("Couldn't find phase.")
def getPhaseNum(sPhase):
return get_phase_index(sPhase)
# for i in range(11):
# if getPhaseString(i)==sPhase:
# return i
def getOutKey(out): return "".join(out)
def getOutLabel(out): return ",".join(out)
def getTimeKey(inp,out): return "_".join([inp,getOutKey(out)])
def getVectorKey(inp,out): return getTimeKey(inp, out)+"_V"
def getCriticalProps(propsfluid):
backend,_,_ = splitFluid(propsfluid)
if backend!="INCOMP":
p_crit_m = PropsSI('pcrit',"T",0,"D",0,propsfluid) *0.995
T_crit_m = PropsSI('Tcrit',"T",0,"D",0,propsfluid) *1.005
d_crit_m = PropsSI('rhocrit',"T",0,"D",0,propsfluid)*0.995
h_crit_m = PropsSI('H',"T",T_crit_m,"D",d_crit_m,propsfluid)
s_crit_m = PropsSI('H',"T",T_crit_m,"D",d_crit_m,propsfluid)
else:
p_crit_m = None
T_crit_m = None
d_crit_m = None
h_crit_m = None
s_crit_m = None
return dict(P=p_crit_m,T=T_crit_m,D=d_crit_m,H=h_crit_m,S=s_crit_m)
def getPTRanges(propsfluid):
backend,_,_ = splitFluid(propsfluid)
# Setting the limits for enthalpy and pressure
if backend == "REFPROP":
T_min = PropsSI('Ttriple',"T",0,"D",0,propsfluid)
T_max = PropsSI( 'Tmax',"T",0,"D",0,propsfluid)
p_min = PropsSI( 'P',"T",T_min,"Q",0,propsfluid)
p_max = PropsSI( 'pmax',"T",0,"D",0,propsfluid)
elif backend == "INCOMP":
T_min = PropsSI('Tmin',"T",0,"D",0,propsfluid)
T_max = PropsSI('Tmax',"T",0,"D",0,propsfluid)
p_min = 1.5*1e5
p_max = 200.0*1e5
else:
p_min = PropsSI('ptriple',"T",0,"D",0,propsfluid)
p_max = PropsSI( 'pmax',"T",0,"D",0,propsfluid)
T_min = PropsSI('Ttriple',"T",0,"D",0,propsfluid)
T_max = PropsSI( 'Tmax',"T",0,"D",0,propsfluid)
p_range = np.logspace(np.log10(p_min),np.log10(p_max),xypoints)
T_range = np.linspace(T_min,T_max,xypoints)
return p_range,T_range
#p_max = min(PropsSI('pcrit',"T",0,"D",0,fluid)*20, p_max)
#T_max = min(PropsSI('Tcrit',"T",0,"D",0,fluid)* 3, T_max)
def getLists(propsfluid):
backend,_,_ = splitFluid(propsfluid)
"""Returns randomised lists of all properties within the ranges"""
p,T = getPTRanges(propsfluid)
p_min = np.min(p)
p_max = np.max(p)
T_min = np.min(T)
T_max = np.max(T)
if backend=="INCOMP":
h_min = PropsSI('H','T',T_min,'P',p_min,propsfluid)
h_max = PropsSI('H','T',T_max,'P',p_max,propsfluid)
else:
critProps = getCriticalProps(propsfluid)
h_min = PropsSI('H','T',T_min,'Q',0,propsfluid)
h_max = PropsSI('H','T',T_min,'Q',1,propsfluid)
h_max = max(PropsSI('H','T',critProps["T"],'D',critProps["D"],propsfluid),h_max)
h_max = (h_max-h_min)*2.0+h_min
loop = True
count = 0
while loop:
count += 1
h_list = np.random.uniform( h_min, h_max,int(xypoints*2.0))
p_list = np.random.uniform(np.log10(p_min),np.log10(p_max),int(xypoints*2.0))
p_list = np.power(10,p_list)
out = ["T","D","S"]
res = PropsSI(out,"P",p_list,"H",h_list,propsfluid)
T_list = res[:,0]
d_list = res[:,1]
s_list = res[:,2]
mask = np.isfinite(T_list) & np.isfinite(d_list) & np.isfinite(s_list)
if np.sum(mask)<xypoints:
if False:
print(h_list); print(p_list); print(T_list); print(d_list); print(s_list)
print("There were not enough valid entries in your result vector: {0:d} > {1:d} - rerunning".format(xypoints,np.sum(mask)))
loop = True
else:
loop = False
p_list = p_list[mask][0:xypoints]
h_list = h_list[mask][0:xypoints]
T_list = T_list[mask][0:xypoints]
d_list = d_list[mask][0:xypoints]
s_list = s_list[mask][0:xypoints]
return dict(P=p_list,T=T_list,D=d_list,H=h_list,S=s_list)
maxTries = 4
if count > maxTries:
loop = False
raise ValueError("{0}: Could not fill the lists in {0} runs, aborting.".format(propsfluid,maxTries))
def getInpValues(inp,dataDict):
in1 = inp[0]
in2 = dataDict[in1]
in3 = inp[1]
in4 = dataDict[in3]
return in1,in2,in3,in4
def getStateObj(propsfluid):
backend,fld,conc = splitFluid(propsfluid)
# fluidstr holds the full information and fluid is only the name
# Initialise the state object
if backend is not None:
state = State(backend,fld)
else:
state = State(fld)
#if backend=="INCOMP":
# state.set_mass_fractions([0.0])
if conc is not None:
state.set_mass_fractions([conc])
return state
def getSpeedMeas(out,in1,in2,in3,in4,propsfluid,vector=False):
pair, out1, _ = generate_update_pair(get_parameter_index(in1),in2[0],get_parameter_index(in3),in4[0])
if out1==in2[0]: swap=False
else: swap=True
if swap:
input1 = in4
input2 = in2
else:
input1 = in2
input2 = in4
state = getStateObj(propsfluid)
outList = [get_parameter_index(i) for i in out]
resLst = np.empty((repeat,))
timLst = np.empty((repeat,))
if vector:
for j in range(repeat):
timLst.fill(np.inf)
lrange = range(len(input1))
resTmp = np.inf
if len(outList)==1 and outList[0]==CoolProp.constants.iT_max:
t1=clock()
for l in lrange:
for o in outList:
resTmp = state.keyed_output(o)
t2=clock()
timLst[j] = (t2-t1)*1e6/float(len(input1))
else: # We have to update before doing other things
t1=clock()
for l in lrange:
state.update(pair,input1[l],input2[l])
for o in outList:
resTmp = state.keyed_output(o)
t2=clock()
timLst[j] = (t2-t1)*1e6/float(len(input1))
res = None
tim = np.min(timLst) # Best of (repeat)
return res,tim
else:
res = np.empty_like(input1)
res.fill(np.inf)
tim = np.empty_like(input1)
tim.fill(np.inf)
for i in range(len(input1)):
resLst.fill(np.inf)
timLst.fill(np.inf)
for j in range(repeat):
lrange = range(loops)
resTmp = np.inf
if len(outList)==1 and outList[0]==CoolProp.constants.iT_max:
t1=clock()
for _ in lrange:
for o in outList:
resTmp = state.keyed_output(o)
t2=clock()
timLst[j] = (t2-t1)*1e6/float(loops)
resLst[j] = resTmp
else: # We have to update before doing other things
inV1 = input1[i]
inV2 = input2[i]#*(1.0+(l/1000.0)*pow(-1,l)) for l in lrange ]
t1=clock()
for l in lrange:
state.update(pair,inV1,inV2)
for o in outList:
resTmp = state.keyed_output(o)
t2=clock()
timLst[j] = (t2-t1)*1e6/float(loops)
resLst[j] = resTmp
if not np.all(resLst==resLst[0]):
raise ValueError("Not all results were the same.")
res[i] = resLst[0]
tim[i] = np.min(timLst) # Best of three (repeat)
return res,tim
def checkDataSet(propsfluid,dataDict,fill=True,quiet=False):
if not check: return
backend,_,_ = splitFluid(propsfluid)
if not quiet: print("\n\n-- {0:16s} --".format(propsfluid),end="")
# Test for required inputs
newInputs = False
inLists = getLists(propsfluid)
for inp in getInpList(backend):
if not quiet: print("\n{0:2s}: ".format(inp),end="")
for inVal in inp:
if inVal not in dataDict: # A problem
if not fill:
raise ValueError("The input {0:1s} is missing or faulty, cannot continue.".format(inVal))
#dataDict[inVal] = inLists[inVal]
dataDict.update(inLists)
newInputs = True
if not quiet: print("{0:s}*({1:d}),".format(inVal,len(dataDict[inVal])),end="")
else:
if not quiet: print("{0:s} ({1:d}),".format(inVal,len(dataDict[inVal])),end="")
# All inputs are there
in1,in2,in3,in4 = getInpValues(inp,dataDict)
#in2 = in2[:3]
#in4 = in4[:3]
if in2.shape != in4.shape:
raise ValueError("The stored data for {0:s} and {1:s} do not have the same shape.".format(in1,in3))
if in2.shape != inLists[in1].shape:
raise ValueError("The stored data for {0:s} and its list do not have the same shape {1} vs {2}.".format(in1,in2.shape,inLists[in1].shape))
# Check for time data
for out in getOutList(inp):
key = getTimeKey(inp, out)
okey = getOutKey(out)
if key not in dataDict or newInputs or not np.all(np.isfinite(dataDict[key])):
if not fill:
raise ValueError("The time data for {0:s} is missing or faulty, cannot continue.".format(key))
res,tim = getSpeedMeas(out, in1, in2, in3, in4, propsfluid)
dataDict[key] = tim
dataDict[okey] = res # We calculated in, why not use it here...
if not quiet: print("{0:s}*({1:d}),".format(key,len(dataDict[key])),end="")
else:
if not quiet: print("{0:s} ({1:d}),".format(key,len(dataDict[key])),end="")
if dataDict[key].shape != in2.shape or not np.all(np.isfinite(dataDict[key])):
raise ValueError("The stored time data for {0:s} does not have the same shape as the inputs.".format(key))
# Check for vectors
for out in getOutList(inp):
key = getVectorKey(inp, out)
if key not in dataDict or not np.all(np.isfinite(dataDict[key])):
if not fill:
raise ValueError("The fluid data for {0:s} is missing or faulty, cannot continue.".format(key))
res,tim = getSpeedMeas(out, in1, in2, in3, in4, propsfluid, vector=True)
dataDict[key] = tim
if not quiet: print("{0:s}*({1:d}),".format(key,dataDict[key].size),end="")
else:
if not quiet: print("{0:s} ({1:d}),".format(key,dataDict[key].size),end="")
if dataDict[key].size!=1 or not np.all(np.isfinite(dataDict[key])):
raise ValueError("The vector data for {0:s} does not have the correct size {1}..".format(key,dataDict[key].size))
# inp = getInpList(backend)[0] # Explicit calls
# # Check for properties
# for out in getOutList(inp)[:-1]:
# key = getOutKey(out)
# if key not in dataDict or not np.all(np.isfinite(dataDict[key])):
# if not fill:
# raise ValueError("The fluid data for {0:s} is missing or faulty, cannot continue.".format(key))
# res = PropsSI(out,in1,in2,in3,in4,propsfluid)
# dataDict[key] = res
# if not quiet: print("{0:s}*({1:d}),".format(key,len(dataDict[key])),end="")
# else:
# if not quiet: print("{0:s} ({1:d}),".format(key,len(dataDict[key])),end="")
# if dataDict[key].shape != in2.shape or not np.all(np.isfinite(dataDict[key])):
# raise ValueError("The stored data for {0:s} does not have the same shape as the inputs {1} vs {2}..".format(key,dataDict[key].shape,in2.shape))
# # Check for phase
# for out in ["Phase"]:
# if backend!="HEOS":
# dataDict[key] = np.zeros_like(a, dtype, order, subok)
# key = getOutKey(out)
# if key not in dataDict or newInputs or not np.all(np.isfinite(dataDict[key])):
# if not fill:
# raise ValueError("The phase data for {0:s} is missing or faulty, cannot continue.".format(key))
# res = np.empty_like(in2)
# res.fill(np.inf)
# for i in range(len(in2)):
# res[i] = PropsSI(out,in1,in2[i],in3,in4[i],propsfluid)
# dataDict[key] = res
# if not quiet: print("{0:s}*({1:d}),".format(key,len(dataDict[key])),end="")
# else:
# if not quiet: print("{0:s} ({1:d}),".format(key,len(dataDict[key])),end="")
# if dataDict[key].shape != in2.shape or not np.all(np.isfinite(dataDict[key])):
# raise ValueError("The stored data for {0:s} does not have the same shape as the inputs {1} vs {2}..".format(key,dataDict[key].shape,in2.shape))
#
# # Now we use the vector data
# key = getVectorKey(inp, out)
# if key not in dataDict or not np.all(np.isfinite(dataDict[key])):
# if not fill:
# raise ValueError("The vector data for {0:s} is missing or faulty, cannot continue.".format(key))
# dataDict[key] = np.empty_like(in2)
# dataDict[key].fill(np.inf)
# res = []
# for _ in range(repeat):
# t1=clock()
# PropsSI(out,in1,in2,in3,in4,propsfluid)
# t2=clock()
# res.append((t2-t1)/float(len(in2)))
# dataDict[key] = np.min(res)
# if not quiet: print("{0:s}*({1}),".format(key,dataDict[key]),end="")
# else:
# if not quiet: print("{0:s} ({1}),".format(key,dataDict[key]),end="")
# try:
# float(dataDict[key])
# except:
# raise ValueError("The stored vector data for {0:s} cannot be casted to float.".format(key))
# if not quiet: print("")
# All data is loaded and checked, we can calculate more now
def getEntryCount(dicts,backend,fld):
return len(fluidData[fld][backend].keys())
def getUKey(fld,bck,inp,out):
return "-".join([fld,bck,inp,"".join(out)])
def getData(fld,backend,inp,out,fluidData):
inputs1 = []
inputs2 = []
values = []
times = []
i1key = inp[0]
i2key = inp[1]
vkey = getOutKey(out)
tkey = getTimeKey(inp,out)
for dkey in fluidData[fld][backend]:
cData = fluidData[fld][backend][dkey]
inputs1.append(cData[i1key])
inputs2.append(cData[i2key])
values.append( cData[vkey] )
times.append( cData[tkey] )
ret = {}
if len(inputs1)>0:
ret[i1key] = np.concatenate(inputs1)
ret[i2key] = np.concatenate(inputs2)
ret[vkey] = np.concatenate(values )
ret[tkey] = np.concatenate(times )
return ret
def getSingleData(fld,backend,key,fluidData):
#print("Getting: "+fld+", "+backend+", "+key)
values = []
for dkey in fluidData[fld][backend]:
if key in fluidData[fld][backend][dkey]:
if "P" in fluidData[fld][backend][dkey]:
# TODO: Fix this, do we need the mask?
#mask = fluidData[fld][backend][dkey]["P"]>0.3e5
mask = fluidData[fld][backend][dkey]["P"]>0.3e5
try:
values.append( fluidData[fld][backend][dkey][key][mask] )
except Exception as e:
values.append( fluidData[fld][backend][dkey][key] )
print(e)
pass
else:
values.append( fluidData[fld][backend][dkey][key] )
if len(values)>0:
if np.size(values[0])>1:
return np.concatenate(values)
else:
return np.array(values)
return None
def fillDict(fld,backend,fluidData,curDict,curKeys):
if curDict is None: curDict = {}
for key in curKeys:
vals = getSingleData(fld, backend, key, fluidData)
if vals is not None: curDict[key] = vals
return curDict
################################################
fluidData = {}
for fluidstr in fluids:
_,fld,_ = splitFluid(fluidstr)
if fld not in fluidData: fluidData[fld] = {}
for backend in backends:
if backend not in fluidData[fld]: # Try to add it
propsfluid = "::".join([backend,fluidstr])
try:
PropsSI('Tmax',"T",0,"D",0,propsfluid)
fluidData[fld][backend] = loadNpzData(backend,fld)
except:
pass
if backend in fluidData[fld]:
for k in fluidData[fld][backend]:
checkDataSet(propsfluid, fluidData[fld][backend][k], fill=False, quiet=True)
else: # Already added backend for fluid
pass
lastSave = 0
while runs<maxruns and calc:
check = True # force checking for new records
runs +=1
# Now we have the data structure with the precalculated data
for fluidstr in fluids:
_,fld,_ = splitFluid(fluidstr)
for backend in fluidData[fld]:
propsfluid = "::".join([backend,fluidstr])
dicts = fluidData[fld][backend]
keys = list(dicts.keys())
keys.sort()
while len(keys)<runs:
if len(keys)<1: newKey = 0
else: newKey = int(keys[-1])+1
if newKey>999:
raise ValueError("Too many dicts: {0}>999".format(newKey))
k = str(newKey).zfill(3)
dicts[k] = {}
dicts[k]['name']=k
try:
checkDataSet(propsfluid, dicts[k], fill=True, quiet=False)
except Exception as e:
print("There was an error, dataset {0} from {1}.might be faulty:\n{2}".format(k,propsfluid,str(e)))
pass
todel = []
#for k in dicts:
try:
checkDataSet(propsfluid, dicts[k], fill=False, quiet=True)
except Exception as e:
print("There was an error, removing dataset {0} from {1}.\n{2}".format(k,propsfluid,str(e)))
todel.append(k)
for t in todel: del dicts[t]
keys = list(dicts.keys())
keys.sort()
# Updated all dicts for this backend, saving data
if runs>=maxruns or (lastSave+4)<runs:
print("\n\nDone processing fluids, saving data: ")
for fld in fluidData:
for backend in fluidData[fld]:
saveNpzData(backend, fld, fluidData[fld][backend], start=lastSave, stop=runs)
print("{0} ({1})".format(backend+"::"+fld,len(fluidData[fld][backend].keys()[lastSave:runs])),end=", ")
print("")
lastSave = runs
if not plot: sys.exit(0)
# exclLst = [["Tmax"],["H"],["D"],["S"],["H","D","S"],["D"],["S"],["T"],["D","S","T"]]
#
### Start with a temporary dictionary that holds all the data we need
# for fld in fluidData:
# cstData = {} # Data from calls to constants (overhead)
# expData = {} # Data from explicit EOS calls
# impData = {} # Data from EOS calls that require iterations
# for backend in fluidData[fld]:
#
# curKeys = []
# for inp in getInpList(backend):
# for out in getOutList(inp)[:1]:
# curKeys.append(getTimeKey( inp, out))
# curKeys.append(getVectorKey(inp, out))
# curDict = {}
# fillDict(fld,backend,fluidData,curDict,curKeys)
# cstData[backend] = curDict
#
# curKeys = []
# for inp in getInpList(backend)[:1]:
# for out in getOutList(inp)[1:]:
# curKeys.append(getTimeKey( inp, out))
# curKeys.append(getVectorKey(inp, out))
# curDict = {}
# fillDict(fld,backend,fluidData,curDict,curKeys)
# expData[backend] = curDict
#
# curKeys = []
# for inp in getInpList(backend)[1:]:
# for out in getOutList(inp)[1:]:
# curKeys.append(getTimeKey( inp, out))
# curKeys.append(getVectorKey(inp, out))
# curDict = {}
# fillDict(fld,backend,fluidData,curDict,curKeys)
# impData[backend] = curDict
# curDict[backend] = {}
# for key in :
# vals = getSingleData(fld, backend, key, fluidData)
# if vals is not None: curDict[backend][key] = vals
# if curDict
#
# cstData[backend] = {}
# for out in getOutList(inp[0])[0]:
# res = getData(fld,backend,inp[0],out,fluidData)
# cstData[backend].update(res)
# for out in getOutList(inp[1])[0]:
# res = getData(fld,backend,inp[1],out,fluidData)
# cstData[backend].update
#
# expData[backend] = {}
# for out in getOutList(inp[0])[1:]:
# res = getData(fld,backend,inp[0],out,fluidData)
# expData[backend].update(res)
#
# impData[backend] = {}
# for out in getOutList(inp[1])[1:]:
# res = getData(fld,backend,inp[1],out,fluidData)
# impData[backend].update(res)
#############################################################
# All data is available in the dicts now.
#############################################################
# The first thuing to do is to print some statistical
# measures to give you an idea about the data.
# try:
# #dataOHCP = [cstData["HEOS"]["DT_Tmax"] , cstData["HEOS"]["HP_Tmax"] ]
# #dataOHRP = [cstData["REFPROP"]["DT_Tmax"], cstData["REFPROP"]["HP_Tmax"]]
# print("\n{0} - {1} points ".format(fld,np.size(cstData["HEOS"]["DT_Tmax"])))
# print("Overhead CoolProp: {0:5.3f} us".format(np.mean(cstData["HEOS"]["DT_Tmax"])))#, np.mean(cstData["HEOS"]["HP_Tmax"]))
# print("Overhead REFPROP : {0:5.3f} us".format(np.mean(cstData["REFPROP"]["DT_Tmax"])))#,np.mean(cstData["REFPROP"]["HP_Tmax"]))
# print("Mean EOS in CoolProp: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.mean(expData["HEOS"]["DT_HPS"]),np.mean(impData["HEOS"]["HP_DST"])))
# print("Std. dev. in CoolProp: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.std(expData["HEOS"]["DT_HPS"]) ,np.std(impData["HEOS"]["HP_DST"])))
# print("Minimum in CoolProp: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.min(expData["HEOS"]["DT_HPS"]) ,np.min(impData["HEOS"]["HP_DST"])))
# print("Maximum in CoolProp: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.max(expData["HEOS"]["DT_HPS"]) ,np.max(impData["HEOS"]["HP_DST"])))
# print("Mean EOS in REFPROP: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.mean(expData["REFPROP"]["DT_HPS"]),np.mean(impData["REFPROP"]["HP_DST"])))
# print("Std. dev. in REFPROP: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.std(expData["REFPROP"]["DT_HPS"]) ,np.std(impData["REFPROP"]["HP_DST"])))
# print("Minimum in REFPROP: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.min(expData["REFPROP"]["DT_HPS"]) ,np.min(impData["REFPROP"]["HP_DST"])))
# print("Maximum in REFPROP: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.max(expData["REFPROP"]["DT_HPS"]) ,np.max(impData["REFPROP"]["HP_DST"])))
# print("")
#
# print("\n{0} - {1} points ".format(fld,np.size(cstData["HEOS"]["DT_Tmax_V"])))
# print("Overhead CoolProp: {0:5.3f} us".format(np.mean(cstData["HEOS"]["DT_Tmax_V"])))#, np.mean(cstData["HEOS"]["HP_Tmax"]))
# print("Overhead REFPROP : {0:5.3f} us".format(np.mean(cstData["REFPROP"]["DT_Tmax_V"])))#,np.mean(cstData["REFPROP"]["HP_Tmax"]))
# print("Mean EOS in CoolProp: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.mean(expData["HEOS"]["DT_HPS_V"]),np.mean(impData["HEOS"]["HP_DST_V"])))
# print("Std. dev. in CoolProp: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.std(expData["HEOS"]["DT_HPS_V"]) ,np.std(impData["HEOS"]["HP_DST_V"])))
# print("Minimum in CoolProp: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.min(expData["HEOS"]["DT_HPS_V"]) ,np.min(impData["HEOS"]["HP_DST_V"])))
# print("Maximum in CoolProp: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.max(expData["HEOS"]["DT_HPS_V"]) ,np.max(impData["HEOS"]["HP_DST_V"])))
# print("Mean EOS in REFPROP: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.mean(expData["REFPROP"]["DT_HPS_V"]),np.mean(impData["REFPROP"]["HP_DST_V"])))
# print("Std. dev. in REFPROP: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.std(expData["REFPROP"]["DT_HPS_V"]) ,np.std(impData["REFPROP"]["HP_DST_V"])))
# print("Minimum in REFPROP: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.min(expData["REFPROP"]["DT_HPS_V"]) ,np.min(impData["REFPROP"]["HP_DST_V"])))
# print("Maximum in REFPROP: f(rho,T): {0:9.3f} us, f(h,p): {1:9.3f} us".format(np.max(expData["REFPROP"]["DT_HPS_V"]) ,np.max(impData["REFPROP"]["HP_DST_V"])))
# print("")
#
# except Exception as e:
# print(str(e.message))
# pass
#
# try:
# fld = 'Water'
# cstData = {} # Data from calls to constants (overhead)
# expData = {} # Data from explicit EOS calls
# impData = {} # Data from EOS calls that require iterations
# for backend in fluidData[fld]:
# curKeys = []
# for inp in getInpList(backend):
# for out in getOutList(inp)[:1]:
# curKeys.append(getTimeKey( inp, out))
# curKeys.append(getVectorKey(inp, out))
# curDict = {}
# fillDict(fld,backend,fluidData,curDict,curKeys)
# cstData[backend] = curDict
#
# curKeys = []
# for inp in getInpList(backend)[:1]:
# for out in getOutList(inp)[1:]:
# curKeys.append(getTimeKey( inp, out))
# curKeys.append(getVectorKey(inp, out))
# curDict = {}
# fillDict(fld,backend,fluidData,curDict,curKeys)
# expData[backend] = curDict
#
# curKeys = []
# for inp in getInpList(backend)[1:]:
# for out in getOutList(inp)[1:]:
# curKeys.append(getTimeKey( inp, out))
# curKeys.append(getVectorKey(inp, out))
# curDict = {}
# fillDict(fld,backend,fluidData,curDict,curKeys)
# impData[backend] = curDict
#
#
# print("Done")
def autolabel(ax,rects,means,stds,lens=0,fac=1):
return
# attach some text labels
yerr = (stds*100.0)/means
ypos = np.max(means) #+ np.max(stds)
for i in range(len(rects)):
xpos = rects[i].get_x()+rects[i].get_width()/2.
#ax.text(xpos, 1.05*ypos, '{0:s}{1:4.2f}{2:s}{3:3.1f}{4:s}'.format(r'',means[i]*fac,r'us +- ',yerr[i],r'%'), rotation=90, ha='center', va='bottom', fontsize='smaller')
ax.text(xpos, 1.05*ypos, '{0:s}{1:4.2f}{2:s}{3:3.1f}{4:s}'.format(r'\SI{',means[i]*fac,r'}{\us} (\SI{\pm',yerr[i],r'}{\percent})'), rotation=90, ha='center', va='bottom', fontsize='smaller')
#ax.text(xpos, 0.25*ypos, str(lens[i]), rotation=90, ha='center', va='bottom', fontsize='smaller')
def axislabel(txt,ax,xPos,yPos=-1):
ax.text(xPos, yPos, txt, rotation=45, ha='center', va='top', fontsize='xx-small')
#############################################################
# All data is available in the dicts now.
#############################################################
# The first plot contains the time data, this is averaged and
# plotted as a bar graph with the standard deviation.
hatchLst = ["", "///" ,"\\\\\\" ]
backendsLst = ["INCOMP","HEOS","REFPROP"]
for fluidstr in fluids[:-1]:
_,fld,_ = splitFluid(fluidstr)
outCst = []
labCst = []
outExp = []
labExp = []
outImp = []
labImp = []
DEBUG=False
for backend in backendsLst:
# Backend exists in fluid data?
try:
for i,inp in enumerate(getInpList(backend)):
for j,out in enumerate(getOutList(inp)):
if j==0: # First output is Tmax
if backend not in fluidData[fld]:
outCst.append([0])
labCst.append("Dummy")
if DEBUG: print("Added a dummy for {0} and {1},{2},{3}".format(fld,backend,inp,out))
else:
outCst.append(getSingleData(fld, backend, getTimeKey(inp, out), fluidData))
labCst.append(getTimeKey(inp, out))
continue
elif i==0: # First input is explicit
if backend not in fluidData[fld]:
outExp.append([0])
labExp.append("Dummy")
if DEBUG: print("Added a dummy for {0} and {1},{2},{3}".format(fld,backend,inp,out))
else:
outExp.append(getSingleData(fld, backend, getTimeKey(inp, out), fluidData))
labExp.append(getTimeKey(inp, out))
continue
elif i==1:
if backend not in fluidData[fld]:
outImp.append([0])
labImp.append("Dummy")
if DEBUG: print("Added a dummy for {0} and {1},{2},{3}".format(fld,backend,inp,out))
else:
outImp.append(getSingleData(fld, backend, getTimeKey(inp, out), fluidData))
labImp.append(getTimeKey(inp, out))
continue
else:
raise ValueError("Wrong number.")
except Exception as e:
print(e)
sys.exit(1)
# Do the plotting
if bp is not None:
bp.figure = None
fg = bp.getFigure()
ccycle = bp.getColorCycle(length=3)
else:
fg = plt.figure()
ccycle = cycle(["b","g","r"])
#fg = plt.figure()
ax1 = fg.add_subplot(111)
ax2 = ax1.twinx()
rects1 = []
labels1 = []
rects2 = []
labels2 = []
rects3 = []
labels3 = []
col1 = ccycle.next()
col2 = ccycle.next()
col3 = ccycle.next()
numBackends = len(backendsLst)
step = 1
width = step/(numBackends+1) # the width of the bars
offset = -0.5*numBackends*width
entries = int((len(outCst)+len(outExp)+len(outImp))/numBackends)
# for o in range(entries):
# ids = np.empty((numBackends,))
# for b in range(numBackends):
# i = o*numBackends+b
# ids[b] = offset + o*step + b*width
# j = i - 0
# if j < len(outCst):
# rects1.extend(ax1.bar(ids[b], np.mean(outCst[j]), width, color=col1, hatch=hatchLst[b]))#, yerr=np.std(curList[i]), ecolor='k'))
#
#
# j = i - 0
# if j < len(outCst):
# rects1.extend(ax1.bar(ids[b], np.mean(outCst[j]), width, color=col1, hatch=hatchLst[b]))#, yerr=np.std(curList[i]), ecolor='k'))
# else:
# j = i-len(outCst)
# if j < len(outExp):
# rects2.extend(ax1.bar(ids[b], np.mean(outExp[j]), width, color=col2, hatch=hatchLst[b]))#, yerr=np.std(curList[i]), ecolor='k'))
# else:
# j = i-len(outCst)-len(outExp)
# if j < len(outImp):
# rects3.extend(ax2.bar(ids[b], np.mean(outImp[j]), width, color=col3, hatch=hatchLst[b]))#, yerr=np.std(curList[i]), ecolor='k'))
# else:
# raise ValueError("Do not go here!")
DEBUG=False
entries = 2
for o in range(entries):
ids = np.empty((numBackends,))
for b in range(numBackends):
i = b*entries+o
try:
ids[b] = offset + o*step + b*width
rects1.extend(ax1.bar(ids[b], np.mean(outCst[i]), width, color=col1, hatch=hatchLst[b], rasterized=False))#, yerr=np.std(curList[i]), ecolor='k'))
if DEBUG:
print("Plotting {0}: {1:7.1f} - {2} - {3}".format(fld,np.mean(outCst[i]),"cst.",b))
#print(ids[b],labCst[i])
#axislabel(labCst[i], ax1, ids[b]+0.5*width)
except:
pass
offset += entries*step
#entries = int(len(outExp)/numBackends)
entries = 4
for o in range(entries):
ids = np.empty((numBackends,))
for b in range(numBackends):
i = b*entries+o
try:
ids[b] = offset + o*step + b*width
rects2.extend(ax1.bar(ids[b], np.mean(outExp[i]), width, color=col2, hatch=hatchLst[b], rasterized=False))#, yerr=np.std(curList[i]), ecolor='k'))
if DEBUG:
print("Plotting {0}: {1:7.1f} - {2} - {3}".format(fld,np.mean(outExp[i]),"exp.",b))
#print(ids[b],labExp[i])
#axislabel(labExp[i], ax1, ids[b]+0.5*width)
except:
pass
x_newaxis = np.max(ids)+1.5*width
plt.axvline(x_newaxis, color=bp._black, linestyle='dashed')
offset += entries*step
entries = 4
for o in range(entries):
ids = np.empty((numBackends,))
for b in range(numBackends):
i = b*entries+o
try:
ids[b] = offset + o*step + b*width
rects3.extend(ax2.bar(ids[b], np.mean(outImp[i]), width, color=col3, hatch=hatchLst[b], rasterized=False))#, yerr=np.std(curList[i]), ecolor='k'))
if DEBUG:
print("Plotting {0}: {1:7.1f} - {2} - {3}".format(fld,np.mean(outImp[i]),"imp.",b))
#print(ids[b],labImp[i])
#axislabel(labImp[i], ax1, ids[b]+0.5*width)
except:
pass
#ax1.set_xlim([ids.min()-2.5*width,ids.max()+2.5*width])
ax1.spines['top'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax1.xaxis.set_ticks_position('bottom')
ax2.xaxis.set_ticks_position('bottom')
labels=[r"ex.",r"im.",r"$h$",r"$\rho|p$",r"$s$",r"all",r"$\rho$",r"$s$",r"$T$",r"all"]
ax1.set_xticks(range(len(labels)))
ax1.set_xticklabels(labels)
#ax1.yaxis.get_label().set_verticalalignment("baseline")
x_min = rects1[0].get_x()
dx = rects1[0].get_width()
x_max = rects3[-1].get_x()
x_min = x_min - 1*dx
x_max = x_max + 2*dx
ax1.set_xlim([x_min,x_max])
y_min = 0
y_max_c = np.nanmax([a.get_height() for a in rects1])
y_max_e = np.nanmax([a.get_height() for a in rects2])
y_max_i = np.nanmax([a.get_height() for a in rects3])
y_max = np.max([y_max_c,y_max_e,y_max_i/10.0])
y_max = np.ceil(1.3*y_max/10.0)*10.0
ax1.set_ylim([y_min,y_max])
ax2.set_ylim([y_min,y_max*10.0])
ratio = 10.0/4.0 * y_max / 250.0 # height of 10 for 4 points if y_max==250
x_min = rects1[ 0].get_x()
x_max = rects1[-1].get_x() + dx
x,y = range_brace(x_min, x_max)
dy = np.ceil(y_max_c/10.0)*10.0
y = dy+y*ratio*(x[-1]-x[0])
ax1.plot(x, y, ls='-',color=bp._black)
ax1.text(np.mean(x), np.max(y), "const.", rotation=0, ha='center', va='bottom', fontsize='medium')
x_min = rects2[ 0].get_x()
x_max = rects2[-1].get_x() + dx
x,y = range_brace(x_min, x_max)
dy = np.ceil(y_max_e/10.0)*10.0
y = dy+y*ratio*(x[-1]-x[0])
ax1.plot(x, y, ls='-',color=bp._black)
ax1.text(np.mean(x), np.max(y), "explicit", rotation=0, ha='center', va='bottom', fontsize='medium')
x_min = rects3[ 0].get_x()
x_max = rects3[-1].get_x() + dx
x,y = range_brace(x_min, x_max)
dy = np.ceil(y_max_i/100.0)*10
y = dy+y*ratio*(x[-1]-x[0])
ax1.plot(x, y, ls='-',color=bp._black)
ax1.text(np.mean(x), np.max(y), "implicit", rotation=0, ha='center', va='bottom', fontsize='medium')
#ax1.text(x_newaxis*0.9, y_max*0.9, "<- left axis", rotation=0, ha='right', va='bottom', fontsize='medium')
#ax1.text(x_newaxis*1.1, y_max*0.9, "right axis ->", rotation=0, ha='left', va='bottom', fontsize='medium')
handles = []
for h in (rects1[0], rects2[1], rects3[2]):
handles.append(copy.copy(h))
handles[-1].set_facecolor('white')
handles.append(copy.copy(h))
handles[-1].set_hatch('')
labels = (r'$p,T$-fit', r'constant', r'CoolProp', r'explicit, $f(p|\rho,T)$', r'REFPROP', r'implicit, $f(h,p)$')
if bp is not None:
bp.drawLegend(ax=ax1,
loc='lower center',
bbox_to_anchor=(0.5, 1.05),
ncol=3,
handles=handles,
labels=labels)
else:
ax1.legend(handles,labels,
loc='lower center',
bbox_to_anchor=(0.5, 1.05),
ncol=3)
ax1.set_ylabel(r'Time per explicit call (us)')
ax2.set_ylabel(r'Time per implicit call (us)')
fg.savefig(path.join(getFigureFolder(),"TimeComp-"+fld.lower()+".pdf"))
if bp is not None:
ax1.set_ylabel(r'Time per explicit call (\si{\us})')
ax2.set_ylabel(r'Time per implicit call (\si{\us})')
mpl.rcParams['text.usetex'] = True
fg.savefig(path.join(getFigureFolder(),"TimeComp-"+fld.lower()+"-tex.pdf"))
mpl.rcParams['text.usetex'] = False
# Fix the wrong baseline
for tick in ax1.get_xaxis().get_major_ticks():
tick.set_pad(2*tick.get_pad())
tick.label1 = tick._get_text1()
for lab in ax1.xaxis.get_ticklabels():
lab.set_verticalalignment("baseline")
#lab.set_pad(1.5*lab.get_pad())
#ax1.set_xticklabels(labels)
#
#for tick in ax1.xaxis.get_major_ticks():
# tick.label1.set_horizontalalignment('center')
bp.savepgf(path.join(getFigureFolder(),"TimeComp-"+fld.lower()+".pgf"),fg,repList)
plt.close()
# for fld in fluids:
# try:
# if bp is not None:
# bp.figure = None
# fg = bp.getFigure()
# ccycle = bp.getColorCycle(length=3)
# else:
# fg = plt.figure()
# ccycle = cycle(["b","g","r"])
#
# #fg = plt.figure()
# ax1 = fg.add_subplot(111)
# ax2 = ax1.twinx()
#
# if "INCOMP" in fluidData[fld]:
# el = 3
# hatch = ["","//","x"]
# else:
# el = 2
# hatch = ["//","x"]
#
# #one standard deviation above and below the mean of the data
# width = 0.25 # the width of the bars
# step = 1
# offset = -step-0.5*el*width
#
# lab = []
# rects1 = []
# rects2 = []
#
# curList = []
# if el==3: curList.append(getSingleData(fld, "INCOMP" , "PT_Tmax", fluidData)*1e2)
# curList.append(getSingleData(fld, "HEOS" , "DT_Tmax", fluidData)*1e2)
# curList.append(getSingleData(fld, "REFPROP", "DT_Tmax", fluidData)*1e2)
#
# lab.extend(["Tmax"])
#
# offset += step
# curN = len(curList)
# curInd = [ offset + i * width for i in range(curN)]
# curCol = ccycle.next()
# for i in range(len(hatch)):
# rects1.extend(ax1.bar(curInd[i], np.mean(curList[i]), width, color=curCol, hatch=hatch[i]))#, yerr=np.std(curList[i]), ecolor='k'))
# autolabel(ax1,rects1[0:],np.mean(curList,axis=1),np.std(curList,axis=1),fac=1e-2)
#
# curList = []
# if el==3: curList.append(getSingleData(fld, "INCOMP" , "PT_H", fluidData))
# curList.append(getSingleData(fld, "HEOS" , "DT_H", fluidData))
# curList.append(getSingleData(fld, "REFPROP", "DT_H", fluidData))
# lab.extend(["H"])
# offset += step
# curN = len(curList)
# curInd = [ offset + i * width for i in range(curN)]
# curCol = ccycle.next()
# for i in range(len(hatch)):
# rects1.extend(ax1.bar(curInd[i], np.mean(curList[i]), width, color=curCol, hatch=hatch[i]))#, yerr=np.std(curList[i]), ecolor='k'))
# autolabel(ax1,rects1[el:],np.mean(curList,axis=1),np.std(curList,axis=1))
#
# curList = []
# if el==3: curList.append(getSingleData(fld, "INCOMP" , "PT_D", fluidData))
# curList.append(getSingleData(fld, "HEOS" , "DT_P", fluidData))
# curList.append(getSingleData(fld, "REFPROP", "DT_P", fluidData))
# if el==3: lab.extend(["D/P"])
# else: lab.extend(["P"])
# offset += step
# curN = len(curList)
# curInd = [ offset + i * width for i in range(curN)]
# #curCol = "g"
# for i in range(len(hatch)):
# rects1.extend(ax1.bar(curInd[i], np.mean(curList[i]), width, color=curCol, hatch=hatch[i]))#, yerr=np.std(curList[i]), ecolor='k'))
# autolabel(ax1,rects1[int(2*el):],np.mean(curList,axis=1),np.std(curList,axis=1))
#
# curList = []
# if el==3: curList.append(getSingleData(fld, "INCOMP" , "PT_S", fluidData))
# curList.append(getSingleData(fld, "HEOS" , "DT_S", fluidData))
# curList.append(getSingleData(fld, "REFPROP", "DT_S", fluidData))
# lab.extend(["S"])
# offset += step
# curN = len(curList)
# curInd = [ offset + i * width for i in range(curN)]
# #curCol = "g"
# for i in range(len(hatch)):
# rects1.extend(ax1.bar(curInd[i], np.mean(curList[i]), width, color=curCol, hatch=hatch[i]))#, yerr=np.std(curList[i]), ecolor='k'))
# autolabel(ax1,rects1[int(3*el):],np.mean(curList,axis=1),np.std(curList,axis=1))
#
# curList = []
# if el==3: curList.append(getSingleData(fld, "INCOMP" , "PT_HDS", fluidData))
# curList.append(getSingleData(fld, "HEOS" , "DT_HPS", fluidData))
# curList.append(getSingleData(fld, "REFPROP", "DT_HPS", fluidData))
# lab.extend(["all"])
# offset += step
# curN = len(curList)
# curInd = [ offset + i * width for i in range(curN)]
# #curCol = "g"
# for i in range(len(hatch)):
# rects1.extend(ax1.bar(curInd[i], np.mean(curList[i]), width, color=curCol, hatch=hatch[i]))#, yerr=np.std(curList[i]), ecolor='k'))
# autolabel(ax1,rects1[int(4*el):],np.mean(curList,axis=1),np.std(curList,axis=1))
#
# curList = []
# if el==3: curList.append(getSingleData(fld, "INCOMP" , "HP_D", fluidData))
# curList.append(getSingleData(fld, "HEOS" , "HP_D", fluidData))
# curList.append(getSingleData(fld, "REFPROP", "HP_D", fluidData))
# lab.extend(["D"])
# offset += step
# curN = len(curList)
# curInd = [ offset + i * width for i in range(curN)]
# curCol = ccycle.next()
# for i in range(len(hatch)):
# rects2.extend(ax2.bar(curInd[i], np.mean(curList[i]), width, color=curCol, hatch=hatch[i]))#, yerr=np.std(curList[i]), ecolor='k'))
# autolabel(ax2,rects2[0:],np.mean(curList,axis=1),np.std(curList,axis=1))
#
# curList = []
# if el==3: curList.append(getSingleData(fld, "INCOMP" , "HP_T", fluidData))
# curList.append(getSingleData(fld, "HEOS" , "HP_T", fluidData))
# curList.append(getSingleData(fld, "REFPROP", "HP_T", fluidData))
# lab.extend(["T"])
# offset += step
# curN = len(curList)
# curInd = [ offset + i * width for i in range(curN)]
# #curCol = "r"
# for i in range(len(hatch)):
# rects2.extend(ax2.bar(curInd[i], np.mean(curList[i]), width, color=curCol, hatch=hatch[i]))#, yerr=np.std(curList[i]), ecolor='k'))
# autolabel(ax2,rects2[int(1*el):],np.mean(curList,axis=1),np.std(curList,axis=1))
#
# curList = []
# if el==3: curList.append(getSingleData(fld, "INCOMP" , "HP_S", fluidData))
# curList.append(getSingleData(fld, "HEOS" , "HP_S", fluidData))
# curList.append(getSingleData(fld, "REFPROP", "HP_S", fluidData))
# lab.extend(["S"])
# offset += step
# curN = len(curList)
# curInd = [ offset + i * width for i in range(curN)]
# #curCol = "r"
# for i in range(len(hatch)):
# rects2.extend(ax2.bar(curInd[i], np.mean(curList[i]), width, color=curCol, hatch=hatch[i]))#, yerr=np.std(curList[i]), ecolor='k'))
# autolabel(ax2,rects2[int(2*el):],np.mean(curList,axis=1),np.std(curList,axis=1))
#
# curList = []
# if el==3: curList.append(getSingleData(fld, "INCOMP" , "HP_DST", fluidData))
# curList.append(getSingleData(fld, "HEOS" , "HP_DST", fluidData))
# curList.append(getSingleData(fld, "REFPROP", "HP_DST", fluidData))
# lab.extend(["all"])
# offset += step
# curN = len(curList)
# curInd = [ offset + i * width for i in range(curN)]
# #curCol = "r"
# for i in range(len(hatch)):
# rects2.extend(ax2.bar(curInd[i], np.mean(curList[i]), width, color=curCol, hatch=hatch[i]))#, yerr=np.std(curList[i]), ecolor='k'))
# autolabel(ax2,rects2[int(3*el):],np.mean(curList,axis=1),np.std(curList,axis=1))
#
#
# ids = np.arange(len(lab))
# # add some text for labels, title and axes ticks
# #if backend=="INCOMP": ax1.set_ylabel(r'Time per $f(p,T)$ call (\si{\us})')
# if el==3: ax1.set_ylabel(r'Time per \texttt{Tmax} call (\SI{0.01}{\us}) and'+"\n"+r'per $f(p,T)$ and $f(\rho,T)$ call (\si{\us})')
# else: ax1.set_ylabel(r'Time per \texttt{Tmax} call (\SI{0.01}{\us})'+"\n"+r'and per $f(\rho,T)$ call (\si{\us})')
# ax2.set_ylabel(r'Time per $f(h,p)$ call (\si{\us})')
#
# ax1.set_xticks(ids)
# ax1.set_xticklabels([r"\texttt{"+i+r"}" for i in lab], rotation=0)
# ax1.set_xlim([ids.min()-2.5*width,ids.max()+2.5*width])
#
# ax1.spines['top'].set_visible(False)
# ax2.spines['top'].set_visible(False)
# ax1.xaxis.set_ticks_position('bottom')
# ax2.xaxis.set_ticks_position('bottom')
#
# handles = []
# if el==3:
# for h in (rects1[0], rects1[4], rects2[2]):
# handles.append(copy.copy(h))
# handles[-1].set_facecolor('white')
# handles.append(copy.copy(h))
# handles[-1].set_hatch('')
# labels = (r'$p,T$-fit', r'\texttt{Tmax}', r'CoolProp', r'explicit, $f(p|\rho,T)$', r'REFPROP', r'implicit, $f(h,p)$')
# else:
# for h in (rects1[0], rects1[2], rects2[1]):
# handles.append(copy.copy(h))
# handles[-1].set_facecolor('white')
# handles.append(copy.copy(h))
# handles[-1].set_hatch('')
# labels = (r'', r'\texttt{Tmax}', r'CoolProp', r'explicit, $f(\rho,T)$', r'REFPROP', r'implicit, $f(h,p)$')
# handles[0] = mpatches.Patch(visible=False)
#
# if bp is not None:
# bp.drawLegend(ax=ax1,
# loc='upper center',
# bbox_to_anchor=(0.5, 1.4),
# ncol=3,
# handles=handles,
# labels=labels)
# else:
# ax1.legend(handles,labels,
# loc='upper center',
# bbox_to_anchor=(0.5, 1.4),
# ncol=3)
#
# fg.savefig(path.join(getFigureFolder(),"TimeComp-"+fld+".pdf"))
# if bp is not None: bp.savepgf(path.join(getFigureFolder(),"TimeComp-"+fld+".pgf"),fg,repList)
# plt.close()
#
# except Exception as e:
# print(e)
# pass
#############################################################
# The second figure compares the backend for the full calculation
#############################################################
backendExp = []
backendImp = []
fluidLabel = []
hatchLst = ["///" ,"\\\\\\"]
backendsLst = ["HEOS","REFPROP"]
for fluidstr in fluids[:-1]:
_,fld,_ = splitFluid(fluidstr)
#if fld=="CO2": fluidLabel.append("\ce{CO2}")
#else:
fluidLabel.append(fld)
for backend in backendsLst:
if backend not in fluidData[fld]:
backendExp.append([0])
backendImp.append([0])
continue
# Backend exists in fluid data
try:
inp = getInpList(backend)
outExp = getTimeKey(inp[0], getOutList(inp[0])[-1])
outImp = getTimeKey(inp[1], getOutList(inp[1])[-1])
backendExp.append(getSingleData(fld, backend, outExp, fluidData))
backendImp.append(getSingleData(fld, backend, outImp, fluidData))
except Exception as e:
backendExp.append([0])
backendImp.append([0])
print(e)
pass
# Data is prepared, we can plot now.
if bp is not None:
bp.figure = None
fg1 = bp.getFigure()
bp2 = BasePlotter()
fg2 = bp2.getFigure()
ccycle = bp.getColorCycle(length=3)
else:
fg1 = plt.figure()
fg2 = plt.figure()
ccycle = cycle(["b","g","r"])
fg1.set_size_inches( (fg1.get_size_inches()[0]*1, fg1.get_size_inches()[1]*0.75) )
fg2.set_size_inches( (fg2.get_size_inches()[0]*1, fg2.get_size_inches()[1]*0.75) )
ccycle.next() # No incomp
#
#ax1 = fg.add_subplot(111)
#ax2 = ax1.twinx()
ax1 = fg1.add_subplot(111)
ax2 = fg2.add_subplot(111)
#entries = int(len(backendExp)/len(fluidLabel))
#one standard deviation above and below the mean of the data
rects1 = []
rects2 = []
col1 = ccycle.next()
col2 = ccycle.next()
numFluids = len(fluidLabel)
numBackends = len(backendsLst)
step = 1
width = step/(numBackends+1) # the width of the bars
offset = -0.5*numBackends*width
for f in range(numFluids):
ids = np.empty((numBackends,))
for b in range(numBackends):
i = f*numBackends+b
ids[b] = offset + f*step + b*width
rects1.extend(ax1.bar(ids[b], np.mean(backendExp[i]), width, color=col1, hatch=hatchLst[b], rasterized=False))#, yerr=np.std(curList[i]), ecolor='k'))
rects2.extend(ax2.bar(ids[b], np.mean(backendImp[i]), width, color=col2, hatch=hatchLst[b], rasterized=False))#, yerr=np.std(curList[i]), ecolor='k'))
y_max = np.max(np.concatenate((np.ravel(ax1.get_ylim()),np.ravel(ax2.get_ylim())/10.0)))
ax1.set_ylim([0,y_max])
ax2.set_ylim([0,y_max*10.0])
for ax in [ax1,ax2]:
ax.set_xticks(range(numFluids))
ax.set_xticklabels(fluidLabel, rotation=25)
ax.set_xlim([0.0-0.5*step,numFluids-1+0.5*step])
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
if ax==ax1: rects = rects1
elif ax==ax2: rects = rects2
handles = (rects[0], rects[1])
labels = (r'CoolProp', r'REFPROP')
anchor = (0.5, 1.2)
if bp is not None:
bp.drawLegend(ax=ax,
loc='upper center',
bbox_to_anchor=anchor,
ncol=numBackends,
handles=handles,
labels=labels)
else:
ax.legend(handles,labels,
loc='upper center',
bbox_to_anchor=anchor,
ncol=numBackends)
ax1.set_ylabel(r'Time per $f(\rho,T)$ call (us)')
ax2.set_ylabel(r'Time per $f(h,p)$ call (us)')
fg1.savefig(path.join(getFigureFolder(),"TimeComp-backends-exp.pdf"))
fg2.savefig(path.join(getFigureFolder(),"TimeComp-backends-imp.pdf"))
if bp is not None:
ax1.set_ylabel(r'Time per $f(\rho,T)$ call (\si{\us})')
ax2.set_ylabel(r'Time per $f(h,p)$ call (\si{\us})')
mpl.rcParams['text.usetex'] = True
fg1.savefig(path.join(getFigureFolder(),"TimeComp-backends-exp-tex.pdf"))
fg2.savefig(path.join(getFigureFolder(),"TimeComp-backends-imp-tex.pdf"))
mpl.rcParams['text.usetex'] = False
bp.savepgf(path.join(getFigureFolder(),"TimeComp-backends-exp.pgf"),fg1,repList)
bp.savepgf(path.join(getFigureFolder(),"TimeComp-backends-imp.pgf"),fg2,repList)
plt.close('all')
#############################################################
# The third figure is a heat map of the execution times in
# log p h diagram
#############################################################
for fluidstr in fluids:
try:
_,fld,_ = splitFluid(fluidstr)
for backend in fluidData[fld]:
propsfluid = "::".join([backend,fluidstr])
if backend!="INCOMP":
TP = {}
points = int(xypoints/2)
T_range_TP = np.linspace(PropsSI('Ttriple',"T",0,"D",0,propsfluid),PropsSI( 'Tcrit',"T",0,"D",0,propsfluid),points)
T_TP = np.append(T_range_TP,T_range_TP[::-1])
Q_TP = np.zeros_like(T_TP)
Q_TP[points:] = 1
points *= 2
out = ["D","H","P","S"]
res = PropsSI(out,"T",T_TP,"Q",Q_TP,propsfluid)
D_TP = res[:,0]
H_TP = res[:,1]
P_TP = res[:,2]
S_TP = res[:,3]
mask = np.isfinite(D_TP)
if np.sum(mask)<points:
warn("There were not enough valid entries in your result vector. Reducing the number of points from {0:d} to {1:d}.".format(points,np.sum(mask)))
points = np.sum(mask)
TP["T"] = T_TP[mask]
TP["D"] = D_TP[mask]
TP["H"] = H_TP[mask]
TP["P"] = P_TP[mask]
TP["S"] = S_TP[mask]
#saveNpzData(TP)
else:
TP = None
state = getStateObj(propsfluid)
if backend=="HEOS" and state.has_melting_line():
p_melt = np.logspace(np.log10(state.melting_line(CoolProp.constants.iP_min, CoolProp.constants.iT, 0)),np.log10(state.melting_line(CoolProp.constants.iP_max, CoolProp.constants.iT, 0)),xypoints)
#p_melt = p_range
ML = dict(T=[],D=[],H=[],S=[],P=p_melt)
for p in p_melt:
try:
ML["T"].append(state.melting_line(CoolProp.constants.iT, CoolProp.constants.iP, p))
except Exception as ve:
ML["T"].append(np.inf)
res = PropsSI(["D","H","P","S","T"],"T",ML["T"],"P",ML["P"],propsfluid)
ML["D"] = res[:,0]
ML["H"] = res[:,1]
ML["P"] = res[:,2]
ML["S"] = res[:,3]
ML["T"] = res[:,4]
mask = np.isfinite(ML["T"])
ML["P"] = ML["P"][mask]
ML["T"] = ML["T"][mask]
ML["D"] = ML["D"][mask]
ML["H"] = ML["H"][mask]
ML["S"] = ML["S"][mask]
else:
ML = None
#ML = {}
IP = {}
p_range,T_range = getPTRanges(propsfluid)
critProps = getCriticalProps(propsfluid)
try:
IP["T"] = T_range
IP["P"] = np.zeros_like(T_range) + critProps["P"]
res = PropsSI(["D","H"],"T",IP["T"],"P",IP["P"],propsfluid)
IP["D"] = res[:,0]
IP["H"] = res[:,1]
except Exception as ve:
IP = None
IT = {}
try:
IT["P"] = p_range
IT["T"] = np.zeros_like(p_range) + critProps["T"]
res = PropsSI(["D","H"],"T",IT["T"],"P",IT["P"],propsfluid)
IT["D"] = res[:,0]
IT["H"] = res[:,1]
except Exception as ve:
IT = None
ID = {}
try:
ID["T"] = T_range
ID["D"] = np.zeros_like(p_range) + critProps["D"]
res = PropsSI(["P","H"],"T",ID["T"],"D",ID["D"],propsfluid)
ID["P"] = res[:,0]
ID["H"] = res[:,1]
except Exception as ve:
ID = None
IH = {}
try:
IH["P"] = p_range
IH["H"] = np.zeros_like(p_range) + critProps["H"]
res = PropsSI(["D","T"],"P",IH["P"],"H",IH["H"],propsfluid)
IH["D"] = res[:,0]
IH["T"] = res[:,1]
except Exception as ve:
IH = None
IS = {}
try:
IS["P"] = p_range
IS["S"] = np.zeros_like(p_range) + critProps["S"]
res = PropsSI(["D","H","T"],"P",IS["P"],"S",IS["S"],propsfluid)
IS["D"] = res[:,0]
IS["H"] = res[:,1]
IS["T"] = res[:,2]
except Exception as ve:
IS = None
for I in [IP,IT,ID,IH,IS]:
if I is not None:
mask = np.isfinite(I["D"]) & np.isfinite(I["H"])
if np.sum(mask)<20: I = None
else:
for k in I:
I[k] = I[k][mask]
for inp in getInpList(backend):
if bp is not None:
bp.figure = None
fg = bp.getFigure()
else:
fg = plt.figure()
kind = getTimeKey(inp, getOutList(inp)[-1])
t_data = getSingleData(fld, backend, kind, fluidData)
x_data = getSingleData(fld, backend, "H", fluidData)
y_data = getSingleData(fld, backend, "P", fluidData)
gs = gridspec.GridSpec(1, 2, wspace=None, hspace=None, width_ratios=[10,1])
ax1 = fg.add_subplot(gs[0,0])
ax1.set_yscale('log')
#ax2 = ax1.twinx()
minHP = np.min(t_data)
maxHP = np.max(t_data)
minIT = np.percentile(t_data,10)
maxIT = np.percentile(t_data,90)
difIT = np.log10(maxIT/minIT)*0.25
print(kind,": {0:7.2f} to {1:7.2f}".format(minHP,maxHP))
if kind == "DT":
if bp is not None:
cx1=bp.getColourMap(reverse=True)
else:
cx1 = mpl.cm.get_cmap('cubehelix_r')
minHP = minIT
maxHP = np.power(10,np.log10(maxIT)+difIT)
#minHP = np.power(10,np.log10(np.percentile(t_data,10)*1e6))
#maxHP = np.power(10,np.log10(np.percentile(t_data,90)*1e6)*1.10)
#maxHP = np.power(10,1.10*np.log10(maxHP))
#minHP = np.percentile(t_data,10)*1e6
#maxHP = np.percentile(t_data,99)*1e6
#print(kind,": {0:7.2f} to {1:7.2f}".format(minHP,maxHP))
#minHP = 100
#maxHP = 20000
else:
if bp is not None:
cx1 = bp.getColourMap()
else:
cx1 = mpl.cm.get_cmap('cubehelix')
minHP = np.power(10,np.log10(minIT)-difIT)
maxHP = maxIT
#minHP = np.power(10,np.log10(np.percentile(t_data,10)*1e6)*0.90)
#maxHP = np.power(10,np.log10(np.percentile(t_data,90)*1e6))
#minHP = np.percentile(t_data,01)*1e6
#maxHP = np.percentile(t_data,90)*1e6
#print(kind,": {0:7.2f} to {1:7.2f}".format(minHP,maxHP))
#minHP = 100
#maxHP = 20000
#cx1_r = reverse_colourmap(cx1)
cNorm = mpl.colors.LogNorm(vmin=minHP, vmax=maxHP)
#cNorm = mpl.colors.LogNorm(vmin=ceil(minHP/1e1)*1e1, vmax=floor(maxHP/1e2)*1e2)
#cNorm = mpl.colors.Normalize(vmin=round(minHP,-2), vmax=round(maxHP,-2))
colourSettings = dict(c=t_data, edgecolors='none', cmap=cx1, norm=cNorm)
pointSettings = dict(s=4)
scatterSettings = dict(rasterized=True, alpha=0.5)
#scatterSettings = dict(rasterized=False, alpha=0.5)
scatterSettings.update(colourSettings)
scatterSettings.update(pointSettings)
SC = ax1.scatter(x_data/1e6,y_data/1e5, **scatterSettings)
for I in [TP,ML]:
if I is not None:
ax1.plot(I["H"]/1e6,I["P"]/1e5,lw=1.5,c=bp._black)
for I in [IP,IT,ID,IS,IH]:
if I is not None:
ax1.plot(I["H"]/1e6,I["P"]/1e5,lw=1.0,c=bp._black,alpha=1)
#ax1.set_xlim([0e+0,6e1])
#ax1.set_ylim([5e-1,2e4])
ax1.set_xlim([np.percentile(x_data/1e6,0.1),np.percentile(x_data/1e6,99.9)])
ax1.set_ylim([np.percentile(y_data/1e5,0.1),np.percentile(y_data/1e5,99.9)])
formatter = ticker.LogFormatter(base=10.0, labelOnlyBase=False)
#formatter = ticker.ScalarFormatter()
#ticks = roundList(np.logspace(np.log10(ax1.get_ylim()[0]), np.log10(ax1.get_ylim()[1]), 5))
#locator = ticker.FixedLocator(ticks)
#ax1.yaxis.set_major_locator(locator)
ax1.yaxis.set_major_formatter(formatter)
cax = fg.add_subplot(gs[0,1])
formatter = ticker.ScalarFormatter()
CB = fg.colorbar(SC, cax=cax,format=formatter)
CB.set_alpha(1)
#CB.locator = ticker.MaxNLocator(nbins=7)
ticks = roundList(np.logspace(np.log10(minHP), np.log10(maxHP), 5))
CB.locator = ticker.FixedLocator(ticks)
CB.update_ticks()
CB.draw_all()
CB.set_label(r'Execution time per call (us)')
ax1.set_xlabel(r'Specific enthalpy (MJ/kg)')
ax1.set_ylabel(r'Pressure (bar)')
fg.tight_layout()
fg.savefig(path.join(getFigureFolder(),"TimeComp-"+inp+"-"+backend.lower()+"-"+fld.lower()+".pdf"))
CB.set_label(r'Execution time per call (\si{\us})')
ax1.set_xlabel(r'Specific enthalpy (\si{\mega\J\per\kg})')
ax1.set_ylabel(r'Pressure (\si{\bar})')
fg.tight_layout()
bp.savepgf(path.join(getFigureFolder(),"TimeComp-"+inp+"-"+backend.lower()+"-"+fld.lower()+".pgf"),fg,repList)
plt.close()
except Exception as e:
print(e)
pass
plt.close('all')
| [
"jowr@mek.dtu.dk"
] | jowr@mek.dtu.dk |
6aeb5dd0d63bbbfa7c7a8309ee7d08cdd953b7f0 | 4aca8b5d8b06891f74ef3ebdd2c3371f0b32b62c | /employes/settings/base.py | 59510cec9c915adcdaf172d955ec24ee9bce36a5 | [] | no_license | javierjsv/employed-django | d125327babfcb3cfc7e7736f5408a85d6708495c | 83134788270e33154509ad04f9c0822263649e1b | refs/heads/master | 2023-02-28T11:06:57.084826 | 2021-02-06T17:56:35 | 2021-02-06T17:56:35 | 332,308,382 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,578 | py |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from unipath import Path
BASE_DIR = Path(__file__).ancestor(3)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '27x4y1s*uthcw4-mzz7wtk04nro8gzye(0bgml=4$g)bgboaa@'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# local Apps terceros
'ckeditor',
# local Apps
'applications.department',
'applications.employed',
'applications.home',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'employes.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR.child('templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'employes.wsgi.application'
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'es-co'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
| [
"javiersolis@useitweb.com"
] | javiersolis@useitweb.com |
2a1ce9e27ded841f4a824d5a6be3f805758fb896 | e9ebcec0fcc99c7721b45a12c5315349d75ee158 | /211012_main.py | db023dd2f814f193076743c1e19bf5df308c300a | [] | no_license | pogn/gazua_sns | d7b119cdf5f30fa9c6acaf0eac73801c3102185a | 3053f127543940cbecdc637378bf196b3f0a5791 | refs/heads/main | 2023-08-22T04:16:29.277063 | 2021-10-18T12:20:19 | 2021-10-18T12:20:19 | 406,468,956 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,691 | py |
import pybithumb
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
import matplotlib as mpl
def get_ror_ji(ticker,start_date,end_date,k,target_vol,money,fee):
df = pybithumb.get_ohlcv(ticker)
df = df.loc[start_date:end_date]
#df = df.loc[start_date, '2021-']
######## Data Frame 주요함수 #########
# cumprod : 누적곱
# shift
# rolling(window=5)
# mean
# max
# cummax
####################################
# 매수조건 1) range 값 이상의 변동성 돌파가 있는경우
df['range'] = (df['high'] - df['low']) * k # range = 당일 (고가-저가)/2
df['target'] = df['open'] + df['range'].shift(1) # target = 당일 시가 + 전일 range(shift(1))가 표시되도록 옮기기
# 매수조건 2) 시가가 이동평균선보다 높은경우
df['ma5'] = df['close'].rolling(window=5).mean().shift(1) # ma5 = 5일간의 이동평균선
df['bull'] = df['open'] > df['ma5'] # 시가가 이동평균선보다 높은지 여부
# 사졌는지 여부 T/F ( 종가가 목표가 초과시 매수)
df['buyTF'] = (df['high'] > df['target']) & df['bull']
# 수익률(ror열) = 샀을경우 수익률 = 종가/목표가, 매수실패시 =1
df['ror'] = np.where(df['buyTF'], df['close'] / df['target'] - fee, 1) # ROR cf) fee는 금액대비 %이니 ROR에서 계산하면 맞다.
df['hpr'] = df['ror'].cumprod() # 기간수익률
df['dd'] = (df['hpr'].cummax() - df['hpr']) / df['hpr'].cummax() * 100 # MDD = 전고점 대비 몇까지 떨어졌는지, 각 일자별로 계산 (마지막 일자를 봐야함)
# 변동성 조절) 변동성을 조절하기 위해 일일 투자금을 정한다. (money가 1인경우 수익률)
df['stb'] = ((df['high'] - df['low']) / df['open']) * 100 # 1일 변동성(당일)
df['stb5'] = df['stb'].rolling(window=5).mean().shift(1) # 5일평균변동성(전일기준)
df['invest_p'] = target_vol / df['stb5'] * money # 투자금 = 목표변동성/예상변동성(stb5) * 전체자산 => 평균변동성에서 목표변동성만큼 맞추기 위해
df.loc[(df.invest_p > 1), 'invest_p'] = 1 # 목표변동성 > 실변동성 인경우 전체 투자(1)
df['not_invest_p'] = (1 - df['invest_p']) * money
df['invest_after_p'] = df['invest_p'] * df['ror'] # 투자금의 수익률반영된 금액 QQQQ 곱해야하는게 ror인가 hpr인가?
df['invest_result'] = df['not_invest_p'] + df['invest_after_p'] # 변동성이 반영된 전체 투자 수익
#df['invest_result'] = df['all_%'].cumprod() # 변동성이 반영된 전체 투자 수익
print(ticker)
print("MDD: ", df['dd'].max(),"%")
print("HPR: ", df['hpr'][-2],"배")
str_d = datetime.strptime(start_date, "%Y-%m-%d")
end_d = datetime.strptime(end_date, "%Y-%m-%d")
diff = end_d - str_d
diff = diff.days / 365
hpr = df['hpr'].iloc[-1]
cagr = ((hpr ** (1 / diff)) - 1) * 100
print('연복리 : ', cagr)
#ror = df['ror'].cumprod()[-2] # 전체 수익률 계산
#print(ticker)
#print(df)
return df
if __name__ == '__main__':
# X 1) top5 상승장 코인 티커 가져오기
# X top5_ticker = get_top5()
###############################
### 1) 각 종목별 일일 ror 계산하기
writer = pd.ExcelWriter('./RESULT/gazua_sns.xlsx', engine='openpyxl') # 필요한 엑셀파일 생성
# -------------- 변수 --------------
tickers = ['BTC','ETH'] #, 'ETH','ADA', 'BNB','XRP'] # 시가총액 10위 기업 티커 입력
start_date = '2013-12-27' # 데이터 계산 시작시점 2021
end_date = '2021-10-12'
k = 0.5 # 구매여부를 결정하는 변동성 돌파정도
money = 1 # 투자자산 - 1인경우 비율로만 계산됨
fee = 0.0032 # 수수료 : 0.002 * 2 + 0.0002 // 0.2%
target_vol = 2 # 목표 변동성 (% 임)
# ----------------------------------
for ticker in tickers:
df = get_ror_ji(ticker, start_date, end_date, k, target_vol, money, fee)
df.to_excel(writer, sheet_name=ticker)
writer.save()
###############################
### 2) 종목별 투자 수익률 가져오기
main_df = pd.DataFrame(columns=['time']) # time열 추가
for ticker in tickers:
df = pd.read_excel('./RESULT/gazua_sns.xlsx', sheet_name=ticker, engine='openpyxl')
df_new = df.loc[:, ['time', 'invest_result']]
df_new = df_new.rename(columns={'invest_result': str(ticker)})
main_df = pd.merge(main_df, df_new, how='outer', on='time')
main_df = main_df.fillna(1)
main_df.to_excel('./RESULT/tmp.xlsx')
x = 0
for ticker in tickers:
if x == 0 :
main_df['sum'] = main_df[ticker]
x = x + 1
else :
main_df['sum'] = main_df['sum'] + main_df[ticker]
# 5 종목 MDD 계산
main_df['ror'] = main_df['sum'] / len(tickers)
main_df['hpr'] = main_df['ror'].cumprod() # 누적수익률
main_df['dd'] = (main_df['ror'].cummax() - (main_df['ror'] / main_df['ror'].cummax())) * 100
MDD = main_df['dd'].max()
HPR = main_df['hpr'].iloc[-1]
main_df.to_excel('./RESULT/result.xlsx')
print("---------최종---------")
print("MDD : ", MDD , "%")
print("HPR : ", HPR , "배")
# 기간수익률 -> 연복리 계산
diff = main_df['time'].iloc[-1] - main_df['time'].iloc[0]
diff = diff.days / 365
hpr = main_df['hpr'].iloc[-1]
cagr = ((hpr ** (1 / diff)) - 1) * 100
print('연복리 : ', cagr)
# --------- graph ---------
ys = ['open'] #, 'ma5', 'target']
df.plot(kind='line', x='time', y=ys)
plt.show()
| [
"ujungin1213@gmail.com"
] | ujungin1213@gmail.com |
7d78c58f4bc55af34e8f3df2884698d75d86cba7 | ec69032800a6f7328f88209b2590d512d6c8aa31 | /Python-SC106A-Assignment2-main/khansole_academy.py | bf9324236450b21318fe85efc74cd821dddf322f | [] | no_license | DianaTs1/SC106A-Assignments | 5bd24483a90023a2612b8115449b40c1dbfbde1e | dcb50704a98b95ff955db5656aeb7a2b9807ed69 | refs/heads/main | 2023-07-13T17:49:25.774903 | 2021-08-30T01:37:11 | 2021-08-30T01:37:11 | 373,280,692 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 850 | py | import random
MIN_NUMBER = 15
MAX_NUMBER = 95
def main():
number_of_users_correct_answer = 0
while number_of_users_correct_answer < 3:
first_number = random.randint(MIN_NUMBER, MAX_NUMBER)
second_number = random.randint(MIN_NUMBER, MAX_NUMBER)
print(f"What is {first_number} + {second_number}? ")
user_answer = int(input("Your answer: "))
correct_answer = first_number + second_number
if user_answer == correct_answer:
number_of_users_correct_answer += 1
print(f"Correct! You have gotten {number_of_users_correct_answer} correct in a row")
else:
number_of_users_correct_answer = 0
print(f"Incorrect! The expected answer is {correct_answer}")
print("Congratulations! You mastered addition!")
if __name__ == '__main__':
main()
| [
"noreply@github.com"
] | DianaTs1.noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.