seq_id string | text string | repo_name string | sub_path string | file_name string | file_ext string | file_size_in_byte int64 | program_lang string | lang string | doc_type string | stars int64 | dataset string | pt string | api list |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
29007039516 | from django.urls import path
from . import views
from django.shortcuts import render, redirect
urlpatterns = [
path("", views.index ,name="index"),
path("index.html", views.index ,name="index"),
path("robots.txt", views.robots ,name="robots"),
path("ads.txt", (lambda request: render(request, "ads.txt") ), name="ads.txt"),
path("sitemap.xml", views.sitemap, name="sitemap"),
path("sitemap/", views.sitemap, name="s"),
path("<category>/<htmlname>", views.page, name="page"),
path("about.html/", views.about, name="about"),
path("<category_name>/", views.category_page, name="page")
]
| minegishirei/flamevalue | trashbox/django3/app/short_tips/urls.py | urls.py | py | 622 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "django.urls.path",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "django.urls.path",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "django.urls.path",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "django.urls.path",
... |
2180140168 | """TCP hole punching and peer communication."""
import socket
import threading
from typing import Callable
class Error(Exception):
pass
class Tunnel:
"""High-level packet transmission."""
class Listener:
"""Automatic tunnel creation on port."""
def __init__(self, port: int, backlog: int = None):
self._sock = socket.socket()
self._sock.bind(('', port))
self._sock.listen(backlog)
self._lock = threading.RLock()
self._running = False
self._thread = None # type: threading.Thread
@property
def running(self):
"""Return whether listener is currently running."""
with self._lock:
return self._running and (self._thread is not None)
def start(self, handler: Callable):
"""Spawn thread to act as listener."""
with self._lock:
if self._thread is not None:
raise Error('listener already started')
self._running = True
self._thread = threading.Thread(target=self._loop, args=(handler,), daemon=True)
self._thread.start()
def _loop(self, handler: Callable):
"""Spawn new threads to handle incoming connections."""
while self.running:
threading.Thread(target=handler, args=(self._sock.accept(),)).start()
def stop(self):
with self._lock:
self._running = False
self._thread.join()
self._thread = None
| TheDocTrier/pyble | pyble/server/tunnel.py | tunnel.py | py | 1,468 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "socket.socket",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "threading.RLock",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "typing.Callable",
"line_number": 34,
"usage_type": "name"
},
{
"api_name": "threading.Thread",
... |
11178768615 | import pandas
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
data = pandas.read_csv("database.csv")
crop = pandas.read_csv("crop.csv")
city = data['city'].to_list()
max_temp = list(map(int, data['max temperature'].to_list()))
min_temp = list(map(int, data['min temperature'].to_list()))
max_humid = list(map(int, data['max humidity'].to_list()))
min_humid = list(map(int, data['min humidity'].to_list()))
min_ph = list(map(int, data['min ph'].to_list()))
max_ph = list(map(int, data['max ph'].to_list()))
wheat_humidity = 80.5
wheat_ph = 9
avg_humi = {}
avg_humidity = []
avg_tempa = {}
avg_temp = []
for i in range(len(data)):
avg_tempa[city[i]] = (max_temp[i]+min_temp[i])/2
avg_temp.append((max_temp[i]+min_temp[i])/2)
for i in range(27):
avg_humi[city[i]] = (max_humid[i]+min_humid[i])/2
avg_humidity.append((max_humid[i]+min_humid[i])/2)
avg_phs = {}
avg_ph = []
for i in range(27):
avg_phs[city[i]] = (max_ph[i]+min_ph[i])/2
avg_ph.append((max_ph[i]+min_ph[i])/2)
datafram = {'city': city, 'temp': avg_temp, 'ph': avg_ph, 'humidity': avg_humidity}
new = pd.DataFrame(datafram)
columns = list(new.head())[1:len(list(new.head()))]
clf = DecisionTreeClassifier()
target = 'crop'
clf.fit(crop[columns], crop[target])
predictions = clf.predict(new[columns])
final = pd.DataFrame({'City': city, 'Temperature': avg_temp, 'pH': avg_ph, 'Humidity': avg_humidity, 'Crop': predictions})
data['avg humidity'] = avg_humidity
data['avg_temp'] = avg_temp
data['avg ph'] = avg_ph
name = input("Enter the name of the city:").lower()
if name not in city:
print("City Not Found....")
else:
print("City Crop Predicted Data")
plot_data = final[final['City'] == name]
print(plot_data)
crops=list(plot_data['Crop'])
crop_data=crop[crop['crop']==crops[0]]
print("Crop Data")
print(crop_data)
crop_cols=['temp','ph','humidity']
plot_columns = list(plot_data.head())[1:len(list(plot_data.head()))-1]
plot_array = []
for i in list(final.head())[1:len(list(final.head()))-1]:
plot_array.append(np.array(final[i]))
for i in range(len(plot_array)):
dt=pd.DataFrame({'City':city,name+"\'s "+plot_columns[i]:float(plot_data[plot_columns[i]]),plot_columns[i]:final[plot_columns[i]],crops[0]+'\'s '+plot_columns[i]:float(crop_data[crop_cols[i]])})
dt.plot()
plt.xlabel("City")
plt.ylabel(plot_columns[i])
plt.show() | dr1810/Agrolect | main.py | main.py | py | 2,546 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "pandas.read_csv",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "pandas.read_csv",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "pandas.DataFrame",
"line_number": 33,
"usage_type": "call"
},
{
"api_name": "sklearn.tree.DecisionT... |
72720227234 | import requests as req
# api url
url = "https://animechan.vercel.app/api"
def res_to_str(data):
character = data["character"]
anime = data["anime"]
quote = data["quote"]
res_string = f"\nQuote by: {character}\nFrom: {anime}\nQuote: {quote}\n"
return res_string
def get_data(full_url):
print("Getting the data.\n")
response = req.get(full_url)
data = response.json()
if type(data) == type([]):
for i in range(len(data)):
res_string = res_to_str(data[i])
print(f"{i + 1}. {res_string}")
elif type(data) == type({}):
res_string = res_to_str(data)
print(res_string)
api_options = [ "Get a random quote.", "Get random quote by anime name.", "Get 10 random quotes", "Get 10 quotes by anime name."]
while True:
for i in range(len(api_options)):
print(f"{i + 1}. {api_options[i]}")
user_choice = int(input("Choose an option: "))
if user_choice == 1:
get_data(f"{url}/random")
elif user_choice == 2:
anime_name = input("Enter Anime name:")
get_data(f"{url}/random/anime?title={anime_name}")
elif user_choice == 3:
get_data(f"{url}/quotes")
elif user_choice == 4:
anime_name = input("Enter Anime name:")
get_data(f"{url}/quotes/anime?title={anime_name}")
else:
print("Invalid Choice!") | imtiaz0307/Python | random_anime_quote_generator.py | random_anime_quote_generator.py | py | 1,363 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "requests.get",
"line_number": 15,
"usage_type": "call"
}
] |
17074239864 | from django.db import models
import uuid
class CategoriesOfProducts(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=64)
seq = models.IntegerField(blank=True, unique=True)
class Meta:
verbose_name = 'CategoryOfProducts'
verbose_name_plural = 'CategoriesOfProducts'
def __str__(self):
return self.name
class GroupsOfProducts(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False)
category_id = models.ForeignKey(CategoriesOfProducts, on_delete=models.PROTECT)
name = models.CharField(max_length=64)
description = models.TextField()
seq = models.IntegerField(blank=True, unique=True)
class Meta:
verbose_name = 'GroupOfProducts'
verbose_name_plural = 'GroupsOfProducts'
def __str__(self):
return self.name
class Products(models.Model):
id = models.AutoField(primary_key=True)
group_id = models.ForeignKey(GroupsOfProducts, on_delete=models.PROTECT)
name = models.CharField(max_length=64)
price = models.DecimalField(decimal_places=2, max_digits=10)
hidden = models.BooleanField(default=False)
class Meta:
verbose_name = 'Product'
verbose_name_plural = 'Products'
def __str__(self):
return self.name
| masian4eg/livest_test | stock_app/models.py | models.py | py | 1,347 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "django.db.models.Model",
"line_number": 5,
"usage_type": "attribute"
},
{
"api_name": "django.db.models",
"line_number": 5,
"usage_type": "name"
},
{
"api_name": "django.db.models.AutoField",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "... |
28176082453 | import io
import sys
import json
from smoke.io.wrap import demo as io_wrp_dm
from smoke.replay import demo as rply_dm
from smoke.replay.const import Data
class Chat(object):
def __init__(self, player, message):
self.player = player
self.message = message
class Player(object):
def __init__(self, steamid, username):
self.steamid = steamid
self.username = username
class Game(object):
def __init__(self, gameid, dire_players, radiant_players, chats, end_time, duration):
self.gameid = gameid
self.dire_players = dire_players
self.radiant_players = radiant_players
self.chats = chats
self.end_time = end_time
self.duration = duration
def parse_game(fn):
with io.open(fn, 'rb') as infile:
demo_io = io_wrp_dm.Wrap(infile)
demo_io.bootstrap()
parse = Data.UserMessages
demo = rply_dm.Demo(demo_io, parse=parse)
demo.bootstrap()
msgs = [msg for match in demo.play()
for msgs in match.user_messages.values()
for msg in msgs
if hasattr(msg, 'chat') and msg.chat]
demo.finish()
overview = demo.match.overview
radiant = [Player(p['steam_id'], p['player_name']) for p in overview['game']['players'] if p['game_team'] == 2]
dire = [Player(p['steam_id'], p['player_name']) for p in overview['game']['players'] if p['game_team'] == 3]
players = {p.username: p for p in (radiant + dire)}
chats = [Chat(players[msg.prefix], msg.text) for msg in msgs]
return Game(overview['game']['match_id'], dire, radiant, chats, overview['game']['end_time'], overview['playback']['time'])
if __name__ == '__main__':
filename = sys.argv[1]
for filename in sys.argv[1:]:
game = parse_game(filename)
print(json.dumps(game, default = lambda o : o.__dict__, indent = 2))
| qiemem/dotalang | messages.py | messages.py | py | 1,914 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "io.open",
"line_number": 29,
"usage_type": "call"
},
{
"api_name": "smoke.io.wrap.demo.Wrap",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "smoke.io.wrap.demo",
"line_number": 30,
"usage_type": "name"
},
{
"api_name": "smoke.replay.const... |
40296920999 | from django.core.mail import send_mail
from fitness.celery import app
from fitness.settings import EMAIL_HOST_USER
from django.utils.translation import gettext_lazy as _
@app.task
def send_code_to_email(code_user, email_user):
"""
Отправка письма с кодом подтверждения
"""
mail_sent = send_mail(
_('Код подтверждения'),
_(f'Забыл пароль, дорогой? :) Лови код для входа: {code_user}'),
EMAIL_HOST_USER,
[email_user],
fail_silently=False,
)
return mail_sent
| SimonaSoloduha/fitness | authentication/tasks.py | tasks.py | py | 605 | python | ru | code | 0 | github-code | 1 | [
{
"api_name": "django.core.mail.send_mail",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "fitness.settings.EMAIL_HOST_USER",
"line_number": 16,
"usage_type": "argument"
},
{
"api_name": "django.utils.translation.gettext_lazy",
"line_number": 14,
"usage_type": ... |
4340651422 | from datetime import datetime
from PySide2.QtCore import Qt, QAbstractItemModel, QModelIndex
from PySide2.QtGui import QBrush
from jal.constants import BookAccount, PredefinedAsset, CustomColor
from jal.widgets.helpers import g_tr
from jal.db.helpers import executeSQL
from jal.widgets.delegates import GridLinesDelegate
# ----------------------------------------------------------------------------------------------------------------------
class ReportTreeItem():
def __init__(self, begin, end, id, name, parent=None):
self._parent = parent
self._id = id
self.name = name
self._y_s = int(datetime.utcfromtimestamp(begin).strftime('%Y'))
self._m_s = int(datetime.utcfromtimestamp(begin).strftime('%-m'))
self._y_e = int(datetime.utcfromtimestamp(end).strftime('%Y'))
self._m_e = int(datetime.utcfromtimestamp(end).strftime('%-m'))
# amounts is 2D-array of per month amounts:
# amounts[year][month] - amount for particular month
# amounts[year][0] - total per year
self._amounts = [ [0] * 13 for _ in range(self._y_e - self._y_s + 1)]
self._total = 0
self._children = []
def appendChild(self, child):
child.setParent(self)
self._children.append(child)
def getChild(self, id):
if id < 0 or id > len(self._children):
return None
return self._children[id]
def childrenCount(self):
return len(self._children)
def dataCount(self):
if self._y_s == self._y_e:
return self._m_e - self._m_s + 3 # + 1 for year, + 1 for totals
else:
# 13 * (self._y_e - self._y_s - 1) + (self._m_e + 1) + (12 - self._m_s + 2) + 1 simplified to:
return 13 * (self._y_e - self._y_s - 1) + (self._m_e - self._m_s + 16)
def column2calendar(self, column):
# column 0 - name of row - return (-1, -1)
# then repetition of [year], [jan], [feb] ... [nov], [dec] - return (year, 0), (year, 1) ... (year, 12)
# last column is total value - return (0, 0)
if column == 0:
return -1, -1
if column == self.dataCount():
return 0, 0
if column == 1:
return self._y_s, 0
column = column + self._m_s - 2
year = self._y_s + int(column / 13)
month = column % 13
return year, month
def setParent(self, parent):
self._parent = parent
def getParent(self):
return self._parent
def addAmount(self, year, month, amount):
y_i = year - self._y_s
self._amounts[y_i][month] += amount
self._amounts[y_i][0] += amount
self._total += amount
if self._parent is not None:
self._parent.addAmount(year, month, amount)
# Return amount for given date and month or total amount if year==0
def getAmount(self, year, month):
if year == 0:
return self._total
y_i = year - self._y_s
return self._amounts[y_i][month]
def getLeafById(self, id):
if self._id == id:
return self
leaf = None
for child in self._children:
leaf = child.getLeafById(id)
return leaf
@property
def year_begin(self):
return self._y_s
@property
def month_begin(self):
return self._m_s
@property
def year_end(self):
return self._y_e
@property
def month_end(self):
return self._m_e
# ----------------------------------------------------------------------------------------------------------------------
class IncomeSpendingReport(QAbstractItemModel):
COL_LEVEL = 0
COL_ID = 1
COL_PID = 2
COL_NAME = 3
COL_PATH = 4
COL_TIMESTAMP = 5
COL_AMOUNT = 6
def __init__(self, parent_view):
super().__init__(parent_view)
self._view = parent_view
self._root = None
self._grid_delegate = None
self._report_delegate = None
self.month_name = [g_tr('Reports', 'Jan'),
g_tr('Reports', 'Feb'),
g_tr('Reports', 'Mar'),
g_tr('Reports', 'Apr'),
g_tr('Reports', 'May'),
g_tr('Reports', 'Jun'),
g_tr('Reports', 'Jul'),
g_tr('Reports', 'Aug'),
g_tr('Reports', 'Sep'),
g_tr('Reports', 'Oct'),
g_tr('Reports', 'Nov'),
g_tr('Reports', 'Dec')]
def rowCount(self, parent=None):
if not parent.isValid():
parent_item = self._root
else:
parent_item = parent.internalPointer()
if parent_item is not None:
return parent_item.childrenCount()
else:
return 0
def columnCount(self, parent=None):
if parent is None:
parent_item = self._root
elif not parent.isValid():
parent_item = self._root
else:
parent_item = parent.internalPointer()
if parent_item is not None:
return parent_item.dataCount() + 1 # + 1 for row header
else:
return 0
def headerData(self, section, orientation, role=Qt.DisplayRole):
if orientation == Qt.Horizontal:
if role == Qt.DisplayRole:
year, month = self._root.column2calendar(section)
if year < 0:
col_name = ''
elif year == 0:
col_name = g_tr("Reports", "TOTAL")
else:
if month == 0:
status = '▼' if self._view.isColumnHidden(section + 1) else '▶'
col_name = f"{year} " + status
else:
col_name = self.month_name[month-1]
return col_name
if role == Qt.TextAlignmentRole:
return Qt.AlignCenter
return None
def index(self, row, column, parent=None):
if not parent.isValid():
parent = self._root
else:
parent = parent.internalPointer()
child = parent.getChild(row)
if child:
return self.createIndex(row, column, child)
return QModelIndex()
def parent(self, index=None):
if not index.isValid():
return QModelIndex()
child_item = index.internalPointer()
parent_item = child_item.getParent()
if parent_item == self._root:
return QModelIndex()
return self.createIndex(0, 0, parent_item)
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return None
item = index.internalPointer()
if role == Qt.DisplayRole:
if index.column() == 0:
return item.name
else:
year, month = self._root.column2calendar(index.column())
return f"{item.getAmount(year, month):,.2f}"
if role == Qt.ForegroundRole:
if index.column() != 0:
year, month = self._root.column2calendar(index.column())
if item.getAmount(year, month) == 0:
return QBrush(CustomColor.Grey)
if role == Qt.TextAlignmentRole:
if index.column() == 0:
return Qt.AlignLeft
else:
return Qt.AlignRight
return None
def configureView(self):
self._grid_delegate = GridLinesDelegate(self._view)
for column in range(self.columnCount()):
self._view.setItemDelegateForColumn(column, self._grid_delegate)
if column == 0:
self._view.setColumnWidth(column, 300)
else:
self._view.setColumnWidth(column, 100)
font = self._view.header().font()
font.setBold(True)
self._view.header().setFont(font)
self._view.header().sectionDoubleClicked.connect(self.toggeYearColumns)
def toggeYearColumns(self, section):
year, month = self._root.column2calendar(section)
if year >= 0 and month == 0:
if year == self._root.year_begin:
year_columns = 12 - self._root.month_begin + 1
elif year == self._root.year_end:
year_columns = self._root.month_end
else:
year_columns = 12
for i in range(year_columns):
new_state = not self._view.isColumnHidden(section + i + 1)
self._view.setColumnHidden(section + i + 1, new_state)
self.headerDataChanged.emit(Qt.Horizontal, section, section)
def prepare(self, begin, end, account_id, group_dates):
query = executeSQL("WITH "
"_months AS (SELECT strftime('%s', datetime(timestamp, 'unixepoch', 'start of month') ) "
"AS month, asset_id, MAX(timestamp) AS last_timestamp "
"FROM quotes AS q "
"LEFT JOIN assets AS a ON q.asset_id=a.id "
"WHERE a.type_id=:asset_money "
"GROUP BY month, asset_id), "
"_category_amounts AS ( "
"SELECT strftime('%s', datetime(t.timestamp, 'unixepoch', 'start of month')) AS month_start, "
"t.category_id AS id, sum(-t.amount * coalesce(q.quote, 1)) AS amount "
"FROM ledger AS t "
"LEFT JOIN _months AS d ON month_start = d.month AND t.asset_id = d.asset_id "
"LEFT JOIN quotes AS q ON d.last_timestamp = q.timestamp AND t.asset_id = q.asset_id "
"WHERE (t.book_account=:book_costs OR t.book_account=:book_incomes) "
"AND t.timestamp>=:begin AND t.timestamp<=:end "
"GROUP BY month_start, category_id) "
"SELECT ct.level, ct.id, c.pid, c.name, ct.path, ca.month_start, "
"coalesce(ca.amount, 0) AS amount "
"FROM categories_tree AS ct "
"LEFT JOIN _category_amounts AS ca ON ct.id=ca.id "
"LEFT JOIN categories AS c ON ct.id=c.id "
"ORDER BY path, month_start",
[(":asset_money", PredefinedAsset.Money), (":book_costs", BookAccount.Costs),
(":book_incomes", BookAccount.Incomes), (":begin", begin), (":end", end)])
query.setForwardOnly(True)
self._root = ReportTreeItem(begin, end, -1, "ROOT") # invisible root
self._root.appendChild(ReportTreeItem(begin, end, 0, g_tr("Reports", "TOTAL"))) # visible root
indexes = range(query.record().count())
while query.next():
values = list(map(query.value, indexes))
leaf = self._root.getLeafById(values[self.COL_ID])
if leaf is None:
parent = self._root.getLeafById(values[self.COL_PID])
leaf = ReportTreeItem(begin, end, values[self.COL_ID], values[self.COL_NAME], parent)
parent.appendChild(leaf)
if values[self.COL_TIMESTAMP]:
year = int(datetime.utcfromtimestamp(int(values[self.COL_TIMESTAMP])).strftime('%Y'))
month = int(datetime.utcfromtimestamp(int(values[self.COL_TIMESTAMP])).strftime('%-m'))
leaf.addAmount(year, month, values[self.COL_AMOUNT])
self.modelReset.emit()
self._view.expandAll()
| iliakan/jal | jal/reports/income_spending_report.py | income_spending_report.py | py | 11,723 | python | en | code | null | github-code | 1 | [
{
"api_name": "datetime.datetime.utcfromtimestamp",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "datetime.datetime",
"line_number": 16,
"usage_type": "name"
},
{
"api_name": "datetime.datetime.utcfromtimestamp",
"line_number": 17,
"usage_type": "call"
},
... |
19752680843 | import json
import os
from datetime import datetime
from flask import Flask
from flask import request
from flask import Response
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from kaner.context import GlobalContext as gctx
from kaner.adapter.tokenizer import CharTokenizer
from kaner.adapter.knowledge import Gazetteer
from kaner.trainer import NERTrainer, TrainerConfig
from kaner.common import load_json
gctx.init()
__APP__ = Flask(__name__)
__TRAINER__ = None
@__APP__.route("/", methods=["GET"])
def _hello():
"""Return welcome!"""
return "<h1>Welcome to KANER!</h1>"
@__APP__.route("/kaner/predict", methods=["POST", "OPTIONS"])
def _predict_span():
"""
Given a list of text, predicting their spans. The format of the requested data should be as the same as
the following example:
data = {"texts": ["document1", "document2", ...]}
"""
start_time = datetime.now()
rsp = {
"success": True
}
try:
data = json.loads(request.data)
if "texts" not in data.keys() or not isinstance(data["texts"], list):
rsp["success"] = False
rsp["info"] = "The requested data should contain a list of document named `texts`."
return json.dumps(rsp, ensure_ascii=False, indent=2)
if len(data["texts"]) <= 0:
rsp["success"] = False
rsp["info"] = "The length of the list `texts` should be greater than 0"
return json.dumps(rsp, ensure_ascii=False, indent=2)
for i in range(len(data["texts"])):
text = data["texts"][i]
if not isinstance(text, str) or len(text) == 0:
rsp["success"] = False
rsp["info"] = "The {0}-th element in the list is not a string or is empty. {1}。".format(i + 1, text)
return json.dumps(rsp, ensure_ascii=False, indent=2)
if "debug" not in data.keys():
data["debug"] = False
global __TRAINER__
if __TRAINER__ is None:
rsp["success"] = False
rsp["info"] = "The server is not prepared. Please wait a while..."
else:
results = []
for _, text in enumerate(data["texts"]):
fragments = []
for i in range(0, len(text), __TRAINER__._config.max_seq_len):
fragments.append(text[i: i + __TRAINER__._config.max_seq_len])
raw_result = __TRAINER__.predict(fragments)
result = {
"text": text,
"spans": []
}
for i in range(0, len(text), __TRAINER__._config.max_seq_len):
idx = i//__TRAINER__._config.max_seq_len
for j in range(len(raw_result[idx]["spans"])):
raw_result[idx]["spans"][j]["start"] += i
raw_result[idx]["spans"][j]["end"] += i
result["spans"].extend(raw_result[idx]["spans"])
results.append(result)
rsp["data"] = results
rsp["model"] = __TRAINER__._config.model
rsp["dataset"] = __TRAINER__._config.dataset
except RuntimeError as runtime_error:
rsp["success"] = False
rsp["info"] = "Runtime Error {}.".format(str(runtime_error))
except json.decoder.JSONDecodeError as json_decode_error:
rsp["success"] = False
rsp["info"] = "Parsing JSON String Error {}.".format(str(json_decode_error))
except Exception as exception:
rsp["success"] = False
rsp["info"] = str(exception)
rsp["time"] = (datetime.now() - start_time).seconds
rsp = Response(json.dumps(rsp, ensure_ascii=False, indent=2))
rsp.headers["content-type"] = "application/json"
# A CORS preflight request is a CORS request that checks to see if the CORS protocol is
# understood and a server is aware using specific methods and headers.
# https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
rsp.headers["Access-Control-Allow-Origin"] = "*"
rsp.headers["Access-Control-Allow-Headers"] = "Origin, X-Requested-With, Content-Type, Accept"
return rsp
def serve(model_folder: str, host: str, port: int) -> None:
"""
Start a service for predicting texts.
Args:
model_folder (str): The folder where the trained model exists.
host (str): Address.
port (str): Listen port.
"""
options = load_json("utf-8", model_folder, "config.json")
options["output_folder"] = model_folder
options["identity"] = os.path.basename(os.path.normpath(model_folder))
config = TrainerConfig(options)
tokenizer = CharTokenizer(model_folder)
gazetteer = Gazetteer(model_folder)
out_adapter = gctx.create_outadapter(config.out_adapter, dataset_folder=model_folder, file_name="labels")
in_adapters = (
gctx.create_inadapter(
config.in_adapter, dataset=[], tokenizer=tokenizer, out_adapter=out_adapter, gazetteer=gazetteer,
**config.hyperparameters
)
for _ in range(3)
)
collate_fn = gctx.create_batcher(
config.model, input_pad=tokenizer.pad_id, output_pad=out_adapter.unk_id, lexicon_pad=gazetteer.pad_id, device=config.device
)
model = gctx.create_model(config.model, **config.hyperparameters)
trainer = NERTrainer(
config, tokenizer, in_adapters, out_adapter, collate_fn, model, None,
gctx.create_traincallback(config.model), gctx.create_testcallback(config.model)
)
trainer.startp()
global __TRAINER__, __APP__
__TRAINER__ = trainer
server = HTTPServer(WSGIContainer(__APP__))
print("-> :: Web Service :: ")
print("service starts at \x1b[1;32;40mhttp://{0}:{1}\x1b[0m".format(host, port))
server.listen(port, host)
IOLoop.instance().start()
| knowledgeresearch/kaner | kaner/service.py | service.py | py | 5,904 | python | en | code | 4 | github-code | 1 | [
{
"api_name": "kaner.context.GlobalContext.init",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "kaner.context.GlobalContext",
"line_number": 19,
"usage_type": "name"
},
{
"api_name": "flask.Flask",
"line_number": 20,
"usage_type": "call"
},
{
"api_name... |
13457456760 | from spacy.lang.en import English
import numpy as np
import srsly
from flask import Flask, render_template
patterns = srsly.read_jsonl("Backend/skill_patterns.jsonl")
nlp = English()
ruler = nlp.add_pipe("entity_ruler")
ruler.add_patterns(patterns)
def extract_keywords(txt):
doc = nlp(txt)
keywords = list(doc.ents)
# remove duplicates
keywords = [str(k) for k in keywords]
keywords = list(set(keywords))
return keywords
def calculate_score(resume_kws, job_kws):
resume_kws = np.array(resume_kws)
job_kws = np.array(job_kws)
match_count = 0
for i in resume_kws:
for j in job_kws:
if i == j:
match_count += 1
continue
score = 2 * match_count / (resume_kws.size + job_kws.size)
return score
def calculate_similarity(resume_str, job_str):
resume_keywords = extract_keywords(resume_str)
job_keywords = extract_keywords(job_str)
score = calculate_score(resume_keywords, job_keywords)
return score
| MAlshaik/Joblify | Backend/analyzer.py | analyzer.py | py | 1,008 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "srsly.read_jsonl",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "spacy.lang.en.English",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"... |
11510348772 | # Released under the MIT License. See LICENSE for details.
#
"""Various functionality related to achievements."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
import babase
import bascenev1
import bauiv1
if TYPE_CHECKING:
from typing import Any, Sequence
import baclassic
# This could use some cleanup.
# We wear the cone of shame.
# pylint: disable=too-many-lines
# pylint: disable=too-many-statements
# pylint: disable=too-many-locals
# pylint: disable=too-many-branches
# FIXME: We should probably point achievements
# at coop levels instead of hard-coding names.
# (so level name substitution works right and whatnot).
ACH_LEVEL_NAMES = {
'Boom Goes the Dynamite': 'Pro Onslaught',
'Boxer': 'Onslaught Training',
'Flawless Victory': 'Rookie Onslaught',
'Gold Miner': 'Uber Onslaught',
'Got the Moves': 'Uber Football',
'Last Stand God': 'The Last Stand',
'Last Stand Master': 'The Last Stand',
'Last Stand Wizard': 'The Last Stand',
'Mine Games': 'Rookie Onslaught',
'Off You Go Then': 'Onslaught Training',
'Onslaught God': 'Infinite Onslaught',
'Onslaught Master': 'Infinite Onslaught',
'Onslaught Training Victory': 'Onslaught Training',
'Onslaught Wizard': 'Infinite Onslaught',
'Precision Bombing': 'Pro Runaround',
'Pro Boxer': 'Pro Onslaught',
'Pro Football Shutout': 'Pro Football',
'Pro Football Victory': 'Pro Football',
'Pro Onslaught Victory': 'Pro Onslaught',
'Pro Runaround Victory': 'Pro Runaround',
'Rookie Football Shutout': 'Rookie Football',
'Rookie Football Victory': 'Rookie Football',
'Rookie Onslaught Victory': 'Rookie Onslaught',
'Runaround God': 'Infinite Runaround',
'Runaround Master': 'Infinite Runaround',
'Runaround Wizard': 'Infinite Runaround',
'Stayin\' Alive': 'Uber Runaround',
'Super Mega Punch': 'Pro Football',
'Super Punch': 'Rookie Football',
'TNT Terror': 'Uber Onslaught',
'The Great Wall': 'Uber Runaround',
'The Wall': 'Pro Runaround',
'Uber Football Shutout': 'Uber Football',
'Uber Football Victory': 'Uber Football',
'Uber Onslaught Victory': 'Uber Onslaught',
'Uber Runaround Victory': 'Uber Runaround',
}
class AchievementSubsystem:
"""Subsystem for achievement handling.
Category: **App Classes**
Access the single shared instance of this class at 'ba.app.ach'.
"""
def __init__(self) -> None:
self.achievements: list[Achievement] = []
self.achievements_to_display: (
list[tuple[baclassic.Achievement, bool]]
) = []
self.achievement_display_timer: bascenev1.BaseTimer | None = None
self.last_achievement_display_time: float = 0.0
self.achievement_completion_banner_slots: set[int] = set()
self._init_achievements()
def _init_achievements(self) -> None:
"""Fill in available achievements."""
achs = self.achievements
# 5
achs.append(
Achievement('In Control', 'achievementInControl', (1, 1, 1), '', 5)
)
# 15
achs.append(
Achievement(
'Sharing is Caring',
'achievementSharingIsCaring',
(1, 1, 1),
'',
15,
)
)
# 10
achs.append(
Achievement(
'Dual Wielding', 'achievementDualWielding', (1, 1, 1), '', 10
)
)
# 10
achs.append(
Achievement(
'Free Loader', 'achievementFreeLoader', (1, 1, 1), '', 10
)
)
# 20
achs.append(
Achievement(
'Team Player', 'achievementTeamPlayer', (1, 1, 1), '', 20
)
)
# 5
achs.append(
Achievement(
'Onslaught Training Victory',
'achievementOnslaught',
(1, 1, 1),
'Default:Onslaught Training',
5,
)
)
# 5
achs.append(
Achievement(
'Off You Go Then',
'achievementOffYouGo',
(1, 1.1, 1.3),
'Default:Onslaught Training',
5,
)
)
# 10
achs.append(
Achievement(
'Boxer',
'achievementBoxer',
(1, 0.6, 0.6),
'Default:Onslaught Training',
10,
hard_mode_only=True,
)
)
# 10
achs.append(
Achievement(
'Rookie Onslaught Victory',
'achievementOnslaught',
(0.5, 1.4, 0.6),
'Default:Rookie Onslaught',
10,
)
)
# 10
achs.append(
Achievement(
'Mine Games',
'achievementMine',
(1, 1, 1.4),
'Default:Rookie Onslaught',
10,
)
)
# 15
achs.append(
Achievement(
'Flawless Victory',
'achievementFlawlessVictory',
(1, 1, 1),
'Default:Rookie Onslaught',
15,
hard_mode_only=True,
)
)
# 10
achs.append(
Achievement(
'Rookie Football Victory',
'achievementFootballVictory',
(1.0, 1, 0.6),
'Default:Rookie Football',
10,
)
)
# 10
achs.append(
Achievement(
'Super Punch',
'achievementSuperPunch',
(1, 1, 1.8),
'Default:Rookie Football',
10,
)
)
# 15
achs.append(
Achievement(
'Rookie Football Shutout',
'achievementFootballShutout',
(1, 1, 1),
'Default:Rookie Football',
15,
hard_mode_only=True,
)
)
# 15
achs.append(
Achievement(
'Pro Onslaught Victory',
'achievementOnslaught',
(0.3, 1, 2.0),
'Default:Pro Onslaught',
15,
)
)
# 15
achs.append(
Achievement(
'Boom Goes the Dynamite',
'achievementTNT',
(1.4, 1.2, 0.8),
'Default:Pro Onslaught',
15,
)
)
# 20
achs.append(
Achievement(
'Pro Boxer',
'achievementBoxer',
(2, 2, 0),
'Default:Pro Onslaught',
20,
hard_mode_only=True,
)
)
# 15
achs.append(
Achievement(
'Pro Football Victory',
'achievementFootballVictory',
(1.3, 1.3, 2.0),
'Default:Pro Football',
15,
)
)
# 15
achs.append(
Achievement(
'Super Mega Punch',
'achievementSuperPunch',
(2, 1, 0.6),
'Default:Pro Football',
15,
)
)
# 20
achs.append(
Achievement(
'Pro Football Shutout',
'achievementFootballShutout',
(0.7, 0.7, 2.0),
'Default:Pro Football',
20,
hard_mode_only=True,
)
)
# 15
achs.append(
Achievement(
'Pro Runaround Victory',
'achievementRunaround',
(1, 1, 1),
'Default:Pro Runaround',
15,
)
)
# 20
achs.append(
Achievement(
'Precision Bombing',
'achievementCrossHair',
(1, 1, 1.3),
'Default:Pro Runaround',
20,
hard_mode_only=True,
)
)
# 25
achs.append(
Achievement(
'The Wall',
'achievementWall',
(1, 0.7, 0.7),
'Default:Pro Runaround',
25,
hard_mode_only=True,
)
)
# 30
achs.append(
Achievement(
'Uber Onslaught Victory',
'achievementOnslaught',
(2, 2, 1),
'Default:Uber Onslaught',
30,
)
)
# 30
achs.append(
Achievement(
'Gold Miner',
'achievementMine',
(2, 1.6, 0.2),
'Default:Uber Onslaught',
30,
hard_mode_only=True,
)
)
# 30
achs.append(
Achievement(
'TNT Terror',
'achievementTNT',
(2, 1.8, 0.3),
'Default:Uber Onslaught',
30,
hard_mode_only=True,
)
)
# 30
achs.append(
Achievement(
'Uber Football Victory',
'achievementFootballVictory',
(1.8, 1.4, 0.3),
'Default:Uber Football',
30,
)
)
# 30
achs.append(
Achievement(
'Got the Moves',
'achievementGotTheMoves',
(2, 1, 0),
'Default:Uber Football',
30,
hard_mode_only=True,
)
)
# 40
achs.append(
Achievement(
'Uber Football Shutout',
'achievementFootballShutout',
(2, 2, 0),
'Default:Uber Football',
40,
hard_mode_only=True,
)
)
# 30
achs.append(
Achievement(
'Uber Runaround Victory',
'achievementRunaround',
(1.5, 1.2, 0.2),
'Default:Uber Runaround',
30,
)
)
# 40
achs.append(
Achievement(
'The Great Wall',
'achievementWall',
(2, 1.7, 0.4),
'Default:Uber Runaround',
40,
hard_mode_only=True,
)
)
# 40
achs.append(
Achievement(
'Stayin\' Alive',
'achievementStayinAlive',
(2, 2, 1),
'Default:Uber Runaround',
40,
hard_mode_only=True,
)
)
# 20
achs.append(
Achievement(
'Last Stand Master',
'achievementMedalSmall',
(2, 1.5, 0.3),
'Default:The Last Stand',
20,
hard_mode_only=True,
)
)
# 40
achs.append(
Achievement(
'Last Stand Wizard',
'achievementMedalMedium',
(2, 1.5, 0.3),
'Default:The Last Stand',
40,
hard_mode_only=True,
)
)
# 60
achs.append(
Achievement(
'Last Stand God',
'achievementMedalLarge',
(2, 1.5, 0.3),
'Default:The Last Stand',
60,
hard_mode_only=True,
)
)
# 5
achs.append(
Achievement(
'Onslaught Master',
'achievementMedalSmall',
(0.7, 1, 0.7),
'Challenges:Infinite Onslaught',
5,
)
)
# 15
achs.append(
Achievement(
'Onslaught Wizard',
'achievementMedalMedium',
(0.7, 1.0, 0.7),
'Challenges:Infinite Onslaught',
15,
)
)
# 30
achs.append(
Achievement(
'Onslaught God',
'achievementMedalLarge',
(0.7, 1.0, 0.7),
'Challenges:Infinite Onslaught',
30,
)
)
# 5
achs.append(
Achievement(
'Runaround Master',
'achievementMedalSmall',
(1.0, 1.0, 1.2),
'Challenges:Infinite Runaround',
5,
)
)
# 15
achs.append(
Achievement(
'Runaround Wizard',
'achievementMedalMedium',
(1.0, 1.0, 1.2),
'Challenges:Infinite Runaround',
15,
)
)
# 30
achs.append(
Achievement(
'Runaround God',
'achievementMedalLarge',
(1.0, 1.0, 1.2),
'Challenges:Infinite Runaround',
30,
)
)
def award_local_achievement(self, achname: str) -> None:
"""For non-game-based achievements such as controller-connection."""
plus = babase.app.plus
if plus is None:
logging.warning('achievements require plus feature-set')
return
try:
ach = self.get_achievement(achname)
if not ach.complete:
# Report new achievements to the game-service.
plus.report_achievement(achname)
# And to our account.
plus.add_v1_account_transaction(
{'type': 'ACHIEVEMENT', 'name': achname}
)
# Now attempt to show a banner.
self.display_achievement_banner(achname)
except Exception:
logging.exception('Error in award_local_achievement.')
def display_achievement_banner(self, achname: str) -> None:
"""Display a completion banner for an achievement.
(internal)
Used for server-driven achievements.
"""
try:
# FIXME: Need to get these using the UI context or some other
# purely local context somehow instead of trying to inject these
# into whatever activity happens to be active
# (since that won't work while in client mode).
activity = bascenev1.get_foreground_host_activity()
if activity is not None:
with activity.context:
self.get_achievement(achname).announce_completion()
except Exception:
logging.exception('Error in display_achievement_banner.')
def set_completed_achievements(self, achs: Sequence[str]) -> None:
"""Set the current state of completed achievements.
(internal)
All achievements not included here will be set incomplete.
"""
# Note: This gets called whenever game-center/game-circle/etc tells
# us which achievements we currently have. We always defer to them,
# even if that means we have to un-set an achievement we think we have.
cfg = babase.app.config
cfg['Achievements'] = {}
for a_name in achs:
self.get_achievement(a_name).set_complete(True)
cfg.commit()
def get_achievement(self, name: str) -> Achievement:
"""Return an Achievement by name."""
achs = [a for a in self.achievements if a.name == name]
assert len(achs) < 2
if not achs:
raise ValueError("Invalid achievement name: '" + name + "'")
return achs[0]
def achievements_for_coop_level(self, level_name: str) -> list[Achievement]:
"""Given a level name, return achievements available for it."""
# For the Easy campaign we return achievements for the Default
# campaign too. (want the user to see what achievements are part of the
# level even if they can't unlock them all on easy mode).
return [
a
for a in self.achievements
if a.level_name
in (level_name, level_name.replace('Easy', 'Default'))
]
def _test(self) -> None:
"""For testing achievement animations."""
def testcall1() -> None:
self.achievements[0].announce_completion()
self.achievements[1].announce_completion()
self.achievements[2].announce_completion()
def testcall2() -> None:
self.achievements[3].announce_completion()
self.achievements[4].announce_completion()
self.achievements[5].announce_completion()
bascenev1.basetimer(3.0, testcall1)
bascenev1.basetimer(7.0, testcall2)
def _get_ach_mult(include_pro_bonus: bool = False) -> int:
"""Return the multiplier for achievement pts.
(just for display; changing this here won't affect actual rewards)
"""
plus = babase.app.plus
classic = babase.app.classic
if plus is None or classic is None:
return 5
val: int = plus.get_v1_account_misc_read_val('achAwardMult', 5)
assert isinstance(val, int)
if include_pro_bonus and classic.accounts.have_pro():
val *= 2
return val
def _display_next_achievement() -> None:
# Pull the first achievement off the list and display it, or kill the
# display-timer if the list is empty.
app = babase.app
assert app.classic is not None
ach_ss = app.classic.ach
if app.classic.ach.achievements_to_display:
try:
ach, sound = ach_ss.achievements_to_display.pop(0)
ach.show_completion_banner(sound)
except Exception:
logging.exception('Error in _display_next_achievement.')
ach_ss.achievements_to_display = []
ach_ss.achievement_display_timer = None
else:
ach_ss.achievement_display_timer = None
class Achievement:
"""Represents attributes and state for an individual achievement.
Category: **App Classes**
"""
def __init__(
self,
name: str,
icon_name: str,
icon_color: Sequence[float],
level_name: str,
award: int,
hard_mode_only: bool = False,
):
self._name = name
self._icon_name = icon_name
self._icon_color: Sequence[float] = list(icon_color) + [1]
self._level_name = level_name
self._completion_banner_slot: int | None = None
self._award = award
self._hard_mode_only = hard_mode_only
@property
def name(self) -> str:
"""The name of this achievement."""
return self._name
@property
def level_name(self) -> str:
"""The name of the level this achievement applies to."""
return self._level_name
def get_icon_ui_texture(self, complete: bool) -> bauiv1.Texture:
"""Return the icon texture to display for this achievement"""
return bauiv1.gettexture(
self._icon_name if complete else 'achievementEmpty'
)
def get_icon_texture(self, complete: bool) -> bascenev1.Texture:
"""Return the icon texture to display for this achievement"""
return bascenev1.gettexture(
self._icon_name if complete else 'achievementEmpty'
)
def get_icon_color(self, complete: bool) -> Sequence[float]:
"""Return the color tint for this Achievement's icon."""
if complete:
return self._icon_color
return 1.0, 1.0, 1.0, 0.6
@property
def hard_mode_only(self) -> bool:
"""Whether this Achievement is only unlockable in hard-mode."""
return self._hard_mode_only
@property
def complete(self) -> bool:
"""Whether this Achievement is currently complete."""
val: bool = self._getconfig()['Complete']
assert isinstance(val, bool)
return val
def announce_completion(self, sound: bool = True) -> None:
"""Kick off an announcement for this achievement's completion."""
app = babase.app
plus = app.plus
classic = app.classic
if plus is None or classic is None:
logging.warning('ach account_completion not available.')
return
ach_ss = classic.ach
# Even though there are technically achievements when we're not
# signed in, lets not show them (otherwise we tend to get
# confusing 'controller connected' achievements popping up while
# waiting to sign in which can be confusing).
if plus.get_v1_account_state() != 'signed_in':
return
# If we're being freshly complete, display/report it and whatnot.
if (self, sound) not in ach_ss.achievements_to_display:
ach_ss.achievements_to_display.append((self, sound))
# If there's no achievement display timer going, kick one off
# (if one's already running it will pick this up before it dies).
# Need to check last time too; its possible our timer wasn't able to
# clear itself if an activity died and took it down with it.
if (
ach_ss.achievement_display_timer is None
or babase.apptime() - ach_ss.last_achievement_display_time > 2.0
) and bascenev1.getactivity(doraise=False) is not None:
ach_ss.achievement_display_timer = bascenev1.BaseTimer(
1.0, _display_next_achievement, repeat=True
)
# Show the first immediately.
_display_next_achievement()
def set_complete(self, complete: bool = True) -> None:
"""Set an achievement's completed state.
note this only sets local state; use a transaction to
actually award achievements.
"""
config = self._getconfig()
if complete != config['Complete']:
config['Complete'] = complete
@property
def display_name(self) -> babase.Lstr:
"""Return a babase.Lstr for this Achievement's name."""
name: babase.Lstr | str
try:
if self._level_name != '':
campaignname, campaign_level = self._level_name.split(':')
classic = babase.app.classic
assert classic is not None
name = (
classic.getcampaign(campaignname)
.getlevel(campaign_level)
.displayname
)
else:
name = ''
except Exception:
name = ''
logging.exception('Error calcing achievement display-name.')
return babase.Lstr(
resource='achievements.' + self._name + '.name',
subs=[('${LEVEL}', name)],
)
@property
def description(self) -> babase.Lstr:
"""Get a babase.Lstr for the Achievement's brief description."""
if (
'description'
in babase.app.lang.get_resource('achievements')[self._name]
):
return babase.Lstr(
resource='achievements.' + self._name + '.description'
)
return babase.Lstr(
resource='achievements.' + self._name + '.descriptionFull'
)
@property
def description_complete(self) -> babase.Lstr:
"""Get a babase.Lstr for the Achievement's description when complete."""
if (
'descriptionComplete'
in babase.app.lang.get_resource('achievements')[self._name]
):
return babase.Lstr(
resource='achievements.' + self._name + '.descriptionComplete'
)
return babase.Lstr(
resource='achievements.' + self._name + '.descriptionFullComplete'
)
@property
def description_full(self) -> babase.Lstr:
"""Get a babase.Lstr for the Achievement's full description."""
return babase.Lstr(
resource='achievements.' + self._name + '.descriptionFull',
subs=[
(
'${LEVEL}',
babase.Lstr(
translate=(
'coopLevelNames',
ACH_LEVEL_NAMES.get(self._name, '?'),
)
),
)
],
)
@property
def description_full_complete(self) -> babase.Lstr:
"""Get a babase.Lstr for the Achievement's full desc. when completed."""
return babase.Lstr(
resource='achievements.' + self._name + '.descriptionFullComplete',
subs=[
(
'${LEVEL}',
babase.Lstr(
translate=(
'coopLevelNames',
ACH_LEVEL_NAMES.get(self._name, '?'),
)
),
)
],
)
def get_award_ticket_value(self, include_pro_bonus: bool = False) -> int:
"""Get the ticket award value for this achievement."""
plus = babase.app.plus
if plus is None:
return 0
val: int = plus.get_v1_account_misc_read_val(
'achAward.' + self._name, self._award
) * _get_ach_mult(include_pro_bonus)
assert isinstance(val, int)
return val
@property
def power_ranking_value(self) -> int:
"""Get the power-ranking award value for this achievement."""
plus = babase.app.plus
if plus is None:
return 0
val: int = plus.get_v1_account_misc_read_val(
'achLeaguePoints.' + self._name, self._award
)
assert isinstance(val, int)
return val
def create_display(
self,
x: float,
y: float,
delay: float,
outdelay: float | None = None,
color: Sequence[float] | None = None,
style: str = 'post_game',
) -> list[bascenev1.Actor]:
"""Create a display for the Achievement.
Shows the Achievement icon, name, and description.
"""
# pylint: disable=cyclic-import
from bascenev1 import CoopSession
from bascenev1lib.actor.image import Image
from bascenev1lib.actor.text import Text
# Yeah this needs cleaning up.
if style == 'post_game':
in_game_colors = False
in_main_menu = False
h_attach = Text.HAttach.CENTER
v_attach = Text.VAttach.CENTER
attach = Image.Attach.CENTER
elif style == 'in_game':
in_game_colors = True
in_main_menu = False
h_attach = Text.HAttach.LEFT
v_attach = Text.VAttach.TOP
attach = Image.Attach.TOP_LEFT
elif style == 'news':
in_game_colors = True
in_main_menu = True
h_attach = Text.HAttach.CENTER
v_attach = Text.VAttach.TOP
attach = Image.Attach.TOP_CENTER
else:
raise ValueError('invalid style "' + style + '"')
# Attempt to determine what campaign we're in
# (so we know whether to show "hard mode only").
if in_main_menu:
hmo = False
else:
try:
session = bascenev1.getsession()
if isinstance(session, CoopSession):
campaign = session.campaign
assert campaign is not None
hmo = self._hard_mode_only and campaign.name == 'Easy'
else:
hmo = False
except Exception:
logging.exception('Error determining campaign.')
hmo = False
objs: list[bascenev1.Actor]
if in_game_colors:
objs = []
out_delay_fin = (delay + outdelay) if outdelay is not None else None
if color is not None:
cl1 = (2.0 * color[0], 2.0 * color[1], 2.0 * color[2], color[3])
cl2 = color
else:
cl1 = (1.5, 1.5, 2, 1.0)
cl2 = (0.8, 0.8, 1.0, 1.0)
if hmo:
cl1 = (cl1[0], cl1[1], cl1[2], cl1[3] * 0.6)
cl2 = (cl2[0], cl2[1], cl2[2], cl2[3] * 0.2)
objs.append(
Image(
self.get_icon_texture(False),
host_only=True,
color=cl1,
position=(x - 25, y + 5),
attach=attach,
transition=Image.Transition.FADE_IN,
transition_delay=delay,
vr_depth=4,
transition_out_delay=out_delay_fin,
scale=(40, 40),
).autoretain()
)
txt = self.display_name
txt_s = 0.85
txt_max_w = 300
objs.append(
Text(
txt,
host_only=True,
maxwidth=txt_max_w,
position=(x, y + 2),
transition=Text.Transition.FADE_IN,
scale=txt_s,
flatness=0.6,
shadow=0.5,
h_attach=h_attach,
v_attach=v_attach,
color=cl2,
transition_delay=delay + 0.05,
transition_out_delay=out_delay_fin,
).autoretain()
)
txt2_s = 0.62
txt2_max_w = 400
objs.append(
Text(
self.description_full if in_main_menu else self.description,
host_only=True,
maxwidth=txt2_max_w,
position=(x, y - 14),
transition=Text.Transition.FADE_IN,
vr_depth=-5,
h_attach=h_attach,
v_attach=v_attach,
scale=txt2_s,
flatness=1.0,
shadow=0.5,
color=cl2,
transition_delay=delay + 0.1,
transition_out_delay=out_delay_fin,
).autoretain()
)
if hmo:
txtactor = Text(
babase.Lstr(resource='difficultyHardOnlyText'),
host_only=True,
maxwidth=txt2_max_w * 0.7,
position=(x + 60, y + 5),
transition=Text.Transition.FADE_IN,
vr_depth=-5,
h_attach=h_attach,
v_attach=v_attach,
h_align=Text.HAlign.CENTER,
v_align=Text.VAlign.CENTER,
scale=txt_s * 0.8,
flatness=1.0,
shadow=0.5,
color=(1, 1, 0.6, 1),
transition_delay=delay + 0.1,
transition_out_delay=out_delay_fin,
).autoretain()
txtactor.node.rotate = 10
objs.append(txtactor)
# Ticket-award.
award_x = -100
objs.append(
Text(
babase.charstr(babase.SpecialChar.TICKET),
host_only=True,
position=(x + award_x + 33, y + 7),
transition=Text.Transition.FADE_IN,
scale=1.5,
h_attach=h_attach,
v_attach=v_attach,
h_align=Text.HAlign.CENTER,
v_align=Text.VAlign.CENTER,
color=(1, 1, 1, 0.2 if hmo else 0.4),
transition_delay=delay + 0.05,
transition_out_delay=out_delay_fin,
).autoretain()
)
objs.append(
Text(
'+' + str(self.get_award_ticket_value()),
host_only=True,
position=(x + award_x + 28, y + 16),
transition=Text.Transition.FADE_IN,
scale=0.7,
flatness=1,
h_attach=h_attach,
v_attach=v_attach,
h_align=Text.HAlign.CENTER,
v_align=Text.VAlign.CENTER,
color=cl2,
transition_delay=delay + 0.05,
transition_out_delay=out_delay_fin,
).autoretain()
)
else:
complete = self.complete
objs = []
c_icon = self.get_icon_color(complete)
if hmo and not complete:
c_icon = (c_icon[0], c_icon[1], c_icon[2], c_icon[3] * 0.3)
objs.append(
Image(
self.get_icon_texture(complete),
host_only=True,
color=c_icon,
position=(x - 25, y + 5),
attach=attach,
vr_depth=4,
transition=Image.Transition.IN_RIGHT,
transition_delay=delay,
transition_out_delay=None,
scale=(40, 40),
).autoretain()
)
if complete:
objs.append(
Image(
bascenev1.gettexture('achievementOutline'),
host_only=True,
mesh_transparent=bascenev1.getmesh(
'achievementOutline'
),
color=(2, 1.4, 0.4, 1),
vr_depth=8,
position=(x - 25, y + 5),
attach=attach,
transition=Image.Transition.IN_RIGHT,
transition_delay=delay,
transition_out_delay=None,
scale=(40, 40),
).autoretain()
)
else:
if not complete:
award_x = -100
objs.append(
Text(
babase.charstr(babase.SpecialChar.TICKET),
host_only=True,
position=(x + award_x + 33, y + 7),
transition=Text.Transition.IN_RIGHT,
scale=1.5,
h_attach=h_attach,
v_attach=v_attach,
h_align=Text.HAlign.CENTER,
v_align=Text.VAlign.CENTER,
color=(1, 1, 1, (0.1 if hmo else 0.2)),
transition_delay=delay + 0.05,
transition_out_delay=None,
).autoretain()
)
objs.append(
Text(
'+' + str(self.get_award_ticket_value()),
host_only=True,
position=(x + award_x + 28, y + 16),
transition=Text.Transition.IN_RIGHT,
scale=0.7,
flatness=1,
h_attach=h_attach,
v_attach=v_attach,
h_align=Text.HAlign.CENTER,
v_align=Text.VAlign.CENTER,
color=(0.6, 0.6, 0.6, (0.2 if hmo else 0.4)),
transition_delay=delay + 0.05,
transition_out_delay=None,
).autoretain()
)
# Show 'hard-mode-only' only over incomplete achievements
# when that's the case.
if hmo:
txtactor = Text(
babase.Lstr(resource='difficultyHardOnlyText'),
host_only=True,
maxwidth=300 * 0.7,
position=(x + 60, y + 5),
transition=Text.Transition.FADE_IN,
vr_depth=-5,
h_attach=h_attach,
v_attach=v_attach,
h_align=Text.HAlign.CENTER,
v_align=Text.VAlign.CENTER,
scale=0.85 * 0.8,
flatness=1.0,
shadow=0.5,
color=(1, 1, 0.6, 1),
transition_delay=delay + 0.05,
transition_out_delay=None,
).autoretain()
assert txtactor.node
txtactor.node.rotate = 10
objs.append(txtactor)
objs.append(
Text(
self.display_name,
host_only=True,
maxwidth=300,
position=(x, y + 2),
transition=Text.Transition.IN_RIGHT,
scale=0.85,
flatness=0.6,
h_attach=h_attach,
v_attach=v_attach,
color=(
(0.8, 0.93, 0.8, 1.0)
if complete
else (0.6, 0.6, 0.6, (0.2 if hmo else 0.4))
),
transition_delay=delay + 0.05,
transition_out_delay=None,
).autoretain()
)
objs.append(
Text(
self.description_complete if complete else self.description,
host_only=True,
maxwidth=400,
position=(x, y - 14),
transition=Text.Transition.IN_RIGHT,
vr_depth=-5,
h_attach=h_attach,
v_attach=v_attach,
scale=0.62,
flatness=1.0,
color=(
(0.6, 0.6, 0.6, 1.0)
if complete
else (0.6, 0.6, 0.6, (0.2 if hmo else 0.4))
),
transition_delay=delay + 0.1,
transition_out_delay=None,
).autoretain()
)
return objs
def _getconfig(self) -> dict[str, Any]:
"""
Return the sub-dict in settings where this achievement's
state is stored, creating it if need be.
"""
val: dict[str, Any] = babase.app.config.setdefault(
'Achievements', {}
).setdefault(self._name, {'Complete': False})
assert isinstance(val, dict)
return val
def _remove_banner_slot(self) -> None:
classic = babase.app.classic
assert classic is not None
assert self._completion_banner_slot is not None
classic.ach.achievement_completion_banner_slots.remove(
self._completion_banner_slot
)
self._completion_banner_slot = None
def show_completion_banner(self, sound: bool = True) -> None:
"""Create the banner/sound for an acquired achievement announcement."""
from bascenev1lib.actor.text import Text
from bascenev1lib.actor.image import Image
app = babase.app
assert app.classic is not None
app.classic.ach.last_achievement_display_time = babase.apptime()
# Just piggy-back onto any current activity
# (should we use the session instead?..)
activity = bascenev1.getactivity(doraise=False)
# If this gets called while this achievement is occupying a slot
# already, ignore it. (probably should never happen in real
# life but whatevs).
if self._completion_banner_slot is not None:
return
if activity is None:
print('show_completion_banner() called with no current activity!')
return
if sound:
bascenev1.getsound('achievement').play(host_only=True)
else:
bascenev1.timer(
0.5, lambda: bascenev1.getsound('ding').play(host_only=True)
)
in_time = 0.300
out_time = 3.5
base_vr_depth = 200
# Find the first free slot.
i = 0
while True:
if i not in app.classic.ach.achievement_completion_banner_slots:
app.classic.ach.achievement_completion_banner_slots.add(i)
self._completion_banner_slot = i
# Remove us from that slot when we close.
# Use an app-timer in an empty context so the removal
# runs even if our activity/session dies.
with babase.ContextRef.empty():
babase.apptimer(
in_time + out_time, self._remove_banner_slot
)
break
i += 1
assert self._completion_banner_slot is not None
y_offs = 110 * self._completion_banner_slot
objs: list[bascenev1.Actor] = []
obj = Image(
bascenev1.gettexture('shadow'),
position=(-30, 30 + y_offs),
front=True,
attach=Image.Attach.BOTTOM_CENTER,
transition=Image.Transition.IN_BOTTOM,
vr_depth=base_vr_depth - 100,
transition_delay=in_time,
transition_out_delay=out_time,
color=(0.0, 0.1, 0, 1),
scale=(1000, 300),
).autoretain()
objs.append(obj)
assert obj.node
obj.node.host_only = True
obj = Image(
bascenev1.gettexture('light'),
position=(-180, 60 + y_offs),
front=True,
attach=Image.Attach.BOTTOM_CENTER,
vr_depth=base_vr_depth,
transition=Image.Transition.IN_BOTTOM,
transition_delay=in_time,
transition_out_delay=out_time,
color=(1.8, 1.8, 1.0, 0.0),
scale=(40, 300),
).autoretain()
objs.append(obj)
assert obj.node
obj.node.host_only = True
obj.node.premultiplied = True
combine = bascenev1.newnode(
'combine', owner=obj.node, attrs={'size': 2}
)
bascenev1.animate(
combine,
'input0',
{
in_time: 0,
in_time + 0.4: 30,
in_time + 0.5: 40,
in_time + 0.6: 30,
in_time + 2.0: 0,
},
)
bascenev1.animate(
combine,
'input1',
{
in_time: 0,
in_time + 0.4: 200,
in_time + 0.5: 500,
in_time + 0.6: 200,
in_time + 2.0: 0,
},
)
combine.connectattr('output', obj.node, 'scale')
bascenev1.animate(obj.node, 'rotate', {0: 0.0, 0.35: 360.0}, loop=True)
obj = Image(
self.get_icon_texture(True),
position=(-180, 60 + y_offs),
attach=Image.Attach.BOTTOM_CENTER,
front=True,
vr_depth=base_vr_depth - 10,
transition=Image.Transition.IN_BOTTOM,
transition_delay=in_time,
transition_out_delay=out_time,
scale=(100, 100),
).autoretain()
objs.append(obj)
assert obj.node
obj.node.host_only = True
# Flash.
color = self.get_icon_color(True)
combine = bascenev1.newnode(
'combine', owner=obj.node, attrs={'size': 3}
)
keys = {
in_time: 1.0 * color[0],
in_time + 0.4: 1.5 * color[0],
in_time + 0.5: 6.0 * color[0],
in_time + 0.6: 1.5 * color[0],
in_time + 2.0: 1.0 * color[0],
}
bascenev1.animate(combine, 'input0', keys)
keys = {
in_time: 1.0 * color[1],
in_time + 0.4: 1.5 * color[1],
in_time + 0.5: 6.0 * color[1],
in_time + 0.6: 1.5 * color[1],
in_time + 2.0: 1.0 * color[1],
}
bascenev1.animate(combine, 'input1', keys)
keys = {
in_time: 1.0 * color[2],
in_time + 0.4: 1.5 * color[2],
in_time + 0.5: 6.0 * color[2],
in_time + 0.6: 1.5 * color[2],
in_time + 2.0: 1.0 * color[2],
}
bascenev1.animate(combine, 'input2', keys)
combine.connectattr('output', obj.node, 'color')
obj = Image(
bascenev1.gettexture('achievementOutline'),
mesh_transparent=bascenev1.getmesh('achievementOutline'),
position=(-180, 60 + y_offs),
front=True,
attach=Image.Attach.BOTTOM_CENTER,
vr_depth=base_vr_depth,
transition=Image.Transition.IN_BOTTOM,
transition_delay=in_time,
transition_out_delay=out_time,
scale=(100, 100),
).autoretain()
assert obj.node
obj.node.host_only = True
# Flash.
color = (2, 1.4, 0.4, 1)
combine = bascenev1.newnode(
'combine', owner=obj.node, attrs={'size': 3}
)
keys = {
in_time: 1.0 * color[0],
in_time + 0.4: 1.5 * color[0],
in_time + 0.5: 6.0 * color[0],
in_time + 0.6: 1.5 * color[0],
in_time + 2.0: 1.0 * color[0],
}
bascenev1.animate(combine, 'input0', keys)
keys = {
in_time: 1.0 * color[1],
in_time + 0.4: 1.5 * color[1],
in_time + 0.5: 6.0 * color[1],
in_time + 0.6: 1.5 * color[1],
in_time + 2.0: 1.0 * color[1],
}
bascenev1.animate(combine, 'input1', keys)
keys = {
in_time: 1.0 * color[2],
in_time + 0.4: 1.5 * color[2],
in_time + 0.5: 6.0 * color[2],
in_time + 0.6: 1.5 * color[2],
in_time + 2.0: 1.0 * color[2],
}
bascenev1.animate(combine, 'input2', keys)
combine.connectattr('output', obj.node, 'color')
objs.append(obj)
objt = Text(
babase.Lstr(
value='${A}:',
subs=[('${A}', babase.Lstr(resource='achievementText'))],
),
position=(-120, 91 + y_offs),
front=True,
v_attach=Text.VAttach.BOTTOM,
vr_depth=base_vr_depth - 10,
transition=Text.Transition.IN_BOTTOM,
flatness=0.5,
transition_delay=in_time,
transition_out_delay=out_time,
color=(1, 1, 1, 0.8),
scale=0.65,
).autoretain()
objs.append(objt)
assert objt.node
objt.node.host_only = True
objt = Text(
self.display_name,
position=(-120, 50 + y_offs),
front=True,
v_attach=Text.VAttach.BOTTOM,
transition=Text.Transition.IN_BOTTOM,
vr_depth=base_vr_depth,
flatness=0.5,
transition_delay=in_time,
transition_out_delay=out_time,
flash=True,
color=(1, 0.8, 0, 1.0),
scale=1.5,
).autoretain()
objs.append(objt)
assert objt.node
objt.node.host_only = True
objt = Text(
babase.charstr(babase.SpecialChar.TICKET),
position=(-120 - 170 + 5, 75 + y_offs - 20),
front=True,
v_attach=Text.VAttach.BOTTOM,
h_align=Text.HAlign.CENTER,
v_align=Text.VAlign.CENTER,
transition=Text.Transition.IN_BOTTOM,
vr_depth=base_vr_depth,
transition_delay=in_time,
transition_out_delay=out_time,
flash=True,
color=(0.5, 0.5, 0.5, 1),
scale=3.0,
).autoretain()
objs.append(objt)
assert objt.node
objt.node.host_only = True
objt = Text(
'+' + str(self.get_award_ticket_value()),
position=(-120 - 180 + 5, 80 + y_offs - 20),
v_attach=Text.VAttach.BOTTOM,
front=True,
h_align=Text.HAlign.CENTER,
v_align=Text.VAlign.CENTER,
transition=Text.Transition.IN_BOTTOM,
vr_depth=base_vr_depth,
flatness=0.5,
shadow=1.0,
transition_delay=in_time,
transition_out_delay=out_time,
flash=True,
color=(0, 1, 0, 1),
scale=1.5,
).autoretain()
objs.append(objt)
assert objt.node
objt.node.host_only = True
# Add the 'x 2' if we've got pro.
if app.classic.accounts.have_pro():
objt = Text(
'x 2',
position=(-120 - 180 + 45, 80 + y_offs - 50),
v_attach=Text.VAttach.BOTTOM,
front=True,
h_align=Text.HAlign.CENTER,
v_align=Text.VAlign.CENTER,
transition=Text.Transition.IN_BOTTOM,
vr_depth=base_vr_depth,
flatness=0.5,
shadow=1.0,
transition_delay=in_time,
transition_out_delay=out_time,
flash=True,
color=(0.4, 0, 1, 1),
scale=0.9,
).autoretain()
objs.append(objt)
assert objt.node
objt.node.host_only = True
objt = Text(
self.description_complete,
position=(-120, 30 + y_offs),
front=True,
v_attach=Text.VAttach.BOTTOM,
transition=Text.Transition.IN_BOTTOM,
vr_depth=base_vr_depth - 10,
flatness=0.5,
transition_delay=in_time,
transition_out_delay=out_time,
color=(1.0, 0.7, 0.5, 1.0),
scale=0.8,
).autoretain()
objs.append(objt)
assert objt.node
objt.node.host_only = True
for actor in objs:
bascenev1.timer(
out_time + 1.000,
babase.WeakCall(actor.handlemessage, bascenev1.DieMessage()),
)
| efroemling/ballistica | src/assets/ba_data/python/baclassic/_achievement.py | _achievement.py | py | 50,903 | python | en | code | 468 | github-code | 1 | [
{
"api_name": "typing.TYPE_CHECKING",
"line_number": 13,
"usage_type": "name"
},
{
"api_name": "baclassic.Achievement",
"line_number": 79,
"usage_type": "attribute"
},
{
"api_name": "bascenev1.BaseTimer",
"line_number": 81,
"usage_type": "attribute"
},
{
"api_name... |
28275954002 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import shutil
import tempfile
import numpy
from six.moves import urllib
import tensorflow as tf
# CVDF mirror of http://yann.lecun.com/exdb/mnist/
SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'
WORK_DIRECTORY = 'data'
IMAGE_SIZE = 28
NUM_CHANNELS = 1
PIXEL_DEPTH = 255
VALIDATION_SIZE = 5000
def maybe_download(filename):
"""Download the data from Yann's website, unless it's already here."""
if not tf.gfile.Exists(WORK_DIRECTORY):
tf.gfile.MakeDirs(WORK_DIRECTORY)
filepath = os.path.join(WORK_DIRECTORY, filename)
if not tf.gfile.Exists(filepath):
filepath, _ = urllib.request.urlretrieve(SOURCE_URL + filename, filepath)
with tf.gfile.GFile(filepath) as f:
size = f.size()
print('Successfully downloaded', filename, size, 'bytes.')
return filepath
def extract_data(filename, num_images):
"""Extract the images into a 4D tensor [image index, y, x, channels].
Values are rescaled from [0, 255] down to [-0.5, 0.5].
"""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
bytestream.read(16)
buf = bytestream.read(IMAGE_SIZE * IMAGE_SIZE * num_images * NUM_CHANNELS)
data = numpy.frombuffer(buf, dtype=numpy.uint8).astype(numpy.float32)
data = (data - (PIXEL_DEPTH / 2.0)) / PIXEL_DEPTH
data = data.reshape(num_images, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS)
return data
def extract_labels(filename, num_images):
"""Extract the labels into a vector of int64 label IDs."""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
bytestream.read(8)
buf = bytestream.read(1 * num_images)
labels = numpy.frombuffer(buf, dtype=numpy.uint8).astype(numpy.int64)
return labels
train_data_filename = maybe_download('train-images-idx3-ubyte.gz')
train_labels_filename = maybe_download('train-labels-idx1-ubyte.gz')
test_data_filename = maybe_download('t10k-images-idx3-ubyte.gz')
test_labels_filename = maybe_download('t10k-labels-idx1-ubyte.gz')
# Extract it into numpy arrays.
train_data = extract_data(train_data_filename, 60000)
train_labels = extract_labels(train_labels_filename, 60000)
test_data = extract_data(test_data_filename, 10000)
test_labels = extract_labels(test_labels_filename, 10000)
validation_data = train_data[:VALIDATION_SIZE, ...]
validation_labels = train_labels[:VALIDATION_SIZE]
train_data = train_data[VALIDATION_SIZE:, ...]
train_labels = train_labels[VALIDATION_SIZE:]
train_size = train_labels.shape[0]
image_size = train_data.shape[1:]
test_size = test_data.shape[0]
# Example of curried function: a function that returns an other function.
def feed_dict_gen(BATCH_SIZE, step, type='train'):
"""format data to feed to session"""
if (type=='train'):
data, labels, size = train_data, train_labels, train_size
else:
data, labels, size = test_data, test_labels, test_size
offset = (step * BATCH_SIZE) % (train_size - BATCH_SIZE)
batch_data = train_data[offset:(offset + BATCH_SIZE), ...]
batch_labels = train_labels[offset:(offset + BATCH_SIZE)]
return [batch_labels, batch_data]
| Pensarfeo/MNISTFullyConnectedTensorflowExample | dataset.py | dataset.py | py | 3,185 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "tensorflow.gfile.Exists",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "tensorflow.gfile",
"line_number": 24,
"usage_type": "attribute"
},
{
"api_name": "tensorflow.gfile.MakeDirs",
"line_number": 25,
"usage_type": "call"
},
{
"api_name"... |
20897754659 | from PyQt4 import QtCore, QtGui
import xml.etree.cElementTree as ET
from log_manager import logger
import csv
SYNC_CONFIG_FILE = "storj_sync_config.xml"
SYNC_DIRECTORIES_FILE = "storj_sync_dirs.csv"
# Configuration backend section
class SyncConfiguration():
def __init__(self, load_config=False):
if load_config:
et = None
try:
et = ET.parse(CONFIG_FILE)
except:
logger.error("Unspecified XML parse error")
for tags in et.iter(str("same_file_name_prompt")):
if tags.text == "1":
self.sameFileNamePrompt = True
elif tags.text == "0":
self.sameFileNamePrompt = False
else:
self.sameFileNamePrompt = True
for tags in et.iter(str("same_file_hash_prompt")):
if tags.text == "1":
self.sameFileHashPrompt = True
elif tags.text == "0":
self.sameFileHashPrompt = False
else:
self.sameFileHashPrompt = True
for tags in et.iter(str("max_chunk_size_for_download")):
if tags.text is not None:
self.maxDownloadChunkSize = int(tags.text)
else:
self.maxDownloadChunkSize = 1024
def get_config_parametr_value(self, parametr):
output = ""
try:
et = ET.parse(CONFIG_FILE)
for tags in et.iter(str(parametr)):
output = tags.text
except:
logger.error("Unspecified error")
return output
def load_config_from_xml(self):
try:
et = ET.parse(SYNC_CONFIG_FILE)
for tags in et.iter('password'):
output = tags.text
except:
logger.error("Unspecified error")
def paint_config_to_ui(self, settings_ui):
self.load_sync_directories(settings_ui.sync_directories_tableWidget)
et = None
try:
et = ET.parse(SYNC_CONFIG_FILE)
for tags in et.iter(str("max_shard_size")):
settings_ui.max_shard_size.setValue(int(tags.text))
for tags in et.iter(str("max_connections_onetime")):
settings_ui.connections_onetime.setValue(int(tags.text))
for tags in et.iter(str("bridge_request_timeout")):
settings_ui.bridge_request_timeout.setValue(int(tags.text))
for tags in et.iter(str("crypto_keys_location")):
settings_ui.crypto_keys_location.setText(str(tags.text))
for tags in et.iter(str("max_download_bandwidth")):
settings_ui.max_download_bandwidth.setText(str(tags.text))
for tags in et.iter(str("max_upload_bandwidth")):
settings_ui.max_upload_bandwidth.setText(str(tags.text))
for tags in et.iter(str("default_file_encryption_algorithm")):
settings_ui.default_crypto_algorithm.setCurrentIndex(int(tags.text))
for tags in et.iter(str("shard_size_unit")):
settings_ui.shard_size_unit.setCurrentIndex(int(tags.text))
for tags in et.iter(str("custom_max_shard_size_enabled")):
if int(tags.text) == 1:
settings_ui.max_shard_size_enabled_checkBox.setChecked(True)
else:
settings_ui.max_shard_size_enabled_checkBox.setChecked(False)
except Exception as e:
logger.error("Unspecified XML parse error" + str(e))
def save_sync_configuration(self, settings_ui):
self.save_sync_directories(settings_ui.sync_directories_tableWidget)
with open(SYNC_CONFIG_FILE, 'r') as conf_file:
XML_conf_data = conf_file.read().replace('\n', '')
tree = ET.parse(SYNC_CONFIG_FILE)
#root = ET.Element("configuration")
#doc = ET.SubElement(root, "client")
# settings_ui = Ui_
if settings_ui.sync_enabled_checkBox.isChecked():
sync_enabled_checkbox = '1'
else:
sync_enabled_checkbox = '0'
if settings_ui.start_sync_on_boot_checkBox.isChecked():
start_sync_on_boot_checkbox = '1'
else:
start_sync_on_boot_checkbox = '0'
if settings_ui.show_sync_tray_icon_checkBox.isChecked():
show_sync_tray_icon_checkbox = '1'
else:
show_sync_tray_icon_checkbox = '0'
tree.write(SYNC_CONFIG_FILE)
def load_sync_directories(self, sync_directories_table):
with open(unicode(SYNC_DIRECTORIES_FILE), 'rb') as stream:
sync_directories_table.setRowCount(0)
sync_directories_table.setColumnCount(0)
for rowdata in csv.reader(stream):
row = sync_directories_table.rowCount()
sync_directories_table.insertRow(row)
sync_directories_table.setColumnCount(len(rowdata))
for column, data in enumerate(rowdata):
item = QtGui.QTableWidgetItem(data.decode('utf8'))
sync_directories_table.setItem(row, column, item)
def save_sync_directories(self, sync_directories_table):
with open(unicode(SYNC_DIRECTORIES_FILE), 'wb') as stream:
writer = csv.writer(stream)
for row in range(sync_directories_table.rowCount()):
rowdata = []
for column in range(sync_directories_table.columnCount()):
item = sync_directories_table.item(row, column)
if item is not None:
rowdata.append(
unicode(item.text()).encode('utf8'))
else:
rowdata.append('')
writer.writerow(rowdata)
| lakewik/EasyStorj | UI/utilities/sync_config.py | sync_config.py | py | 5,871 | python | en | code | 74 | github-code | 1 | [
{
"api_name": "xml.etree.cElementTree.parse",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "xml.etree.cElementTree",
"line_number": 20,
"usage_type": "name"
},
{
"api_name": "log_manager.logger.error",
"line_number": 22,
"usage_type": "call"
},
{
"api_... |
10289153237 | from paprika.core.base_signal import Signal
from paprika.data.fetcher import DataType
from paprika.data.feed_subscriber import FeedSubscriber
from paprika.signals.signal_data import SignalData
from paprika.data.data_channel import DataChannel
from paprika.alpha.base import Alpha
from paprika.data.data_processor import DataProcessor
from paprika.data.feed_filter import TimeFreqFilter, TimePeriod
import datetime as dt
import numpy as np
import pandas as pd
import re
from typing import List, Tuple
import logging
class AlphaUnit(FeedSubscriber, Signal):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.alpha_unit = self.get_parameter("alpha")
self.positions = pd.DataFrame()
self.prices = pd.DataFrame()
self.probabilities = pd.DataFrame()
def handle_event(self, events: List[Tuple[DataType, pd.DataFrame]]):
super().handle_event(events)
if len(events) == 1:
event = events[0]
data = event[1]
date = pd.to_datetime(data.index.unique().values[-1])
data = data.reset_index().set_index([DataChannel.SYMBOL_INDEX, DataChannel.DATA_INDEX])
# data.reset_index().set_index([DataChannel.DATA_INDEX, DataChannel.SYMBOL_INDEX])
# symbols = data['Symbol'].unique().tolist()
# symbols = DataChannel.symbols_remove_data_type(symbols)
# dfs = DataChannel.fetch(symbols, end=date)
dp = DataProcessor(data)
# dp.ohlcv(time_filter, inplace=True)
alpha = Alpha(dp)
alpha.add_alpha(self.alpha_unit)
# # for alpha_unit in alpha.list_alpha():
res = alpha[self.alpha_unit.__name__]
if res.shape[0] > 0:
res = res.loc[date]
position = res.apply(lambda x: 1 if x > 0 else 0)
self.positions = self.positions.append(position)
self.prices = self.prices.append(dp.close.loc[date])
self.probabilities = self.probabilities.append(position.apply(lambda x: 1))
def signal_data(self):
self.positions.index.name = DataChannel.DATA_INDEX
self.probabilities.index.name = DataChannel.DATA_INDEX
self.prices.index.name = DataChannel.DATA_INDEX
return SignalData(self.__class__.__name__,
[("positions", SignalData.create_indexed_frame(
# self.positions[[self.y_name, self.x_name]].fillna(method='ffill'))),
self.positions.fillna(method='ffill'))),
("prices", SignalData.create_indexed_frame(self.prices)),
("probabilities", SignalData.create_indexed_frame(self.prices))])
| hraoyama/radish | paprika/signals/signals/alpha_unit.py | alpha_unit.py | py | 2,770 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "paprika.data.feed_subscriber.FeedSubscriber",
"line_number": 18,
"usage_type": "name"
},
{
"api_name": "paprika.core.base_signal.Signal",
"line_number": 18,
"usage_type": "name"
},
{
"api_name": "pandas.DataFrame",
"line_number": 24,
"usage_type": "call"
... |
44293486284 | import pygame
import os
pygame.font.init()
WIDTH, HEIGHT = 1100, 800
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Cowboy shooter")
class Draw_Controller:
def __init__(self, covers, P1, P2, Bullet_Controller):
self._DESERT = pygame.transform.scale(pygame.image.load(os.path.join('Assets', 'Desert.png')), (WIDTH, HEIGHT))
self._covers = covers
self._P1 = P1
self._P2 = P2
self._Bullet_Ctrl = Bullet_Controller
self._caput_m = (35, 15, 13)
self._winner_font = pygame.font.SysFont('comicsans', 100)
self._timer_font = pygame.font.SysFont('comicsans', 50)
def draw_winner(self, text):
winner_text = self._winner_font.render(text, 1, self._caput_m)
WIN.blit(winner_text, (WIDTH/2 - winner_text.get_width()/2, HEIGHT/2 - winner_text.get_height()/2))
pygame.display.update()
pygame.time.delay(5000)
def draw_time(self, timer):
timer_text = pygame.transform.rotate(self._timer_font.render("Time: " + str(int(timer / 1000)) + "/120" + "s", True, (255, 255, 255)), 270)
WIN.blit(timer_text, (1000, HEIGHT//2 - timer_text.get_height()//2))
def draw_window(self, timer):
WIN.blit(self._DESERT, (0, 0))
self._P1.draw_health(WIN, self._P1.get_health())
self._P2.draw_health(WIN, self._P2.get_health())
for cover in self._covers:
if cover.get_status():
cover.draw(WIN)
self.draw_time(timer)
self._P1.draw(WIN)
self._P2.draw(WIN)
self._Bullet_Ctrl.draw_bullets(WIN)
pygame.display.update()
| Ivailo2707/Pygame_Project_Cowboy | Draw_Controller.py | Draw_Controller.py | py | 1,641 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "pygame.font.init",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "pygame.font",
"line_number": 4,
"usage_type": "attribute"
},
{
"api_name": "pygame.display.set_mode",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "pygame.display... |
36780999631 | import numpy as np
from isoexp.linear.linearbandit import EfficientLinearBandit, LinearBandit, LinPHE
from isoexp.conservative.linearmabs import EfficientConservativeLinearBandit, SafetySetCLUCB
from isoexp.linear.linearmab_models import RandomLinearArms, DiffLinearArms, OtherArms, CircleBaseline, LinPHEModel
from matplotlib import rc
from joblib import Parallel, delayed
from isoexp.linear.coldstart import ColdStartFromDatasetModel
import os
rc('text', usetex=True)
import matplotlib.pyplot as plt
from tqdm import tqdm
from collections import namedtuple
MABResults = namedtuple('MABResults', 'regret,norm_error, cum_rewards')
random_state = np.random.randint(0, 123123)
NOISE = 0.1
#model = RandomLinearArms(n_actions=300, n_features=100, noise=NOISE, bound_features = 5, bound_theta = 3)
model = ColdStartFromDatasetModel(csvfile=os.path.abspath('jester/Vt_jester.csv'), noise=NOISE)
theta_bound = np.linalg.norm(model.theta, 2)
means = np.dot(model.features, model.theta)
print(means)
idxs = np.argsort(means)
#baseline = np.random.randint(0, model.n_actions - 1)
baseline = idxs[-5]
mean_baseline = means[baseline]
optimal_arm = np.argmax(means)
PARALLEL = False
n_a = model.n_actions
d = model.n_features
T = 20000
batch_horizon = int(T*0.2)
nb_simu = 10
alpha = 0.1
algorithms = {
'EfficientLinearBandit': EfficientLinearBandit(arm_features=model.features,
reg_factor=1.,
delta=0.01,
noise_variance=NOISE,
bound_theta=theta_bound)
}
conservative_algorithms = {
# 'CLUCB-new': EfficientConservativeLinearBandit(model.features, baseline, mean_baseline,
# bound_theta=theta_bound, noise_variance=NOISE,
# reg_factor=1., delta=0.01, conservative_level=alpha,
# version = 'new', oracle = False, means = means,
# batched = False, check_every = batch_horizon, positive = True),
# 'CLUCB-old': EfficientConservativeLinearBandit(model.features, baseline, mean_baseline,
# bound_theta=theta_bound, noise_variance=NOISE,
# reg_factor=1., delta=0.01, conservative_level=alpha,
# version = 'old', oracle = False, means = means,
# batched = False, check_every = batch_horizon, positive = True),
# 'SafetySet-Old' : SafetySetCLUCB(model.features, baseline, mean_baseline,
# bound_theta=theta_bound, noise_variance=NOISE,
# reg_factor=1., delta=0.01, conservative_level=alpha,
# version = 'old', batched = False, check_every = batch_horizon, positive = True, verbose = False),
# 'SafetySet-new' : SafetySetCLUCB(model.features, baseline, mean_baseline,
# bound_theta=theta_bound, noise_variance=NOISE,
# reg_factor=1., delta=0.01, conservative_level=alpha,
# version = 'new', oracle = False, batched = False, check_every = batch_horizon, means = means,
# verbose = False, positive = True)
}
algorithms = {**algorithms, **conservative_algorithms}
if PARALLEL:
import multiprocessing
num_cores = multiprocessing.cpu_count()
def work(alg_name, alg):
regret = np.zeros((nb_simu, T))
norms = np.zeros((nb_simu, T))
cond = regret.copy()
for k in tqdm(range(nb_simu)):
alg.reset()
for t in range(T):
a_t = alg.get_action()
# print(a_t)
r_t = model.reward(a_t)
alg.update(a_t, r_t)
cond[k, t] = means[a_t] - (1-alpha)*mean_baseline
regret[k, t] = model.best_arm_reward() - r_t
if hasattr(alg, 'theta_hat'):
norms[k, t] = np.linalg.norm(alg.theta_hat - model.theta, 2)
# results[alg_name] = \
return alg_name, MABResults(regret=regret, norm_error=norms, cum_rewards = cond)
results = Parallel(n_jobs=num_cores, verbose=1)(
delayed(work)(alg_name, algorithms[alg_name]) for alg_name in algorithms.keys())
else:
from tqdm import trange
results = []
for alg_name in algorithms.keys():
regret = np.zeros((nb_simu, T))
norms = np.zeros((nb_simu, T))
cond = np.zeros((nb_simu, T))
nb = 0
draws = 0*regret
for k in tqdm(range(nb_simu), desc='Simulating {}'.format(alg_name)):
alg = algorithms[alg_name]
alg.reset()
for t in trange(T):
a_t = alg.get_action()
r_t = model.reward(a_t)
cond[k, t] = means[a_t] - (1-alpha)*mean_baseline
alg.update(a_t, r_t)
draws[k,t] = a_t
if a_t == baseline:
nb += 1
regret[k, t] = model.best_arm_reward() - r_t
if hasattr(alg, 'theta_hat'):
norms[k, t] = np.linalg.norm(alg.theta_hat - model.theta, 2)
results += [(alg_name, MABResults(regret=regret, norm_error=norms, cum_rewards=cond.cumsum(axis = 1)))]
#%%
plt.figure(1, figsize=(10, 10))
plt.figure(2, figsize=(10, 10))
for alg_name, val in results :
temp = val.regret
temp = temp.cumsum(axis = 1)
mean_regret = np.mean(temp, axis=0)
mean_norms = np.mean(val.norm_error, axis=0)
low_quantile = np.quantile(temp, 0.000, axis=0)
high_quantile = np.quantile(temp, 1, axis=0)
condition_satisfied = np.mean(val.cum_rewards, axis=0)
low_quantile_condition = np.quantile(val.cum_rewards, 0.25, axis=0)
high_quantile_condition = np.quantile(val.cum_rewards, 0.75, axis=0)
t = np.linspace(0, T-1, T, dtype='int')
# plt.subplot(131)
# # plt.plot(mean_norms, label=alg_name)
# plt.plot(mean_regret.cumsum() / (np.arange(len(mean_regret)) + 1), label=alg_name)
# plt.fill_between(t, low_quantile.cumsum() / (np.arange(len(mean_regret)) + 1),
# high_quantile.cumsum() / (np.arange(len(mean_regret)) + 1), alpha=0.15)
plt.figure(1)
print('mean_regret')
print(alg_name, ' = ', mean_regret[-1])
plt.fill_between(t, low_quantile, high_quantile, alpha = 0.15)
plt.plot(mean_regret, label=alg_name)
plt.title('d = {}'.format(model.n_features))
plt.figure(2)
print(alg_name, '= ', min(condition_satisfied.cumsum()))
print('-'*100)
# plt.plot(condition_satisfied, label=alg_name)
plt.title('d = {}'.format(model.n_features))
# plt.fill_between(t, low_quantile_condition, high_quantile_condition, alpha = 0.15)
if alg_name != 'EfficientLinearBandit':
plt.plot(condition_satisfied.cumsum()[:200], label=alg_name)
plt.fill_between(t[:200], low_quantile_condition.cumsum()[:200], high_quantile_condition.cumsum()[:200], alpha = 0.15)
#ax = plt.subplot(131)
## plt.ylabel(r'$\|\hat{\theta} - \theta\|_{2}$')
#plt.ylabel(r'$R_t / t$')
#plt.xlabel("Rounds")
## # Turn off tick labels
## ax.set_yticklabels([])
## ax.set_xticklabels([])
#plt.legend()
#
#ax = plt.subplot(132)
#plt.ylabel("Cumulative Regret")
#plt.xlabel("Rounds")
## # Turn off tick labels
## ax.set_yticklabels([])
## ax.set_xticklabels([])
#plt.legend()
#
##ax = plt.subplot(223)
##plt.title('Model')
##plt.scatter(model.features[:, 0], model.features[:, 1])
##optimal_arm = np.argmax(means)
##plt.scatter([model.features[optimal_arm, 0]], [model.features[optimal_arm, 1]], color='red', label='Optimal arm')
##plt.scatter([model.features[baseline, 0]], [model.features[baseline, 1]], color='cyan', label='Baseline arm')
##plt.scatter([model.theta[0]], [model.theta[1]], color='yellow', label='Theta')
### # Turn off tick labels
### ax.set_yticklabels([])
### ax.set_xticklabels([])
##plt.legend()
#
#ax = plt.subplot(133)
#plt.ylabel("Margin")
#plt.xlabel("Rounds")
# # Turn off tick labels
# ax.set_yticklabels([])
# ax.set_xticklabels([])
plt.figure(1)
plt.legend()
#plt.savefig("model_random_{}_{}_seed_{}.png".format(alpha, model.n_actions, random_state))
plt.show()
| facebookresearch/ContextualBanditsAttacks | examples/main_linearmab.py | main_linearmab.py | py | 8,137 | python | en | code | 4 | github-code | 1 | [
{
"api_name": "matplotlib.rc",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "collections.namedtuple",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "numpy.random.randint",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "numpy.rando... |
22942092792 | import logging
import os
from typing import Dict
from monai.transforms import Invertd, SaveImaged
import monailabel
from monailabel.interfaces.app import MONAILabelApp
from monailabel.interfaces.tasks.infer_v2 import InferTask
from monailabel.interfaces.tasks.scoring import ScoringMethod
from monailabel.interfaces.tasks.strategy import Strategy
from monailabel.interfaces.tasks.train import TrainTask
from monailabel.tasks.activelearning.first import First
from monailabel.tasks.activelearning.random import Random
from monailabel.tasks.infer.bundle import BundleInferTask
from monailabel.tasks.scoring.epistemic_v2 import EpistemicScoring
from monailabel.tasks.train.bundle import BundleTrainTask
from monailabel.utils.others.generic import get_bundle_models, strtobool
logger = logging.getLogger(__name__)
class MyApp(MONAILabelApp):
def __init__(self, app_dir, studies, conf):
self.models = get_bundle_models(app_dir, conf)
# Add Epistemic model for scoring
self.epistemic_models = (
get_bundle_models(app_dir, conf, conf_key="epistemic_model") if conf.get("epistemic_model") else None
)
if self.epistemic_models:
# Get epistemic parameters
self.epistemic_max_samples = int(conf.get("epistemic_max_samples", "0"))
self.epistemic_simulation_size = int(conf.get("epistemic_simulation_size", "5"))
self.epistemic_dropout = float(conf.get("epistemic_dropout", "0.2"))
super().__init__(
app_dir=app_dir,
studies=studies,
conf=conf,
name=f"MONAILabel - Zoo/Bundle ({monailabel.__version__})",
description="DeepLearning models provided via MONAI Zoo/Bundle",
version=monailabel.__version__,
)
def init_infers(self) -> Dict[str, InferTask]:
infers: Dict[str, InferTask] = {}
#################################################
# Models
#################################################
for n, b in self.models.items():
if "deepedit" in n:
# Adding automatic inferer
i = BundleInferTask(b, self.conf, type="segmentation")
logger.info(f"+++ Adding Inferer:: {n}_seg => {i}")
infers[n + "_seg"] = i
# Adding inferer for managing clicks
i = BundleInferTask(b, self.conf, type="deepedit")
logger.info("+++ Adding DeepEdit Inferer")
infers[n] = i
else:
i = BundleInferTask(b, self.conf)
logger.info(f"+++ Adding Inferer:: {n} => {i}")
infers[n] = i
return infers
def init_trainers(self) -> Dict[str, TrainTask]:
trainers: Dict[str, TrainTask] = {}
if strtobool(self.conf.get("skip_trainers", "false")):
return trainers
for n, b in self.models.items():
t = BundleTrainTask(b, self.conf)
if not t or not t.is_valid():
continue
logger.info(f"+++ Adding Trainer:: {n} => {t}")
trainers[n] = t
return trainers
def init_strategies(self) -> Dict[str, Strategy]:
strategies: Dict[str, Strategy] = {
"random": Random(),
"first": First(),
}
logger.info(f"Active Learning Strategies:: {list(strategies.keys())}")
return strategies
def init_scoring_methods(self) -> Dict[str, ScoringMethod]:
methods: Dict[str, ScoringMethod] = {}
if not self.conf.get("epistemic_model"):
return methods
for n, b in self.epistemic_models.items():
# Create BundleInferTask task with dropout instantiation for scoring inference
i = BundleInferTask(
b,
self.conf,
train_mode=True,
skip_writer=True,
dropout=self.epistemic_dropout,
post_filter=[SaveImaged, Invertd],
)
methods[n] = EpistemicScoring(
i, max_samples=self.epistemic_max_samples, simulation_size=self.epistemic_simulation_size
)
if not methods:
continue
methods = methods if isinstance(methods, dict) else {n: methods[n]}
logger.info(f"+++ Adding Scoring Method:: {n} => {b}")
logger.info(f"Active Learning Scoring Methods:: {list(methods.keys())}")
return methods
"""
Example to run train/infer/scoring task(s) locally without actually running MONAI Label Server
"""
def main():
import argparse
import shutil
from pathlib import Path
from monailabel.utils.others.generic import device_list, file_ext
os.putenv("MASTER_ADDR", "127.0.0.1")
os.putenv("MASTER_PORT", "1234")
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] [%(process)s] [%(threadName)s] [%(levelname)s] (%(name)s:%(lineno)d) - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
force=True,
)
home = str(Path.home())
studies = f"{home}/Datasets/Radiology"
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--studies", default=studies)
parser.add_argument("-m", "--model", default="wholeBody_ct_segmentation")
parser.add_argument("-t", "--test", default="infer", choices=("train", "infer", "batch_infer"))
args = parser.parse_args()
app_dir = os.path.dirname(__file__)
studies = args.studies
conf = {
"models": args.model,
"preload": "false",
}
app = MyApp(app_dir, studies, conf)
# Infer
if args.test == "infer":
sample = app.next_sample(request={"strategy": "first"})
image_id = sample["id"]
image_path = sample["path"]
# Run on all devices
for device in device_list():
res = app.infer(request={"model": args.model, "image": image_id, "device": device})
label = res["file"]
label_json = res["params"]
test_dir = os.path.join(args.studies, "test_labels")
os.makedirs(test_dir, exist_ok=True)
label_file = os.path.join(test_dir, image_id + file_ext(image_path))
shutil.move(label, label_file)
print(label_json)
print(f"++++ Image File: {image_path}")
print(f"++++ Label File: {label_file}")
break
return
# Batch Infer
if args.test == "batch_infer":
app.batch_infer(
request={
"model": args.model,
"multi_gpu": False,
"save_label": True,
"label_tag": "original",
"max_workers": 1,
"max_batch_size": 0,
}
)
return
# Train
app.train(
request={
"model": args.model,
"max_epochs": 10,
"dataset": "Dataset", # PersistentDataset, CacheDataset
"train_batch_size": 1,
"val_batch_size": 1,
"multi_gpu": False,
"val_split": 0.1,
},
)
if __name__ == "__main__":
# export PYTHONPATH=~/Projects/MONAILabel:`pwd`
# python main.py
main()
| Project-MONAI/MONAILabel | sample-apps/monaibundle/main.py | main.py | py | 7,247 | python | en | code | 472 | github-code | 1 | [
{
"api_name": "logging.getLogger",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "monailabel.interfaces.app.MONAILabelApp",
"line_number": 23,
"usage_type": "name"
},
{
"api_name": "monailabel.utils.others.generic.get_bundle_models",
"line_number": 25,
"usage_t... |
42687602182 | import numpy as np
from collections import OrderedDict
import csv
import matplotlib.pyplot as plt
class Adam:
"""Adam (http://arxiv.org/abs/1412.6980v8)"""
def __init__(self, lr=0.001, beta1=0.9, beta2=0.999):
self.lr = lr
self.beta1 = beta1
self.beta2 = beta2
self.iter = 0
self.m = None
self.v = None
def update(self, params, grads):
if self.m is None:
self.m, self.v = {}, {}
for key, val in params.items():
self.m[key] = np.zeros_like(val)
self.v[key] = np.zeros_like(val)
self.iter += 1
lr_t = self.lr * np.sqrt(1.0 - self.beta2**self.iter) / (1.0 - self.beta1**self.iter)
for key in params.keys():
#self.m[key] = self.beta1*self.m[key] + (1-self.beta1)*grads[key]
#self.v[key] = self.beta2*self.v[key] + (1-self.beta2)*(grads[key]**2)
self.m[key] += (1 - self.beta1) * (grads[key] - self.m[key])
self.v[key] += (1 - self.beta2) * (grads[key]**2 - self.v[key])
params[key] -= lr_t * self.m[key] / (np.sqrt(self.v[key]) + 1e-7)
#unbias_m += (1 - self.beta1) * (grads[key] - self.m[key]) # correct bias
#unbisa_b += (1 - self.beta2) * (grads[key]*grads[key] - self.v[key]) # correct bias
#params[key] += self.lr * unbias_m / (np.sqrt(unbisa_b) + 1e-7)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
class Sigmoid:
def __init__(self):
self.out = None
def forward(self, x):
out = sigmoid(x)
self.out = out
return out
def backward(self, dout):
dx = dout * (1.0 - self.out) * self.out
return dx
class Affine:
def __init__(self, W, b):
self.W =W
self.b = b
self.x = None
self.original_x_shape = None
self.dW = None
self.db = None
def forward(self, x):
self.original_x_shape = x.shape
x = x.reshape(x.shape[0], -1)
self.x = x
out = np.dot(self.x, self.W) + self.b
return out
def backward(self, dout):
dx = np.dot(dout, self.W.T)
self.dW = np.dot(self.x.T, dout)
self.db = np.sum(dout, axis=0)
dx = dx.reshape(*self.original_x_shape)
return dx
def cross_entropy_error(y, t):
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size)
if t.size == y.size:
t = t.argmax(axis=1)
batch_size = y.shape[0]
return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size
def softmax(x):
if x.ndim == 2:
x = x.T
x = x - np.max(x, axis=0)
y = np.exp(x) / np.sum(np.exp(x), axis=0)
return y.T
x = x - np.max(x)
return np.exp(x) / np.sum(np.exp(x))
class SoftmaxWithLoss:
def __init__(self):
self.loss = None
self.y = None
self.t = None
def forward(self, x, t):
self.t = t
self.y = softmax(x)
self.loss = cross_entropy_error(self.y, self.t)
return self.loss
def backward(self, dout=1):
batch_size = self.t.shape[0]
if self.t.size == self.y.size:
dx = (self.y - self.t) / batch_size
else:
dx = self.y.copy()
dx[np.arange(batch_size), self.t] -= 1
dx = dx / batch_size
return dx
class TwoLayerNet:
def __init__(self, input_size, hidden_size, output_size, weight_init_std = 0.01):
self.params = {}
self.params['W1'] = weight_init_std * np.random.randn(input_size, output_size)
self.params['b1'] = np.zeros(output_size)
self.layers = OrderedDict()
self.layers['Affine1'] = Affine(self.params['W1'], self.params['b1'])
self.layers['Sigmoid'] = Sigmoid()
self.lastLayer = SoftmaxWithLoss()
def predict(self, x):
for layer in self.layers.values():
x = layer.forward(x)
return x
def loss(self, x, t):
y = self.predict(x)
return self.lastLayer.forward(y, t)
def accuracy(self, x, t):
y = self.predict(x)
y = np.argmax(y, axis=1)
if t.ndim != 1 : t = np.argmax(t, axis=1)
accuracy = np.sum(y == t) / float(x.shape[0])
return accuracy
def gradient(self, x, t):
# forward
self.loss(x, t)
# backward
dout = 1
dout = self.lastLayer.backward(dout)
layers = list(self.layers.values())
layers.reverse()
for layer in layers:
dout = layer.backward(dout)
grads = {}
grads['W1'], grads['b1'] = self.layers['Affine1'].dW, self.layers['Affine1'].db
return grads
ally = []
with open('train_y.csv', 'r') as f:
lines = f.readlines()
for line_i in range(1,len(lines)):
things = lines[line_i].replace('\n', "").split(',')
if float(things[0]) == 0:
tem = np.array([0,1])
ally.append(tem)
else:
tem = np.array([1,0])
ally.append(tem)
with open('train_x.csv', 'r') as f:
lines = f.readlines()
allx = []
alldata=[[]for i in range(30)]
for line_i in range(1,len(lines)):
row = []
things = lines[line_i].replace('\n', "").split(',')
for j in range(23):
row.append(float(things[j]))
for k in range(6):
row.append((float(things[11+k])-float(things[17+k]))/ float(things[0]))
row.append(float(1))
row = np.array(row)
allx.append(np.array(row))
for l in range(30):
alldata[l].append(row[l])
ms = []
ss = []
for l in range(30):
ms.append(np.mean(alldata[l]))
ss.append(np.std(alldata[l]))
for i in range(len(allx)):
for j in range(len(allx[i])-1):
allx[i][j] = (allx[i][j] - ms[j]) / ss[j]
np.save('mean',ms)
np.save('std',ss)
network = TwoLayerNet(input_size=30, hidden_size=2, output_size=2)
allx = np.array(allx)
ally = np.array(ally)
iters_num = 70000
train_size = allx.shape[0]
batch_size = 200
learning_rate = 0.1
iter_per_epoch = max(train_size / batch_size, 1)
train_loss_list = []
train_acc_list = []
optimizer = Adam()
for i in range(iters_num):
batch_mask = np.random.choice(train_size, batch_size)
x_batch = allx[batch_mask]
t_batch = ally[batch_mask]
grad = network.gradient(x_batch, t_batch)
for key in ('W1', 'b1'):
optimizer.update(network.params, grad)
loss = network.loss(x_batch, t_batch)
train_loss_list.append(loss)
if i % iter_per_epoch == 0:
train_acc = network.accuracy(allx, ally)
train_acc_list.append(train_acc)
plot_x = [z for z in range(len(train_loss_list))]
plt.plot(plot_x,train_loss_list)
np.save("w_"+str(loss),network.params['W1'])
np.save("b_"+str(loss),network.params['b1'])
# =============================================================================
# with open('test_x.csv', 'r') as f:
# lines = f.readlines()
#
# testx = []
#
# for line_i in range(1,len(lines)):
# row = []
# things = lines[line_i].replace('\n', "").split(',')
# for j in range(23):
# row.append(float(things[j]))
# for k in range(6):
# row.append((float(things[11+k])-float(things[17+k]))/ float(things[0]))
# row.append(float(1))
#
# row = np.array(row)
# row.reshape([30,])
#
# testx.append(np.array(row))
#
#
# for i in range(len(testx)):
# for j in range(len(testx[i])-1):
# testx[i][j] = (testx[i][j] - ms[j]) / ss[j]
#
# pr = []
# with open('ans'+str(loss)+'.csv', 'w', newline='') as csvfile:
# writer = csv.writer(csvfile)
# writer.writerow(['id', 'Value'])
#
# for l in range(10000):
# ids = 'id_'+ str(l)
# tem = testx[l]
# pre = network.predict(np.reshape(testx[l],(1,30)))
# pr.append(pre)
# if pre[0][0]>0.5:
# writer.writerow([ids, '1'])
# else:
# writer.writerow([ids, '0'])
# =============================================================================
| r07942086/ML2018FALL | hw2/train_best.py | train_best.py | py | 8,694 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "numpy.zeros_like",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "numpy.zeros_like",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "numpy.sqrt",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "numpy.sqrt",
"line_n... |
12458772738 | import os, sys
import pygame
import pygame.locals
import grid
import gem
import random
import player
import threading
import time
BLACK = 0, 0, 0
OFFSET = 70
pygame.init()
class Updater(threading.Thread):
'''Handles brick drop speed.'''
def __init__(self, players):
threading.Thread.__init__(self)
self.daemon = True
self.running = False
self.players = players
def run(self):
self.running = True
while self.running:
for playerx in self.players:
playerx.update()
time.sleep(1)
class AI (threading.Thread):
'''Handles brick drop speed.'''
def __init__(self, players, difficulty):
threading.Thread.__init__(self)
self.daemon = True
self.running = False
self.players = players
self.difficulty = difficulty
def run(self):
self.running = True
while self.running:
self.players[1].move()
time.sleep(self.difficulty)
class Main:
"""The Main class of the Puzzle Fighter game - this class handles
initialization and creation of the game"""
def __init__(self, width = 640, height = 600):
global OFFSET
self.size = width, height
self.screen = pygame.display.set_mode(self.size)
pygame.display.set_caption('PuzzleFighter!')
self.running = False
self.playing = True
topleft = (OFFSET, 0)
topmid = (width / 2 + OFFSET, 0)
self.players = [player.Player(topleft), player.AI(topmid)]
self.players[0].opponent = self.players[1]
self.players[1].opponent = self.players[0]
self.ai = None
self.difficulty = 1.75
self.updater = None
self.winner = None
self.loser = None
def handle_event(self, event):
'''Handle key events.'''
if event.type == pygame.QUIT:
sys.exit()
if self.playing:
if event.type == pygame.KEYDOWN: #All for player[0]
playerx = self.players[0]
if event.key == pygame.K_RIGHT:
playerx.rotate.rotate_clockwise()
elif event.key == pygame.K_LEFT:
playerx.rotate.rotate_anticlockwise()
if event.key == pygame.K_d:
playerx.rotate.move_right()
elif event.key == pygame.K_a:
playerx.rotate.move_left()
if event.key == pygame.K_DOWN:
playerx.rotate.drop()
else:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
for playerx in self.players:
playerx.restart()
self.updater = Updater(self.players)
self.updater.start()
if self.winner == self.players[0]:
self.difficulty *= 0.9
else:
self.difficulty *= 1.1
self.ai = AI(self.players, self.difficulty)
self.ai.start()
self.playing = True
def game_over(self):
'''Handles the game over event.'''
global BLACK
self.playing = False
self.ai.running = False
self.updater.running = False
def run(self):
"""Run the main loop of the game"""
global BLACK, OFFSET
self.updater = Updater(self.players)
self.updater.start()
self.ai = AI(self.players, self.difficulty)
self.ai.start()
self.running = True
while self.running:
for event in pygame.event.get():
self.handle_event(event)
self.screen.fill(BLACK)
for playerx in self.players:
playerx.draw(self.screen)
if self.playing:
for playerx in self.players:
if playerx.has_lost():
self.winner = playerx.opponent
self.loser = playerx
self.game_over()
else:
font = pygame.font.Font(None, gem.SIZE * 3)
rfont = pygame.font.Font(None, 24)
winner = font.render("WINNER", 1, (255, 255, 255))
loser = font.render("LOSER", 1, (255, 255, 255))
restart = rfont.render("Press 'r' to restart.", 1, (255, 255, 255))
grid_height = grid.HEIGHT * gem.SIZE
grid_width = grid.WIDTH * gem.SIZE
wx = self.winner.grid.topleft[0]
lx = self.loser.grid.topleft[0]
self.screen.blit (winner, (wx - 30, grid_height / 4))
self.screen.blit (loser, (lx - 10, grid_height / 4))
self.screen.blit (restart, (OFFSET, grid_height + gem.SIZE))
pygame.display.flip()
if __name__ == "__main__":
MainWindow = Main()
MainWindow.run()
| Ceasar/Puzzle-Fighter | main.py | main.py | py | 5,000 | python | en | code | 4 | github-code | 1 | [
{
"api_name": "pygame.init",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "threading.Thread",
"line_number": 17,
"usage_type": "attribute"
},
{
"api_name": "threading.Thread.__init__",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "threading... |
19152762512 | from django.test import TestCase
from django.core.urlresolvers import reverse
from committee.models import Committee, Meeting
class ResponseStatus(TestCase):
def test_committees(self):
response = self.client.get(reverse('committee-hub'))
self.assertEqual(response.status_code, 200)
def test_committee(self):
response = self.client.get('/committee/')
self.assertEqual(response.status_code, 200)
def test_committee_detail_resp(self):
committee = Committee(name="Committee Name",
main_contact="Main Contact", slug="commitee-name")
committee.save()
response = self.client.get(committee.get_absolute_url())
self.assertEqual(response.status_code, 200)
def test_meeting_detail_resp(self):
meeting = Meeting(notes="Blah blah blah \n Blah Blue")
meeting.save()
response = self.client.get(meeting.get_absolute_url())
self.assertEqual(response.status_code, 200)
| imagreenplant/beacon-food-forest | committee/tests.py | tests.py | py | 1,001 | python | en | code | 2 | github-code | 1 | [
{
"api_name": "django.test.TestCase",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "django.core.urlresolvers.reverse",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "committee.models",
"line_number": 17,
"usage_type": "name"
},
{
"api_name": "... |
13649108676 | import json
from rest_framework import status
from api.constans import AutoNotificationConstants, TaskStageConstants
from api.models import *
from api.tests import GigaTurnipTestHelper
class DateTimeSortTest(GigaTurnipTestHelper):
def test_datetime_sort_for_tasks(self):
from datetime import datetime
second_stage = self.initial_stage.add_stage(TaskStage(
assign_user_by="RA"
))
third_stage = second_stage.add_stage(TaskStage(
assign_user_by="RA"
))
verifier_rank = Rank.objects.create(name="verifier")
RankRecord.objects.create(
user=self.employee,
rank=verifier_rank)
RankLimit.objects.create(
rank=verifier_rank,
stage=second_stage,
open_limit=5,
total_limit=0,
is_creation_open=False,
is_listing_allowed=True,
is_selection_open=True,
is_submission_open=True
)
RankLimit.objects.create(
rank=verifier_rank,
stage=third_stage,
open_limit=5,
total_limit=0,
is_creation_open=False,
is_listing_allowed=True,
is_selection_open=True,
is_submission_open=True
)
time_limit = datetime(year=2020, month=1, day=1)
DatetimeSort.objects.create(
stage=second_stage,
start_time=time_limit
)
DatetimeSort.objects.create(
stage=third_stage,
end_time=time_limit
)
task1 = self.create_initial_task()
task1 = self.complete_task(task1)
task2 = task1.out_tasks.get()
response = self.get_objects('task-user-selectable', client=self.employee_client)
content = json.loads(response.content)
self.assertEqual(len(content['results']), 1)
self.assertEqual(content['results'][0]['id'], task2.id)
response_assign = self.get_objects('task-request-assignment', pk=task2.id, client=self.employee_client)
self.assertEqual(response_assign.status_code, status.HTTP_200_OK)
self.assertEqual(self.employee.tasks.count(), 1)
task2 = Task.objects.get(id=task2.id)
task2 = self.complete_task(task2, client=self.employee_client)
last_task = task2.out_tasks.get()
response = self.get_objects('task-user-selectable', client=self.employee_client)
content = json.loads(response.content)
self.assertEqual(len(content['results']), 0)
response_assign = self.get_objects('task-request-assignment', pk=last_task.id, client=self.employee_client)
self.assertEqual(response_assign.status_code, status.HTTP_200_OK)
last_task = Task.objects.get(id=last_task.id)
self.complete_task(last_task, client=self.employee_client)
def test_task_with_timer_is_exist(self):
second_stage = self.initial_stage.add_stage(TaskStage(
assign_user_by="RA"
))
verifier_rank = Rank.objects.create(name="verifier")
RankRecord.objects.create(
user=self.employee,
rank=verifier_rank)
RankLimit.objects.create(
rank=verifier_rank,
stage=second_stage,
open_limit=5,
total_limit=0,
is_creation_open=False,
is_listing_allowed=True,
is_selection_open=True,
is_submission_open=True
)
DatetimeSort.objects.create(
stage=second_stage,
how_much=2,
after_how_much=0.1
)
task1 = self.create_initial_task()
task1 = self.complete_task(task1)
task1.out_tasks.get()
response = self.get_objects('task-user-relevant')
content = json.loads(response.content)
self.assertEqual(len(content['results']), 1)
def test_number_rank_endpoint(self):
CampaignManagement.objects.create(user=self.employee,
campaign=self.campaign)
manager = CustomUser.objects.create_user(username="manager",
email='manager@email.com',
password='manager')
track = Track.objects.create(campaign=self.campaign)
rank1 = Rank.objects.create(name='rank1', track=track)
rank2 = Rank.objects.create(name='rank2', track=track)
rank2.prerequisite_ranks.add(rank1)
rank3 = Rank.objects.create(name='rank3', track=track)
track.default_rank = rank1
self.campaign.default_track = track
self.campaign.save(), track.save()
task_awards = TaskAward.objects.create(
task_stage_completion=self.initial_stage,
task_stage_verified=self.initial_stage,
rank=rank3,
count=1,
)
RankRecord.objects.create(user=self.employee,
rank=rank1)
RankRecord.objects.create(user=manager,
rank=rank1)
RankRecord.objects.create(user=self.employee,
rank=rank2)
RankRecord.objects.create(user=self.employee,
rank=rank3)
response = self.get_objects('numberrank-list', client=self.employee_client)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()[0]
my_ranks_list = [
{'name': 'rank1', 'condition': 'default', 'count': 2},
{'name': 'rank2', 'condition': 'prerequisite_ranks', 'count': 1},
{'name': 'rank3', 'condition': 'task_awards', 'count': 1},
]
received_ranks = []
for received_rank in data['ranks']:
d = {
'name': received_rank['name'],
'condition': received_rank['condition'],
'count': received_rank['count'],
}
received_ranks.append(d)
for my_rank in my_ranks_list:
self.assertIn(my_rank, received_ranks)
| KloopMedia/GigaTurnip | api/tests/test_datetime_sort.py | test_datetime_sort.py | py | 6,128 | python | en | code | 2 | github-code | 1 | [
{
"api_name": "api.tests.GigaTurnipTestHelper",
"line_number": 10,
"usage_type": "name"
},
{
"api_name": "datetime.datetime",
"line_number": 45,
"usage_type": "call"
},
{
"api_name": "json.loads",
"line_number": 60,
"usage_type": "call"
},
{
"api_name": "rest_fram... |
10327628407 | import numpy as np
import os
from PIL import Image
import cv2
import matplotlib.pyplot as plt
from tqdm import tqdm
import pandas as pd
from config import *
import dlib
def convert_csv_to_jpg(csv_path):
# 加载opencv的人脸识别文件
# 'haarcascade_frontalface_alt' higher accuracy, but slower
# 'haarcascade_frontalface_default' lower accuracy, but faster and lighter
# detector = cv2.CascadeClassifier(haarcascade_frontalface_alt)
detector = dlib.get_frontal_face_detector()
landmark_predictor = dlib.shape_predictor(shape_predictor_68_face_landmarks)
# 将csv转换为numpy数组,再通过PIL转换为jpg
data = pd.read_csv(csv_path, encoding="ISO-8859-1")
train_path_data = {'path': [], 'emotion': []}
valid_path_data = {'path': [], 'emotion': []}
test_path_data = {'path': [], 'emotion': []}
train_landmark = []
valid_landmark = []
test_landmark = []
if not os.path.exists(TRAIN_DIR):
os.mkdir(TRAIN_DIR)
if not os.path.exists(TEST_DIR):
os.mkdir(TEST_DIR)
if not os.path.exists(VALID_DIR):
os.mkdir(VALID_DIR)
total = 0
for label, pixels, usage in tqdm(zip(data['emotion'], data['pixels'], data['Usage'])):
img = np.asarray(pixels.split()).astype(np.int32).reshape([img_size, img_size])
all_faces, all_landmarks = crop_face_area(detector, landmark_predictor, img, img_size)
if all_faces is None:
continue
for img, landmarks in zip(all_faces, all_landmarks):
img = Image.fromarray(img).convert(mode='L')
fname = str(total) + '.jpg'
if usage == 'Training':
save_path = TRAIN_DIR + '/' + fname
train_path_data['path'].append(fname)
train_path_data['emotion'].append(label)
train_landmark.append(landmarks)
elif usage == 'PrivateTest':
save_path = VALID_DIR + '/' + fname
valid_path_data['path'].append(fname)
valid_path_data['emotion'].append(label)
valid_landmark.append(landmarks)
else:
save_path = TEST_DIR + '/' + fname
test_path_data['path'].append(fname)
test_path_data['emotion'].append(label)
test_landmark.append(landmarks)
img.save(save_path)
total += 1
train_landmark = np.asarray(train_landmark)
valid_landmark = np.asarray(valid_landmark)
test_landmark = np.asarray(test_landmark)
np.savez(TRAIN_LANDMARK_PATH, landmark=train_landmark)
np.savez(VALID_LANDMARK_PATH, landmark=valid_landmark)
np.savez(TEST_LANDMARK_PATH, landmark=test_landmark)
train_path_data = pd.DataFrame(train_path_data)
train_path_data.to_pickle(TRAIN_PATH)
valid_path_data = pd.DataFrame(valid_path_data)
valid_path_data.to_pickle(VALID_PATH)
test_path_data = pd.DataFrame(test_path_data)
test_path_data.to_pickle(TEST_PATH)
print('Total: {}, training: {}, valid: {}, test: {}'.format(
total, len(train_path_data), len(valid_path_data), len(test_path_data)))
def crop_face_area(detector, landmark_predictor, image, img_size):
"""
裁剪图像的人脸部分,并resize到img_size尺寸
:param detector:
:param image:
:param img_size:
:return: Two numpy arrays containing the area and landmarks of all faces.
None if no face was detected.
"""
# p_img = Image.fromarray(image).convert(mode='RGB')
# cv_img = cv2.cvtColor(np.asarray(p_img), cv2.COLOR_RGB2GRAY)
# faces = detector.detectMultiScale(
# image=cv_img,
# scaleFactor=1.1,
# minNeighbors=1,
# minSize=(30, 30),
# flags=0
# )
# if len(faces) != 0:
# x, y, w, h = faces[0]
# cv_img = cv2.resize(cv_img[x:x + w, y:y + h], (img_size, img_size))
# return np.asarray(cv_img)
# else:
# return None
p_img = Image.fromarray(image).convert(mode='RGB')
cv_img = cv2.cvtColor(np.asarray(p_img), cv2.COLOR_RGB2GRAY)
faces = detector(cv_img, 1)
all_landmarks = []
all_faces = []
if len(faces) > 0:
for face in faces:
shape = landmark_predictor(cv_img, face)
landmarks = np.ndarray(shape=[68, 2])
for i in range(68):
landmarks[i] = (shape.part(i).x, shape.part(i).y)
all_landmarks.append(landmarks)
x1, y1, x2, y2 = face.left(), face.top(), face.right(), face.bottom()
if x1 < 0:
x1 = 0
if x1 > cv_img.shape[1]:
x1 = cv_img.shape[1]
if x2 < 0:
x2 = 0
if x2 > cv_img.shape[1]:
x2 = cv_img.shape[1]
if y1 < 0:
y1 = 0
if y1 > cv_img.shape[0]:
y1 = cv_img.shape[0]
if y2 < 0:
y2 = 0
if y2 > cv_img.shape[0]:
y2 = cv_img.shape[0]
img = cv2.resize(cv_img[y1:y2, x1:x2], (img_size, img_size))
all_faces.append(img)
return np.asarray(all_faces), np.asarray(all_landmarks)
else:
return None, None
def count_lines(csv_path):
data = pd.read_csv(csv_path, encoding="ISO-8859-1")
return data.shape[0]
def show_class_distribution(file_path):
label_num = np.zeros([7], dtype=np.int32)
data = pd.read_csv(file_path)
for label in data['emotion']:
label_num[label] += 1
rects = plt.bar(class_names, label_num)
plt.title('Label Distribution')
plt.xlabel("Label")
plt.ylabel("Number")
for rect in rects:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() / 2, height + 1, str(height), ha="center", va="bottom")
plt.show()
if __name__ == '__main__':
convert_csv_to_jpg(DATA_PATH)
| ryangawei/CNN-Facial-Expression-Recognition | src/preprocess.py | preprocess.py | py | 5,897 | python | en | code | 16 | github-code | 1 | [
{
"api_name": "dlib.get_frontal_face_detector",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "dlib.shape_predictor",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "pandas.read_csv",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "o... |
18652820535 | from django.conf.urls import url
from django.urls import path
from .views import CustomerGroupAPIView, CustomerGroupAPIDetailView, SiteAPIDetailView, SiteAPIView
app_name = "api-group"
# app_name will help us do a reverse look-up latter.
urlpatterns = [
url(r'^(?P<id>\d+)/$', CustomerGroupAPIDetailView.as_view(), name='detail'),
url(r'^sites/(?P<group>\d+)/$', SiteAPIDetailView.as_view(), name='fcity'),
path('sites/', SiteAPIView.as_view(), name='city-list'),
path('', CustomerGroupAPIView.as_view(), name='list')
] | KUSH23/bkend | customergroups/api/urls.py | urls.py | py | 539 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "django.conf.urls.url",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "views.CustomerGroupAPIDetailView.as_view",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "views.CustomerGroupAPIDetailView",
"line_number": 11,
"usage_type": "name"
... |
71114520353 | from plot import *
from bokeh.plotting import output_file, show
from bokeh.models import Div
# example values
layout = column(
Div(text="<h1>Cruise control (PI regulator)</h1>", align="center"),
make_plot(start_velocity=0, end_velocity=50),
make_plots(start_velocity=0, end_velocity=50)
)
output_file("cruise_control.html", title="Cruise control")
show(layout)
| gg-mike/PUT-3-PA-project | Main.py | Main.py | py | 376 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "bokeh.models.Div",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "bokeh.plotting.output_file",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "bokeh.plotting.show",
"line_number": 14,
"usage_type": "call"
}
] |
4157922495 | from django.urls import path
from .views import (
SignupAPIView,
SigninAPIView,
DeleteUserView,
ProjectMixins,
ProjectDetailMixins
)
urlpatterns = [
path("users/signup/", SignupAPIView.as_view(), name='signup'),
path("users/signin/", SigninAPIView.as_view(), name='signin'),
path("users/<int:pk>/", DeleteUserView.as_view(), name='user-delete'),
path("projects/", ProjectMixins.as_view(), name='project-c'),
path('projects/<int:pk>/', ProjectDetailMixins.as_view(), name='project-rud'),
] | HyeonWooJo/tts-input-service | backend/apis/urls.py | urls.py | py | 531 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "django.urls.path",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "views.SignupAPIView.as_view",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "views.SignupAPIView",
"line_number": 13,
"usage_type": "name"
},
{
"api_name": "djan... |
38302460948 | """Tests for `ember_mug.mug connections`."""
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING
from unittest.mock import AsyncMock, Mock, patch
import pytest
from bleak import BleakError
from bleak.backends.device import BLEDevice
from ember_mug.consts import (
EMBER_MUG,
EXTRA_ATTRS,
INITIAL_ATTRS,
UPDATE_ATTRS,
MugCharacteristic,
TemperatureUnit,
VolumeLevel,
)
from ember_mug.data import Colour, Model
from ember_mug.mug import EmberMug
if TYPE_CHECKING:
class MockMug(EmberMug):
_client: AsyncMock
@patch("ember_mug.mug.IS_LINUX", True)
async def test_adapter_with_bluez(ble_device: BLEDevice):
mug = EmberMug(ble_device, adapter="hci0")
assert mug._client_kwargs["adapter"] == "hci0"
@patch("ember_mug.mug.IS_LINUX", False)
async def test_adapter_without_bluez(ble_device: BLEDevice):
with pytest.raises(ValueError):
EmberMug(ble_device, adapter="hci0")
@patch("ember_mug.mug.EmberMug.subscribe")
@patch("ember_mug.mug.establish_connection")
async def test_connect(
mug_subscribe: Mock,
mock_establish_connection: Mock,
ember_mug: MockMug,
) -> None:
# Already connected
ember_mug._client = AsyncMock()
ember_mug._client.is_connected = True
async with ember_mug.connection():
pass
mug_subscribe.assert_not_called()
mock_establish_connection.assert_not_called()
# Not connected
mock_disconnect = AsyncMock()
with patch.multiple(ember_mug, _client=None, disconnect=mock_disconnect):
async with ember_mug.connection():
pass
mock_establish_connection.assert_called()
mug_subscribe.assert_called()
assert ember_mug._client is not None
mock_disconnect.assert_called()
@patch("ember_mug.mug.logger")
@patch("ember_mug.mug.establish_connection")
async def test_connect_error(
mock_establish_connection: Mock,
mock_logger: Mock,
ember_mug: MockMug,
) -> None:
ember_mug._client = None # type: ignore[assignment]
mock_establish_connection.side_effect = BleakError
with pytest.raises(BleakError):
await ember_mug._ensure_connection()
msg, device, exception = mock_logger.debug.mock_calls[1].args
assert msg == "%s: Failed to connect to the mug: %s"
assert device == ember_mug.device
assert isinstance(exception, BleakError)
@patch("ember_mug.mug.logger")
@patch("ember_mug.mug.establish_connection")
async def test_pairing_exceptions_esphome(
mock_establish_connection: Mock,
mock_logger: Mock,
ember_mug: MockMug,
) -> None:
ember_mug._client.is_connected = False
mock_client = AsyncMock()
mock_client.connect.side_effect = BleakError
mock_client.pair.side_effect = NotImplementedError
mock_establish_connection.return_value = mock_client
with patch.multiple(
ember_mug,
update_initial=AsyncMock(),
subscribe=AsyncMock(),
):
await ember_mug._ensure_connection()
mock_establish_connection.assert_called_once()
mock_logger.warning.assert_called_with(
"Pairing not implemented. "
"If your mug is still in pairing mode (blinking blue) tap the button on the bottom to exit.",
)
@patch("ember_mug.mug.establish_connection")
async def test_pairing_exceptions(
mock_establish_connection: Mock,
ember_mug: MockMug,
) -> None:
mock_client = AsyncMock()
mock_client.pair.side_effect = BleakError
mock_establish_connection.return_value = mock_client
with patch.multiple(
ember_mug,
update_initial=AsyncMock(),
subscribe=AsyncMock(),
):
await ember_mug._ensure_connection()
async def test_disconnect(ember_mug: MockMug) -> None:
mock_client = AsyncMock()
ember_mug._client = mock_client
mock_client.is_connected = False
await ember_mug.disconnect()
assert ember_mug._client is None
mock_client.disconnect.assert_not_called()
mock_client.is_connected = True
ember_mug._client = mock_client
await ember_mug.disconnect()
assert ember_mug._client is None
mock_client.disconnect.assert_called()
@patch("ember_mug.mug.logger")
def test_disconnect_callback(mock_logger: Mock, ember_mug: MockMug) -> None:
ember_mug._expected_disconnect = True
ember_mug._disconnect_callback(AsyncMock())
mock_logger.debug.assert_called_with("Disconnect callback called")
mock_logger.reset_mock()
ember_mug._expected_disconnect = False
ember_mug._disconnect_callback(AsyncMock())
mock_logger.debug.assert_called_with("Unexpectedly disconnected")
@patch("ember_mug.mug.logger")
async def test_read(
mock_logger: Mock,
ember_mug: MockMug,
) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"TEST"
await ember_mug._read(MugCharacteristic.MUG_NAME)
ember_mug._client.read_gatt_char.assert_called_with(
MugCharacteristic.MUG_NAME.uuid,
)
mock_logger.debug.assert_called_with(
"Read attribute '%s' with value '%s'",
MugCharacteristic.MUG_NAME,
b"TEST",
)
@patch("ember_mug.mug.logger")
async def test_write(mock_logger: Mock, ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
test_name = bytearray(b"TEST")
await ember_mug._write(
MugCharacteristic.MUG_NAME,
test_name,
)
ember_mug._client.write_gatt_char.assert_called_with(
MugCharacteristic.MUG_NAME.uuid,
test_name,
)
mock_logger.debug.assert_called_with(
"Wrote '%s' to attribute '%s'",
test_name,
MugCharacteristic.MUG_NAME,
)
ember_mug._client = AsyncMock()
ember_mug._client.write_gatt_char.side_effect = BleakError
with pytest.raises(BleakError):
await ember_mug._write(
MugCharacteristic.MUG_NAME,
test_name,
)
ember_mug._client.write_gatt_char.assert_called_with(
MugCharacteristic.MUG_NAME.uuid,
test_name,
)
msg, data, char, exception = mock_logger.error.mock_calls[0].args
assert msg == "Failed to write '%s' to attribute '%s': %s"
assert data == test_name
assert char == MugCharacteristic.MUG_NAME
assert isinstance(exception, BleakError)
def test_set_device(ember_mug: MockMug) -> None:
new_device = BLEDevice(
address="BA:36:a5:be:88:cb",
name="Ember Ceramic Mug",
details={},
rssi=1,
)
assert ember_mug.device.address != new_device.address
ember_mug.set_device(new_device)
assert ember_mug.device.address == new_device.address
async def test_get_mug_meta(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"Yw====-ABCDEFGHIJ"
meta = await ember_mug.get_meta()
assert meta.mug_id == "WXc9PT09"
assert meta.serial_number == "ABCDEFGHIJ"
ember_mug._client.read_gatt_char.assert_called_once_with(MugCharacteristic.MUG_ID.uuid)
async def test_get_mug_battery(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"5\x01"
battery = await ember_mug.get_battery()
assert battery.percent == 53.00
assert battery.on_charging_base is True
ember_mug._client.read_gatt_char.assert_called_once_with(MugCharacteristic.BATTERY.uuid)
async def test_get_mug_led_colour(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"\xf4\x00\xa1\xff"
colour = await ember_mug.get_led_colour()
assert colour.as_hex() == "#f400a1"
ember_mug._client.read_gatt_char.assert_called_once_with(MugCharacteristic.LED.uuid)
async def test_set_mug_led_colour(ember_mug: MockMug) -> None:
mock_ensure_connection = AsyncMock()
with patch.object(ember_mug, "_ensure_connection", mock_ensure_connection):
await ember_mug.set_led_colour(Colour(244, 0, 161))
mock_ensure_connection.assert_called_once()
ember_mug._client.write_gatt_char.assert_called_once_with(
MugCharacteristic.LED.uuid,
bytearray(b"\xf4\x00\xa1\xff"),
)
async def test_set_volume_level_travel_mug(ember_mug: MockMug) -> None:
ember_mug.is_travel_mug = True
mock_ensure_connection = AsyncMock()
with patch.object(ember_mug, "_ensure_connection", mock_ensure_connection):
await ember_mug.set_volume_level(VolumeLevel.HIGH)
mock_ensure_connection.assert_called_once()
ember_mug._client.write_gatt_char.assert_called_once_with(
MugCharacteristic.VOLUME.uuid,
bytearray(b"\02"),
)
mock_ensure_connection.reset_mock()
ember_mug._client.write_gatt_char.reset_mock()
await ember_mug.set_volume_level(0)
mock_ensure_connection.assert_called_once()
ember_mug._client.write_gatt_char.assert_called_once_with(
MugCharacteristic.VOLUME.uuid,
bytearray(b"\00"),
)
async def test_set_volume_level_mug(ember_mug: MockMug) -> None:
mock_ensure_connection = AsyncMock()
with patch.object(ember_mug, "_ensure_connection", mock_ensure_connection):
with pytest.raises(NotImplementedError):
await ember_mug.set_volume_level(VolumeLevel.HIGH)
mock_ensure_connection.assert_not_called()
ember_mug._client.write_gatt_char.assert_not_called()
async def test_get_mug_target_temp(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"\xcd\x15"
assert (await ember_mug.get_target_temp()) == 55.81
ember_mug._client.read_gatt_char.assert_called_once_with(MugCharacteristic.TARGET_TEMPERATURE.uuid)
async def test_set_mug_target_temp(ember_mug: MockMug) -> None:
mock_ensure_connection = AsyncMock()
with patch.object(ember_mug, "_ensure_connection", mock_ensure_connection):
await ember_mug.set_target_temp(55.81)
mock_ensure_connection.assert_called_once()
ember_mug._client.write_gatt_char.assert_called_once_with(
MugCharacteristic.TARGET_TEMPERATURE.uuid,
bytearray(b"\xcd\x15"),
)
async def test_get_mug_current_temp(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"\xcd\x15"
assert (await ember_mug.get_current_temp()) == 55.81
ember_mug._client.read_gatt_char.assert_called_once_with(MugCharacteristic.CURRENT_TEMPERATURE.uuid)
async def test_get_mug_liquid_level(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"\n"
assert (await ember_mug.get_liquid_level()) == 10
ember_mug._client.read_gatt_char.assert_called_once_with(MugCharacteristic.LIQUID_LEVEL.uuid)
async def test_get_mug_liquid_state(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"\x06"
assert (await ember_mug.get_liquid_state()) == 6
ember_mug._client.read_gatt_char.assert_called_once_with(MugCharacteristic.LIQUID_STATE.uuid)
async def test_get_mug_name(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"Mug Name"
assert (await ember_mug.get_name()) == "Mug Name"
ember_mug._client.read_gatt_char.assert_called_once_with(MugCharacteristic.MUG_NAME.uuid)
async def test_set_mug_name(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()), pytest.raises(ValueError):
await ember_mug.set_name("Hé!")
mock_ensure_connection = AsyncMock()
with patch.object(ember_mug, "_ensure_connection", mock_ensure_connection):
await ember_mug.set_name("Mug name")
mock_ensure_connection.assert_called()
ember_mug._client.write_gatt_char.assert_called_once_with(
MugCharacteristic.MUG_NAME.uuid,
bytearray(b"Mug name"),
)
async def test_get_mug_udsk(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"abcd12345"
assert (await ember_mug.get_udsk()) == "YWJjZDEyMzQ1"
ember_mug._client.read_gatt_char.assert_called_once_with(MugCharacteristic.UDSK.uuid)
async def test_set_mug_udsk(ember_mug: MockMug) -> None:
mock_ensure_connection = AsyncMock()
with patch.object(ember_mug, "_ensure_connection", mock_ensure_connection):
await ember_mug.set_udsk("abcd12345")
mock_ensure_connection.assert_called_once()
ember_mug._client.write_gatt_char.assert_called_once_with(
MugCharacteristic.UDSK.uuid,
bytearray(b"YWJjZDEyMzQ1"),
)
async def test_get_mug_dsk(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"abcd12345"
assert (await ember_mug.get_dsk()) == "YWJjZDEyMzQ1"
ember_mug._client.read_gatt_char.return_value = b"something else"
assert (await ember_mug.get_dsk()) == "c29tZXRoaW5nIGVsc2U="
ember_mug._client.read_gatt_char.assert_called_with(MugCharacteristic.DSK.uuid)
async def test_get_mug_temperature_unit(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"\x01"
assert (await ember_mug.get_temperature_unit()) == TemperatureUnit.FAHRENHEIT
ember_mug._client.read_gatt_char.assert_called_once_with(MugCharacteristic.TEMPERATURE_UNIT.uuid)
ember_mug._client.read_gatt_char.reset_mock()
ember_mug._client.read_gatt_char.return_value = b"\x00"
assert (await ember_mug.get_temperature_unit()) == TemperatureUnit.CELSIUS
ember_mug._client.read_gatt_char.assert_called_once_with(MugCharacteristic.TEMPERATURE_UNIT.uuid)
async def test_set_mug_temperature_unit(ember_mug: MockMug) -> None:
mock_ensure_connection = AsyncMock()
with patch.object(ember_mug, "_ensure_connection", mock_ensure_connection):
await ember_mug.set_temperature_unit(TemperatureUnit.CELSIUS)
mock_ensure_connection.assert_called_once()
ember_mug._client.write_gatt_char.assert_called_once_with(
MugCharacteristic.TEMPERATURE_UNIT.uuid,
bytearray(b"\x00"),
)
async def test_mug_ensure_correct_unit(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug.data.temperature_unit = TemperatureUnit.CELSIUS
ember_mug.data.use_metric = True
mock_set_temp = AsyncMock(return_value=None)
with patch.object(ember_mug, 'set_temperature_unit', mock_set_temp):
await ember_mug.ensure_correct_unit()
mock_set_temp.assert_not_called()
ember_mug.data.temperature_unit = TemperatureUnit.FAHRENHEIT
await ember_mug.ensure_correct_unit()
mock_set_temp.assert_called_with(TemperatureUnit.CELSIUS)
async def test_get_mug_battery_voltage(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"\x01"
assert (await ember_mug.get_battery_voltage()) == 1
ember_mug._client.read_gatt_char.assert_called_once_with(MugCharacteristic.CONTROL_REGISTER_DATA.uuid)
async def test_get_mug_date_time_zone(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"c\x0f\xf6\x00"
date_time = await ember_mug.get_date_time_zone()
assert isinstance(date_time, datetime)
assert date_time.timestamp() == 1661990400.0
ember_mug._client.read_gatt_char.assert_called_once_with(MugCharacteristic.DATE_TIME_AND_ZONE.uuid)
async def test_read_firmware(ember_mug: MockMug) -> None:
with patch.object(ember_mug, "_ensure_connection", AsyncMock()):
ember_mug._client.read_gatt_char.return_value = b"c\x01\x80\x00\x12\x00"
firmware = await ember_mug.get_firmware()
assert firmware.version == 355
assert firmware.hardware == 128
assert firmware.bootloader == 18
ember_mug._client.read_gatt_char.assert_called_once_with(MugCharacteristic.FIRMWARE.uuid)
async def test_mug_update_initial(ember_mug: MockMug) -> None:
no_extra = INITIAL_ATTRS - EXTRA_ATTRS
mock_update = AsyncMock(return_value={})
with patch.multiple(ember_mug, _ensure_connection=AsyncMock(), _update_multiple=mock_update):
ember_mug.data.model = Model(EMBER_MUG, include_extra=False)
assert (await ember_mug.update_initial()) == {}
mock_update.assert_called_once_with(no_extra)
# Try with extra
mock_update.reset_mock()
ember_mug.data.model = Model(EMBER_MUG, include_extra=True)
assert (await ember_mug.update_initial()) == {}
mock_update.assert_called_once_with(INITIAL_ATTRS)
async def test_mug_update_all(ember_mug: MockMug) -> None:
mock_update = AsyncMock(return_value={})
with patch.multiple(ember_mug, _ensure_connection=AsyncMock(), _update_multiple=mock_update):
assert (await ember_mug.update_all()) == {}
mock_update.assert_called_once_with(UPDATE_ATTRS - EXTRA_ATTRS)
# Try with extras
mock_update.reset_mock()
assert (await ember_mug.update_all()) == {}
mock_update.assert_called_once_with(UPDATE_ATTRS)
async def test_mug_update_multiple(ember_mug: MockMug) -> None:
mock_get_name = AsyncMock(return_value="name")
mock_update_info = AsyncMock()
with patch.multiple(ember_mug, _ensure_connection=AsyncMock(), get_name=mock_get_name):
with patch.object(ember_mug.data, 'update_info', mock_update_info):
await ember_mug._update_multiple({"name"})
mock_get_name.assert_called_once()
mock_update_info.assert_called_once_with(name="name")
async def test_mug_update_queued_attributes(ember_mug: MockMug) -> None:
mock_get_name = AsyncMock(return_value="name")
mock_update_info = AsyncMock()
with patch.multiple(ember_mug, _ensure_connection=AsyncMock(), get_name=mock_get_name):
ember_mug._queued_updates = set()
assert (await ember_mug.update_queued_attributes()) == []
with patch.object(ember_mug.data, 'update_info', mock_update_info):
ember_mug._queued_updates = {"name"}
await ember_mug.update_queued_attributes()
mock_update_info.assert_called_once_with(name="name")
def test_mug_notify_callback(ember_mug: MockMug) -> None:
gatt_char = AsyncMock()
ember_mug._notify_callback(gatt_char, bytearray(b"\x01"))
ember_mug._notify_callback(gatt_char, bytearray(b"\x02"))
assert 2 in ember_mug._latest_events
ember_mug._notify_callback(gatt_char, bytearray(b"\x04"))
assert 4 in ember_mug._latest_events
ember_mug._notify_callback(gatt_char, bytearray(b"\x05"))
assert 5 in ember_mug._latest_events
ember_mug._notify_callback(gatt_char, bytearray(b"\x06"))
assert 6 in ember_mug._latest_events
ember_mug._notify_callback(gatt_char, bytearray(b"\x07"))
assert 7 in ember_mug._latest_events
ember_mug._notify_callback(gatt_char, bytearray(b"\x08"))
assert 8 in ember_mug._latest_events
callback = Mock()
second_callback = Mock()
unregister = ember_mug.register_callback(callback)
second_unregister = ember_mug.register_callback(second_callback)
repeat_unregister = ember_mug.register_callback(callback)
assert unregister is repeat_unregister
assert unregister is not second_unregister
assert callback in ember_mug._callbacks
ember_mug._notify_callback(gatt_char, bytearray(b"\x09"))
assert 9 in ember_mug._latest_events
callback.assert_not_called()
assert ember_mug._queued_updates == {
"battery",
"target_temp",
"current_temp",
"liquid_level",
"liquid_state",
"battery_voltage",
}
ember_mug._latest_events = {}
ember_mug._notify_callback(gatt_char, bytearray(b"\x02"))
callback.assert_called_once()
callback.reset_mock()
ember_mug._notify_callback(gatt_char, bytearray(b"\x02"))
callback.assert_not_called()
# Remove callback
unregister()
assert callback not in ember_mug._callbacks
| sopelj/python-ember-mug | tests/test_connection.py | test_connection.py | py | 21,188 | python | en | code | 18 | github-code | 1 | [
{
"api_name": "typing.TYPE_CHECKING",
"line_number": 24,
"usage_type": "name"
},
{
"api_name": "ember_mug.mug.EmberMug",
"line_number": 26,
"usage_type": "name"
},
{
"api_name": "unittest.mock.AsyncMock",
"line_number": 27,
"usage_type": "name"
},
{
"api_name": "b... |
21484583538 | import math
import numpy as np
import scipy.constants as sc
import units as unit
def db_to_abs(db_value):
"""
:param db_value: list or float
:return: Convert dB to absolute value
"""
absolute_value = 10**(db_value/float(10))
return absolute_value
def abs_to_db(absolute_value):
"""
:param absolute_value: list or float
:return: Convert absolute value to dB
"""
db_value = 10*np.log10(absolute_value)
return db_value
class TransmissionSystem(object):
def __init__(self):
# active_channels =
# {link_id:
# {span_id: [
# {channel_id: power_level},
# {channel_id: noise_levels},
# {channel_id: amplifier_attenuation}]
# }
# }
self.input_power = {}
self.output_power = {}
self.amplified_spontaneous_emission_noise = {}
self.nonlinear_interference_noise = {}
def init_interfaces(self, links):
for link in links:
self.input_power[link] = {}
self.output_power[link] = {}
self.amplified_spontaneous_emission_noise[link] = {}
self.nonlinear_interference_noise[link] = {}
spans = link.spans
for span, _amplifier in spans:
self.input_power[link][span] = {}
self.output_power[link][span] = {}
self.amplified_spontaneous_emission_noise[link][span] = {}
self.nonlinear_interference_noise[link][span] = {}
def propagate(self, path, signals):
"""
:param path: list of Span tuples (span, amplifier)
:param signals: list of signals in transmission - list[Signal(),]
:return: Run transmission system, returning True on success
"""
input_power = {}
output_power = {}
signal_power_nonlinear = {}
amplified_spontaneous_emission_noise = {}
nonlinear_interference_noise = {}
wdg = {}
for signal in signals:
signal_index = signal.index
input_power[signal_index] = db_to_abs(signal.launch_power)
output_power[signal_index] = db_to_abs(signal.launch_power)
nonlinear_interference_noise[signal_index] = db_to_abs(0.0)
# get last node in path (Rx)
rx_node = path[-1][0]
# Calculate the current signal behaviour across the
# path elements (nodes and links)
for node, link in path:
# If we are at the Rx node, then we are done with this path
if node == rx_node:
break
else:
# Calculate impairments of the node and its compensation
node_attenuation = db_to_abs(node.attenuation())
node_amplifier = node.amplifier
previous_amplifier = node_amplifier
for signal in signals:
signal_index = signal.index
signal_frequency = signal.frequency
signal_launch_power = signal.launch_power # MAYBE TO BE REMOVED
signal_power = output_power[signal_index]
# Needed for computation of nonlinear interference noise
signal_power_nonlinear[signal_index] = output_power[signal_index]
signal_power = signal_power / node_attenuation
if node_amplifier:
amplifier_target_gain = node_amplifier.target_gain
amplifier_noise_figure = node_amplifier.noise_figure
amplifier_mode = node_amplifier.mode
amplifier_bandwidth = node_amplifier.bandwidth
amplifier_wavelength_dependent_gain = node_amplifier.wavelength_dependent_gain[signal_index]
signal_noise = self.stage_amplified_spontaneous_emission_noise(
signal_frequency, amplifier_target_gain, amplifier_wavelength_dependent_gain,
amplifier_noise_figure, amplifier_bandwidth)
amplified_spontaneous_emission_noise[signal_index] = signal_noise
# Output signal power levels after amplification
signal_power = self.output_amplified_power(
signal_power, amplifier_target_gain, amplifier_mode,
signal_launch_power, amplifier_wavelength_dependent_gain)
# Signal performance after node
# Output power levels after amplification
output_power[signal_index] = signal_power
# Links are composed of fibre spans and amplifiers.
# Iterate through the link elements and compute the
# impairments raised by each
for span, amplifier in link.spans:
# Retrieve linear degradation effects due to the optical fiber
fibre_attenuation = db_to_abs(span.fibre_attenuation * span.length)
for signal in signals:
# Compute linear effects
signal_index = signal.index
signal_power = output_power[signal_index]
signal_power = signal_power / fibre_attenuation
# dispersion requires revision
# dispersion = self.dispersion(signal, span)
# signal_power = signal_power / dispersion
# Signal performance at the end of span
# considering linear effects
input_power[signal_index] = signal_power
if amplifier:
wdg[signal_index] = amplifier.wavelength_dependent_gain[signal_index]
# Check if active channels is not single channel, or
# if the loop is not at the last EDFA.
if len(input_power) > 1:
# Compute nonlinear effects
# compute SRS impairment
input_power = self.zirngibl_srs(signals,
input_power,
span)
if amplifier:
# Store not normalized power and noise levels
# to be considered in the power excursion calculation
not_normalized_power = input_power
not_normalized_noise = amplified_spontaneous_emission_noise
normalized_power, normalized_noise = self.normalize_channel_levels(
input_power,
amplified_spontaneous_emission_noise,
wdg)
# Consider power excursion and propagation per-span
input_power = self.power_excursion_propagation(
normalized_power, normalized_noise,
not_normalized_power, not_normalized_noise)
if len(input_power) > 2:
# Compute nonlinear interference noise, passing the node_amplifier
# because its amplification gain impacts negatively the nonlinear
# interference.
if amplifier:
nonlinear_interference_noise = self.output_nonlinear_noise(
signals,
nonlinear_interference_noise,
signal_power_nonlinear,
span,
node_amplifier)
self.nonlinear_interference_noise[link][span] = nonlinear_interference_noise
for signal in signals:
# Compute linear effects
signal_index = signal.index
signal_frequency = signal.frequency
signal_launch_power = signal.launch_power
signal_power = input_power[signal_index]
self.input_power[link][span][signal_index] = signal_power * unit.mW
if amplifier:
amplifier_target_gain = amplifier.target_gain
amplifier_previous_gain = previous_amplifier.target_gain
amplifier_noise_figure = amplifier.noise_figure
amplifier_mode = amplifier.mode
amplifier_bandwidth = node_amplifier.bandwidth
amplifier_wavelength_dependent_gain = amplifier.wavelength_dependent_gain[signal_index]
amplifier_previous_wavelength_dependent_gain = \
previous_amplifier.wavelength_dependent_gain[signal_index]
signal_noise = self.stage_amplified_spontaneous_emission_noise(
signal_frequency, amplifier_previous_gain, amplifier_previous_wavelength_dependent_gain,
amplifier_noise_figure, amplifier_bandwidth)
self.amplified_spontaneous_emission_noise[link][span][signal_index] = signal_noise
# Output signal power levels after amplification
signal_power = self.output_amplified_power(
signal_power, amplifier_target_gain, amplifier_mode,
signal_launch_power, amplifier_wavelength_dependent_gain)
previous_amplifier = amplifier
# Output power levels after amplification
self.output_power[link][span][signal_index] = signal_power
@staticmethod
def dispersion(signal, span):
symbol_rate = signal.symbol_rate
bits_per_symbol = signal.bits_per_symbol
gross_bit_rate = symbol_rate * np.log2(bits_per_symbol)
bandwidth_nm = unit.c / signal.bandwidth
dispersion = -(2 * unit.pi * unit.c/signal.wavelength**2) * span.dispersion_coefficient
dispersion_penalty = 5 * np.log10(1 + (4 * bandwidth_nm*unit.nm * gross_bit_rate * span.length * dispersion)**2)
dispersion_penalty_abs = db_to_abs(dispersion_penalty)
return dispersion_penalty_abs
@staticmethod
def output_amplified_power(signal_power, target_gain, mode, launch_power, amplifier_wavelength_dependent_gain):
"""
:param signal_power: units: mW - float
:param target_gain: units mW (absolute value) - float
:param mode: amplifier mode - string
:param launch_power: units: mW, only used if mode=AGC - float
:param amplifier_wavelength_dependent_gain: units: mW - float
:param amplifier_wavelength_dependent_gain: units: mW - float
:return: amplification-compensated power levels - float
"""
if mode == 'AGC':
# Adjust the gain to keep signal power constant
target_gain = db_to_abs(abs(abs_to_db(signal_power)-launch_power))
# Conversion from dB to linear
target_gain_linear = db_to_abs(target_gain)
wavelength_dependent_gain_linear = db_to_abs(amplifier_wavelength_dependent_gain)
return signal_power * target_gain_linear * wavelength_dependent_gain_linear
@staticmethod
def stage_amplified_spontaneous_emission_noise(signal_frequency, amplifier_target_gain,
amplifier_wavelength_dependent_gain,
amplifier_noise_figure, amplifier_bandwidth):
"""
:param signal_frequency: units: THz
:param amplifier_target_gain: units: dB
:param amplifier_wavelength_dependent_gain: units: dB
:param amplifier_noise_figure: units: dB
:param amplifier_bandwidth: units: GHz
:return: ASE noise in linear form
Ch.5 Eqs. 4-16,18 in: Gumaste A, Antony T. DWDM network designs and engineering solutions. Cisco Press; 2003.
"""
# Compute parameters needed for ASE model
population_inversion = 0.5 * 10**(amplifier_noise_figure/10.0)
amplifier_gain = amplifier_target_gain - 1
# Conversion from dB to linear
gain_linear = db_to_abs(amplifier_gain)
wavelength_dependent_gain_linear = db_to_abs(amplifier_wavelength_dependent_gain)
# Calculation of the amplified spontaneous emission (ASE) noise.
# Simpler formula
# ase_noise = db_to_abs(amplifier_noise_figure) * sc.h * signal_frequency * amplifier_bandwidth
ase_noise = 2 * population_inversion * (gain_linear * wavelength_dependent_gain_linear) * \
sc.h * signal_frequency * amplifier_bandwidth
return ase_noise
def output_nonlinear_noise(self, signals, nonlinear_interference_noise,
signal_power_nonlinear, span, node_amplifier):
"""
:param signals: signals interacting at given transmission - list[Signal() object]
:param nonlinear_interference_noise: accumulated NLI noise - dict{signal_index: NLI noise levels}
:param signal_power_nonlinear: power levels at beginning of span - dict{signal_index: power levels}
:param span: Span() object
:param node_amplifier: Amplifier() object at beginning of span
:return: dict{signal_index: accumulated NLI noise levels}
"""
node_amplifier_gain = db_to_abs(node_amplifier.target_gain)
nonlinear_noise = self.nonlinear_noise(signals, signal_power_nonlinear, span, node_amplifier_gain)
out_noise = {}
for signal_index, value in nonlinear_noise.items():
out_noise[signal_index] = nonlinear_interference_noise[signal_index] + nonlinear_noise[signal_index]
return out_noise
@staticmethod
def nonlinear_noise(signals, signal_power, span, lump_gain):
"""
Computation taken from: Poggiolini, P., et al. "Accurate Non-Linearity Fully-Closed-Form Formula
based on the GN/EGN Model and Large-Data-Set Fitting." Optical Fiber Communication Conference.
Optical Society of America, 2019. Equations 1-4
:param signals: signals interacting at given transmission - list[Signal() object]
:param signal_power: power levels at beginning of span - dict{signal_index: power levels}
:param span: Span() object
:param lump_gain: EDFA target gain + wavelength dependent gain - float
:return: Nonlinear Interference noise - dictionary{signal_index: NLI}
"""
nonlinear_noise_struct = {}
channels_index = sorted(signal_power.keys())
for channel_index in channels_index:
nonlinear_noise_struct[channel_index] = None
channel_center = channels_index[int(math.floor(len(signal_power.keys()) / 2))]
for signal in signals:
if signal.index == channel_center:
frequency_center = signal.frequency
break
# Retrieve fiber properties from span
b2 = span.dispersion_coefficient
b3 = span.dispersion_slope
alpha = span.loss_coefficient
gamma = span.non_linear_coefficient
span_length = span.length
for signal in signals:
channel_under_test = signal.index
frequency_cut = signal.frequency
symbol_rate_cut = signal.symbol_rate
bits_per_symbol_cut = signal.bits_per_symbol
gross_bit_rate_cut = symbol_rate_cut * np.log2(bits_per_symbol_cut)
bw_cut = gross_bit_rate_cut / (2 * np.log2(4)) # full bandwidth of the nth channel (THz).
pwr_cut = signal_power[signal.index]
g_cut = pwr_cut / bw_cut # G is the flat PSD per channel power (per polarization)
nonlinear_noise_term2 = 0
for ch in signals:
# omit channel under test
if ch == channel_under_test:
continue
frequency_ch = ch.frequency
symbol_rate_ch = signal.symbol_rate
bits_per_symbol_ch = signal.bits_per_symbol
gross_bit_rate_ch = symbol_rate_ch * np.log2(bits_per_symbol_ch)
bw_ch = gross_bit_rate_ch / (2 * np.log2(4)) # full bandwidth of the nth channel (THz).
pwr_ch = signal_power[ch.index]
g_ch = pwr_ch / bw_ch # G is the flat PSD per channel power (per polarization)
b2_eff_nch = b2 + unit.pi * b3 * (
frequency_ch + frequency_cut - 2 * frequency_center) # FWM-factor - [1], Eq. (5)
b2_eff_ncut = b2 + unit.pi * b3 * (
2 * frequency_cut - 2 * frequency_center) # FWM-factor - [1], Eq. (6)
nch_dividend1 = math.asinh(
(unit.pi ** 2 / 2) * abs(b2_eff_nch / alpha) *
(frequency_ch - frequency_cut + (bw_ch / 2)) * bw_cut)
nch_divisor1 = 8 * unit.pi * abs(b2_eff_nch) * alpha
nch_dividend2 = math.asinh(
(unit.pi ** 2 / 2) * abs(b2_eff_nch / alpha) *
(frequency_ch - frequency_cut - (bw_ch / 2)) * bw_cut)
nch_divisor2 = 8 * unit.pi * abs(b2_eff_nch) * alpha
_nch = (nch_dividend1 / float(nch_divisor1)) - (
nch_dividend2 / float(nch_divisor2)) # [1], Eq. (3)
cut_dividend = math.asinh((unit.pi ** 2 / 2) * abs(b2_eff_ncut / (2 * alpha)) * bw_cut ** 2)
cut_divisor = 4 * unit.pi * abs(b2_eff_ncut) * alpha
_cut = cut_dividend / float(cut_divisor) # [1], Eq. (4)
nonlinear_noise_term2 += (2 * g_ch ** 2 * _nch + g_cut ** 2 * _cut)
nonlinear_noise_term1 = 16 / 27.0 * gamma ** 2 * lump_gain * math.e ** (-2 * alpha * span_length) * g_cut
nonlinear_noise = nonlinear_noise_term1 * nonlinear_noise_term2
nonlinear_noise_struct[channel_under_test] = nonlinear_noise
return nonlinear_noise_struct
@staticmethod
def zirngibl_srs(signals, active_channels, span):
"""
Computation taken from : M. Zirngibl Analytical model of Raman gain effects in massive
wavelength division multiplexed transmission systems, 1998. - Equations 7,8.
:param signals: signals interacting at given transmission - list[Signal() object]
:param active_channels: power levels at the end of span - dict{signal_index: power levels}
:param span: Span() object
:return:
"""
min_wavelength_index = 90
max_wavelength_index = 0
min_signal = None
max_signal = None
for signal in signals:
if signal.index < min_wavelength_index:
min_signal = signal
min_wavelength_index = signal.index
if signal.index > max_wavelength_index:
max_signal = signal
max_wavelength_index = signal.index
frequency_min = min_signal.frequency # minimum frequency of longest wavelength
frequency_max = max_signal.frequency # maximum frequency of shortest wavelength
effective_length = span.effective_length # SMF effective distance
beta = span.raman_coefficient
total_power = 0 # Total input power calculated by following loop
for channel, power_per_channel in active_channels.items():
total_power += power_per_channel*unit.mW
# Calculate delta P for each channel
for signal in signals:
signal_index = signal.index
frequency = signal.frequency
r1 = beta * total_power * effective_length * (frequency_max - frequency_min) * math.e ** (
beta * total_power * effective_length * (frequency_max - frequency)) # term 1
r2 = math.e ** (beta * total_power * effective_length * (frequency_max - frequency_min)) - 1 # term 2
delta_p = float(r1/r2) # Does the arithmetic in mW
active_channels[signal_index] *= delta_p
return active_channels
@staticmethod
def normalize_channel_levels(power_levels, noise_levels, wavelength_dependent_gains):
"""
:param power_levels: units: mW - list[float,]
:param noise_levels: units: linear - list[float,]
:param wavelength_dependent_gains: units: dB list[float,]
:return: dictionary of normalized power and noise - dict{signal_index: power/noise}
"""
# Sum amplifier attenuation for each channel
# Calculate the main system gain of the loaded channels
# (i.e. mean wavelength gain)
loaded_gains_db = wavelength_dependent_gains.values()
total_system_gain_db = sum(loaded_gains_db)
channel_count = len(wavelength_dependent_gains)
mean_system_gain_db = total_system_gain_db/float(channel_count)
mean_system_gain_abs = db_to_abs(mean_system_gain_db)
# Affect the power and noise with the mean of wavelength gain
normalized_power = {k: abs(x/mean_system_gain_abs) for k, x in power_levels.items()}
normalized_noise = {k: abs(x/mean_system_gain_abs) for k, x in noise_levels.items()}
return normalized_power, normalized_noise
@staticmethod
def power_excursion_propagation(normalized_power, normalized_noise,
not_normalized_power, not_normalized_noise):
"""
:param normalized_power: dict{signal_index: power - float}
:param normalized_noise: dict{signal_index: noise - float}
:param not_normalized_power: dict{signal_index: power - float}
:param not_normalized_noise: dict{signal_index: noise - float}
:return: dictionary with the power excursion propagated in the signal power levels
"""
# Calculate total power values given by the form: P*N
total_power = {}
for k in normalized_power.keys():
power = normalized_power[k]
noise = normalized_noise[k]
total_power[k] = abs(power * noise + power)
total_power_old = {}
for k in normalized_power.keys():
power = not_normalized_power[k]
noise = not_normalized_noise[k]
total_power_old[k] = abs(power * noise + power)
# Calculate excursion
excursion = max(p/op for p, op in zip(total_power.values(), total_power_old.values()))
# Propagate power excursion
power_excursion_prop = {k: p*excursion for k, p in total_power.items()} # new
# update current power levels with the excursion propagation
return power_excursion_prop
| adiazmont/optical-network-simulator | transmission_system.py | transmission_system.py | py | 23,048 | python | en | code | 4 | github-code | 1 | [
{
"api_name": "numpy.log10",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "units.mW",
"line_number": 188,
"usage_type": "attribute"
},
{
"api_name": "numpy.log2",
"line_number": 219,
"usage_type": "call"
},
{
"api_name": "units.c",
"line_number": 2... |
37614366922 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
plt.style.use('fivethirtyeight')
def fit_model(x_train, y_train):
# Fits a linear regression to find the actual b and w that minimize the loss
regression = LinearRegression()
regression.fit(x_train, y_train)
b_minimum, w_minimum = regression.intercept_[0], regression.coef_[0][0]
return b_minimum, w_minimum
def figure1(x_train, y_train, x_val, y_val):
fig, ax = plt.subplots(1, 2, figsize=(12, 6))
ax[0].scatter(x_train, y_train)
ax[0].set_xlabel('x')
ax[0].set_ylabel('y')
ax[0].set_ylim([0, 3.1])
ax[0].set_title('Generated Data - Train')
ax[1].scatter(x_val, y_val, c='r')
ax[1].set_xlabel('x')
ax[1].set_ylabel('y')
ax[1].set_ylim([0, 3.1])
ax[1].set_title('Generated Data - Validation')
fig.tight_layout()
return fig, ax
def figure3(x_train, y_train):
b_minimum, w_minimum = fit_model(x_train, y_train)
# Generates evenly spaced x feature
x_range = np.linspace(0, 1, 101)
# Computes yhat
yhat_range = b_minimum + w_minimum * x_range
fig, ax = plt.subplots(1, 1, figsize=(6, 6))
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_ylim([0, 3.1])
# Dataset
ax.scatter(x_train, y_train)
# Predictions
ax.plot(x_range, yhat_range, label='Final model\'s predictions', c='k', linestyle='--')
# Annotations
ax.annotate('b = {:.4f} w = {:.4f}'.format(b_minimum, w_minimum), xy=(.4, 1.5), c='k', rotation=34)
ax.legend(loc=0)
fig.tight_layout()
return fig, ax
| dvgodoy/PyTorchStepByStep | plots/chapter1.py | chapter1.py | py | 1,612 | python | en | code | 622 | github-code | 1 | [
{
"api_name": "matplotlib.pyplot.style.use",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot.style",
"line_number": 4,
"usage_type": "attribute"
},
{
"api_name": "matplotlib.pyplot",
"line_number": 4,
"usage_type": "name"
},
{
"api_name"... |
26191591366 | import numpy as np
import matplotlib.pyplot as plt
import torch
from torchvision.io import read_image
from torchvision.ops import masks_to_boxes
def show_mask(mask, ax, random_color=False):
if random_color:
color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
else:
color = np.array([30/255, 144/255, 255/255, 0.6])
h, w = mask.shape[-2:]
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
ax.imshow(mask_image)
def show_points(coords, labels, ax, marker_size=375):
pos_points = coords[labels==1]
neg_points = coords[labels==0]
ax.scatter(pos_points[:, 0], pos_points[:, 1], color='green', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)
ax.scatter(neg_points[:, 0], neg_points[:, 1], color='red', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)
def show_box(box, ax):
x0, y0 = box[0], box[1]
w, h = box[2] - box[0], box[3] - box[1]
ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2))
def prepare_image(image, transform, device):
image = transform.apply_image(image)
image = torch.as_tensor(image, device=device.device)
return image.permute(2, 0, 1).contiguous()
def get_torch_prompts_labels(xycoo, prompt_size, device):
n = min(len(xycoo), prompt_size)
xy_coo_array = [[xycoo[i]["x"],xycoo[i]["y"]] for i in range(n)]
xy_coo_array = [xy_coo_array]
xy_label_array = [[1 for _ in range(n)]]
xy_coo_array = torch.tensor(xy_coo_array, device = device)
xy_label_array = torch.tensor(xy_label_array, device = device)
return xy_coo_array, xy_label_array
def get_boxes(mask_path, device):
mask = read_image(mask_path)
boxes = masks_to_boxes(mask)
boxes.to(device)
return boxes
| anushkumarv/AITestKitchen | SAM/utils/helper.py | helper.py | py | 1,807 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "numpy.concatenate",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "numpy.random.random",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "numpy.random",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "numpy.array",... |
38420624656 | import configparser
import csv
from src.web_monitor import web_monitor
def read_config():
config = configparser.ConfigParser()
config.read('config.ini')
with open("websites.txt", "r") as web_config:
tsv_reader = csv.DictReader(web_config, delimiter='\t')
web_dict = {}
for row in tsv_reader:
web_dict[row['website']] = row['content_file']
config['url_content'] = web_dict
return config
def main():
config = read_config()
web_monitor.main(config)
if __name__ == '__main__':
main()
| Cy83rr/web_monitor | run_script.py | run_script.py | py | 556 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "configparser.ConfigParser",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "csv.DictReader",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "src.web_monitor.web_monitor.main",
"line_number": 22,
"usage_type": "call"
},
{
"api_name... |
72794581795 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from rknn.api import RKNN
#import _init_paths
import cv2
import numpy as np
import math
import threading
from time import sleep
imreadLock = threading.Lock()
#from python_wrapper import *
#import os
import sys
PNET_PYRAMID= np.array([[270,207],[192,147],[136,104],[97,74],[69,53],[49,37],[35,27],[25,19],[18,14]])
ODD_PYRAMID = np.array([[270,207],[136,104],[69,53],[35,27],[18,14]])
ODD_SCALES = np.array([0.6,0.302,0.153,0.0778,0.04])
EVEN_PYRAMID = np.array([[192,147],[97,74],[49,37],[25,19]])
EVEN_SCALES = np.array([0.4267,0.2156,0.1089,0.0556])
#PNET_PYRAMID_ARR= np.array([[[1, 2, 130, 99],[1, 4, 130, 99]],[[1, 2, 91, 69],[1, 4, 91, 69]],[[1, 2, 63, 47],[1, 4, 63, 47]],[[1, 2, 44, 32],[1, 4, 44, 32]],[[1, 2, 30, 22],[1, 4, 30, 22]],[[1, 2, 20, 14],[1, 4, 20, 14]],[[1, 2, 13, 9],[1, 4, 13, 9]],[[1, 2, 8, 5],[1, 4, 8, 5]],[[1, 2, 4, 2],[1, 4, 4, 2]]])
PNET_ODD_ARR = np.array([[1, 2, 198, 99],[1, 4, 198, 99]])
PNET_EVEN_ARR = np.array([[1, 2, 140, 69],[1, 4, 140, 69]])
boundingbox_list = []
IMAGE = np.zeros((344,450,3))
IMAGE_list = []
IMAGE_list.append(IMAGE)
IMAGE_list.append(IMAGE)
proflag = 1
#----------------------------------------------多线程类
class MtcnnThread (threading.Thread): #继承父类threading.Thread
def __init__(self):
threading.Thread.__init__(self)
def run(self): #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
minsize = 20
threshold = [0.8, 0.9, 0.95]
factor = 0.709
pnet_rknn_list=init_pnet()
rnet_rknn = RKNN()
onet_rknn = RKNN()
rnet_rknn.load_rknn('./RNet.rknn')
onet_rknn.load_rknn('./ONet.rknn')
ret = rnet_rknn.init_runtime()
if ret != 0:
#print('Init rnet runtime environment failed')
exit(ret)
ret = onet_rknn.init_runtime()
if ret != 0:
#print('Init onet runtime environment failed')
exit(ret)
sys.stdout = open('/dev/stdout', 'w')
sys.stderr = open('/dev/stderr', 'w')
global proflag
global IMAGE_list
global boundingbox_list
nonfacecount = 0
#wrongimg = 1
while(proflag ==1):
imreadLock.acquire()
img0 = IMAGE_list[0].copy()
img = IMAGE_list[1].copy()
imreadLock.release()
#tic()
score_cmp = compare_image(img0,img)
#print("score_cmp",score_cmp)
#toc()
if score_cmp < 0.98:
#imreadLock.release()
#print("detect face start")
#cv2.imwrite("aa.jpg",img)
tic()
boundingboxes, points = detect_face(img, minsize, pnet_rknn_list, rnet_rknn, onet_rknn, threshold, False,factor)
#print("boundingboxes shape",boundingboxes.shape)
print("total cost")
toc()
if boundingboxes.shape[0] != 0:
if len(boundingbox_list) != 0:
boundingbox_list.clear()
boundingbox_list.append(boundingboxes)
else:
#path = str(wrongimg)+".jpg"
#cv2.imwrite(path,img)
#wrongimg += 1
nonfacecount += 1
if nonfacecount >= 3:
boundingbox_list.clear()
nonfacecount = 0
for i in range(2):
pnet_rknn_list[i].release()
rnet_rknn.release()
onet_rknn.release()
'''
def return_res(self):
try:
return self.boundingboxes
except Exception:
return None
'''
'''
class MtcnnThread(threading.Thread):
def __init__(self, target, args):
super().__init__()
self.target = target
self.args = args
def run(self):
self.target(*self.args)
'''
class ShowImgThread (threading.Thread): #继承父类threading.Thread
def __init__(self):
threading.Thread.__init__(self)
def run(self): #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 \
global proflag
global IMAGE_list
global boundingbox_list
proflag = 1
capture = cv2.VideoCapture(0)
while (True):
#tic()
ret, img = capture.read()
if ret == True:
#img = cv2.imread('./test4.jpg')
img = cv2.resize(img,(450,344))
#print("img shape",img.shape)
image = img.copy()
del IMAGE_list[0]
IMAGE_list.append(image)
#print(IMAGE)
#IMAGE = cv2.cvtColor(IMAGE, cv2.COLOR_BGR2RGB)
if len(boundingbox_list) != 0:
imreadLock.acquire()
img = drawBoxes(img, boundingbox_list[0])
imreadLock.release()
cv2.imshow('img', img)
c = cv2.waitKey(1) & 0xff
if c==27:
break
#toc()
#print("imshow--------------------")
#if boundingboxes.shape[0] > 0:
# error.append[imgpath]
#print(error)
proflag = 0
cv2.destroyAllWindows()
capture.release()
def compare_image(image1, image2): #图片对比函数
grayA = cv2.cvtColor(image1, cv2.COLOR_RGB2GRAY)
grayB = cv2.cvtColor(image2, cv2.COLOR_RGB2GRAY)
diff = np.sum((grayA-grayB)**2)
score = 1-diff/450/344/255
return score
def bbreg(boundingbox, reg):
reg = reg.T
# calibrate bouding boxes
if reg.shape[1] == 1:
#print("reshape of reg")
pass # reshape of reg
w = boundingbox[:,2] - boundingbox[:,0] + 1
h = boundingbox[:,3] - boundingbox[:,1] + 1
bb0 = boundingbox[:,0] + reg[:,0]*w
bb1 = boundingbox[:,1] + reg[:,1]*h
bb2 = boundingbox[:,2] + reg[:,2]*w
bb3 = boundingbox[:,3] + reg[:,3]*h
boundingbox[:,0:4] = np.array([bb0, bb1, bb2, bb3]).T
#print("bb", boundingbox)
return boundingbox
def pad(boxesA, w, h):
boxes = boxesA.copy() # shit, value parameter!!!
#print('#################')
#print('boxes', boxes)
#print('w,h', w, h)
tmph = boxes[:,3] - boxes[:,1] + 1
tmpw = boxes[:,2] - boxes[:,0] + 1
numbox = boxes.shape[0]
#print('tmph', tmph)
#print('tmpw', tmpw)
dx = np.ones(numbox)
dy = np.ones(numbox)
edx = tmpw
edy = tmph
x = boxes[:,0:1][:,0]
y = boxes[:,1:2][:,0]
ex = boxes[:,2:3][:,0]
ey = boxes[:,3:4][:,0]
tmp = np.where(ex > w)[0]
if tmp.shape[0] != 0:
edx[tmp] = -ex[tmp] + w-1 + tmpw[tmp]
ex[tmp] = w-1
tmp = np.where(ey > h)[0]
if tmp.shape[0] != 0:
edy[tmp] = -ey[tmp] + h-1 + tmph[tmp]
ey[tmp] = h-1
tmp = np.where(x < 1)[0]
if tmp.shape[0] != 0:
dx[tmp] = 2 - x[tmp]
x[tmp] = np.ones_like(x[tmp])
tmp = np.where(y < 1)[0]
if tmp.shape[0] != 0:
dy[tmp] = 2 - y[tmp]
y[tmp] = np.ones_like(y[tmp])
# for python index from 0, while matlab from 1
dy = np.maximum(0, dy-1)
dx = np.maximum(0, dx-1)
y = np.maximum(0, y-1)
x = np.maximum(0, x-1)
edy = np.maximum(0, edy-1)
edx = np.maximum(0, edx-1)
ey = np.maximum(0, ey-1)
ex = np.maximum(0, ex-1)
#print("dy" ,dy )
#print("dx" ,dx )
#print("y " ,y )
#print("x " ,x )
#print("edy" ,edy)
#print("edx" ,edx)
#print("ey" ,ey )
#print("ex" ,ex )
#print('boxes', boxes)
return [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph]
def rerec(bboxA):
# convert bboxA to square
w = bboxA[:,2] - bboxA[:,0]
h = bboxA[:,3] - bboxA[:,1]
l = np.maximum(w,h).T
#print('bboxA', bboxA)
#print('w', w)
#print('h', h)
#print('l', l)
bboxA[:,0] = bboxA[:,0] + w*0.5 - l*0.5
bboxA[:,1] = bboxA[:,1] + h*0.5 - l*0.5
bboxA[:,2:4] = bboxA[:,0:2] + np.repeat([l], 2, axis = 0).T
return bboxA
def nms(boxes, threshold, type):
"""nms
:boxes: [:,0:5]
:threshold: 0.5 like
:type: 'Min' or others
:returns: TODO
"""
if boxes.shape[0] == 0:
return np.array([])
x1 = boxes[:,0]
y1 = boxes[:,1]
x2 = boxes[:,2]
y2 = boxes[:,3]
s = boxes[:,4]
area = np.multiply(x2-x1+1, y2-y1+1)
I = np.array(s.argsort()) # read s using I
pick = [];
while len(I) > 0:
xx1 = np.maximum(x1[I[-1]], x1[I[0:-1]])
yy1 = np.maximum(y1[I[-1]], y1[I[0:-1]])
xx2 = np.minimum(x2[I[-1]], x2[I[0:-1]])
yy2 = np.minimum(y2[I[-1]], y2[I[0:-1]])
w = np.maximum(0.0, xx2 - xx1 + 1)
h = np.maximum(0.0, yy2 - yy1 + 1)
inter = w * h
if type == 'Min':
o = inter / np.minimum(area[I[-1]], area[I[0:-1]])
else:
o = inter / (area[I[-1]] + area[I[0:-1]] - inter)
pick.append(I[-1])
I = I[np.where( o <= threshold)[0]]
return pick
def generateBoundingBox(map_prob, reg, scale, pyramid, threshold):
stride = 2
cellsize = 12
map_prob = map_prob.T
#print("map_prob shape",map_prob.shape)
dx1 = reg[0,:,:].T
dy1 = reg[1,:,:].T
dx2 = reg[2,:,:].T
dy2 = reg[3,:,:].T
(x, y) = np.where(map_prob >= threshold)
#print("x:",x)
#print("y:",y)
yy = y.copy()
xx = x.copy()
lenface = len(yy)
#print("lenface:",lenface)
lenpy = len(pyramid)
w0 = pyramid[0][0]
#print("w0:",w0)
#print("(w0-6)/2+1:",(w0-6)/2+1)
pyramid_reverse = []
htmp = 0
for i in range(1,lenpy):
htmp += pyramid[i][1]
pyramid_reverse.append(htmp)
pyramid_reverse.reverse()
#print("pyramid_reverse:",pyramid_reverse)
label = np.zeros(lenface)+lenpy-1
for i in range(lenface):
if yy[i] > math.ceil((w0-6)/2)+1:
yy[i] -= math.ceil((w0)/2)+1
yy[i] = max(yy[i],0)
if xx[i] < math.ceil((pyramid_reverse[lenpy-2]-6)/2)+1:
label[i] = 1
else:
for j in range(1,lenpy-1):
if xx[i] > math.ceil((pyramid_reverse[j]-6)/2)+1:
xx[i] -= math.ceil((pyramid_reverse[j])/2)+1
xx[i] = max(xx[i],0)
label[i] -= j-1
break
else:
label[i] = 0
scales_py = np.zeros(lenface)
for i in range(0,lenface):
scales_py[i] = scale[int(label[i])]
#print(scales_py)
#print("......................................")
#print(scales_py)
'''
if y.shape[0] == 1: # only one point exceed threshold
y = y.T
x = x.T
score = map_prob[x,y].T
dx1 = dx1.T
dy1 = dy1.T
dx2 = dx2.T
dy2 = dy2.T
# a little stange, when there is only one bb created by PNet
#print("1: x,y", x,y)
a = (x*map_prob.shape[1]) + (y+1)
x = a/map_prob.shape[0]
y = a%map_prob.shape[0] - 1
#print("2: x,y", x,y)
else:
score = map_prob[x,y]
'''
#print("dx1.shape", dx1.shape)
#print('map_prob.shape', map_prob.shape)
score = map_prob[x,y]
reg = np.array([dx1[x,y], dy1[x,y], dx2[x,y], dy2[x,y]])
if reg.shape[0] == 0:
pass
boundingbox = np.array([yy, xx]).T
scales_py = np.vstack((scales_py,scales_py))
scales_py = scales_py.T
#print(boundingbox.shape)
bb1 = np.fix((stride * (boundingbox) + 1) / scales_py).T # matlab index from 1, so with "boundingbox-1"
bb2 = np.fix((stride * (boundingbox) + cellsize - 1 + 1) / scales_py).T # while python don't have to
score = np.array([score])
boundingbox_out = np.concatenate((bb1, bb2, score, reg), axis=0)
#print('(x,y)',x,y)
#print('score', score)
#print('reg', reg)
#print("generateBoundingBox over")
return boundingbox_out.T
def drawBoxes(im, boxes):
x1 = boxes[:,0]
y1 = boxes[:,1]
x2 = boxes[:,2]
y2 = boxes[:,3]
for i in range(x1.shape[0]):
cv2.rectangle(im, (int(x1[i]), int(y1[i])), (int(x2[i]), int(y2[i])), (0,255,0), 1)
return im
from time import time
_tstart_stack = []
def tic():
_tstart_stack.append(time())
def toc(fmt="Elapsed: %s s"):
print(fmt % (time()-_tstart_stack.pop()))
#输入原始图片,根据缩放金字塔系数生成奇偶拼接图
def img_joint(img):
img_odd_pyramid = []
img_even_pyramid = []
for i in range(9):
imgtmp = cv2.resize(img,(PNET_PYRAMID[i][0],PNET_PYRAMID[i][1]))
#print("imgtmp shape:",imgtmp.shape)
imgtmp = imgtmp.transpose(2,0,1)
#print("imgtmp shape:",imgtmp.shape)
if i%2 == 0:
img_odd_pyramid.append(imgtmp)
else:
img_even_pyramid.append(imgtmp)
# odd图片拼接
w0 = ODD_PYRAMID[0][0]
h0 = ODD_PYRAMID[0][1]
w1 = ODD_PYRAMID[1][0]
image_odd = np.zeros((3, h0, w0+w1))
image_odd[:,0:h0,0:w0] = img_odd_pyramid[0]
htmp = 0
for i in range(1,len(img_odd_pyramid)):
image_odd[:,htmp:htmp+img_odd_pyramid[i].shape[1],w0:w0+img_odd_pyramid[i].shape[2]] = img_odd_pyramid[i]
htmp += img_odd_pyramid[i].shape[1]
# even图片拼接
w0 = EVEN_PYRAMID[0][0]
h0 = EVEN_PYRAMID[0][1]
w1 = EVEN_PYRAMID[1][0]
image_even = np.zeros((3, h0, w0+w1))
image_even[:,0:h0,0:w0] = img_even_pyramid[0]
htmp = 0
for i in range(1,len(img_even_pyramid)):
image_even[:,htmp:htmp+img_even_pyramid[i].shape[1],w0:w0+img_even_pyramid[i].shape[2]] = img_even_pyramid[i]
htmp += img_even_pyramid[i].shape[1]
img_odd_even = [image_odd,image_even]
return img_odd_even
def delete_abn(boxes, width,height):
"""delete abnormal window
Arguments:
boxes: a float numpy array of shape [n, 5],
where each row is (xmin, ymin, xmax, ymax, score).
width: a int number.
height:a int number.
Returns:
list with indices of the selected boxes
"""
# if there are no boxes, return the empty list
if len(boxes) == 0:
return []
# grab the coordinates of the bounding boxes
x1, y1, x2, y2, score = [boxes[:, i] for i in range(5)]
area = (x2 - x1 + 1.0)*(y2 - y1 + 1.0)
# compute intersections
# of the box with the image
# warning:在图片中y轴朝下
# left top corner of intersection boxes
ix1 = np.maximum(0, x1)
iy1 = np.maximum(0, y1)
# right bottom corner of intersection boxes
ix2 = np.minimum(width, x2)
iy2 = np.minimum(height, y2)
# width and height of intersection boxes
w = np.maximum(0.0, ix2 - ix1 + 1.0)
h = np.maximum(0.0, iy2 - iy1 + 1.0)## 修改,原代码为h = np.maximum(0.0, iy2 - iy1 + 1.0)
# intersections' areas
inter = w * h
overlap = inter/area
# list of picked indices
pick = []
pick = np.where(overlap > 0.4)[0]
return pick
def detect_face(img, minsize, PNet_list, RNet, ONet, threshold, fastresize, factor):
points = []
h = img.shape[0]
w = img.shape[1]
img_odd_even = img_joint(img)
#print("img_joint start")
#print("img_odd_even[0] shape:",img_odd_even[0].shape)
#print("img_odd_even[1] shape:",img_odd_even[1].shape)
# first stage
#'''
#print("img_odd_even[0]:",img_odd_even[0].shape)
#img_odd_even[0] = np.swapaxes(img_odd_even[0], 1, 2)
#img_odd_even[0] = np.swapaxes(img_odd_even[0], 0, 2)
img_odd_even[0] = img_odd_even[0].transpose(1,2,0)
img_odd_even[0] = np.array(img_odd_even[0], dtype = np.uint8)
#cv2.imshow('img_odd_even[0]',img_odd_even[0])
#ch = cv2.waitKey(50000) & 0xFF
#img_odd_even[1] = np.swapaxes(img_odd_even[1], 1, 2)
#img_odd_even[1] = np.swapaxes(img_odd_even[1], 0, 2)
#print(img_odd_even[1].shape)
img_odd_even[1] = img_odd_even[1].transpose(1,2,0)
img_odd_even[1] = np.array(img_odd_even[1], dtype = np.uint8)
#cv2.imshow('img_odd_even[1]',img_odd_even[1])
#ch = cv2.waitKey(50000) & 0xFF
#'''
img_odd_even[0] = np.swapaxes(img_odd_even[0], 0, 2)
img_odd_even[1] = np.swapaxes(img_odd_even[1], 0, 2)
#img_joint is ok
#tic()
output0= PNet_list[0].inference(inputs=[img_odd_even[0]],data_format='nchw')
#print("pnet0 inference over")
#toc()
odd_prob0 = output0[1]
odd_conv4_2_0 = output0[0]
odd_prob0=odd_prob0.reshape(PNET_ODD_ARR[0][1], PNET_ODD_ARR[0][2], PNET_ODD_ARR[0][3])
odd_conv4_2_0=odd_conv4_2_0.reshape(PNET_ODD_ARR[1][1], PNET_ODD_ARR[1][2], PNET_ODD_ARR[1][3])
odd_boxes = generateBoundingBox(odd_prob0[1,:,:], odd_conv4_2_0, ODD_SCALES,ODD_PYRAMID,threshold[0])
#print("odd_boxes:",odd_boxes.shape)
#tic()
output1= PNet_list[1].inference(inputs=[img_odd_even[1]],data_format='nchw')
#print("pnet inference1 over")
#toc()
even_prob1 = output1[1]
#print("even_prob1 shape:",even_prob1.shape)
even_conv4_2_1 = output1[0]
even_prob1= even_prob1.reshape(PNET_EVEN_ARR[0][1], PNET_EVEN_ARR[0][2], PNET_EVEN_ARR[0][3])
#print(even_prob1[1,:,:])
even_conv4_2_1=even_conv4_2_1.reshape(PNET_EVEN_ARR[1][1], PNET_EVEN_ARR[1][2], PNET_EVEN_ARR[1][3])
even_boxes = generateBoundingBox(even_prob1[1,:,:], even_conv4_2_1, EVEN_SCALES,EVEN_PYRAMID,threshold[0])
#print("even_boxes:",even_boxes.shape)
total_boxes = np.concatenate((odd_boxes, even_boxes), axis=0)
if total_boxes.shape[0] != 0:
pick = delete_abn(total_boxes, 450, 344)
else:
pick = []
if len(pick) > 0 :
total_boxes = total_boxes[pick, :]
#print(total_boxes.shape)
#print("pnet over")
numbox = total_boxes.shape[0]
#print("pnet numbox:",numbox)
if numbox > 0:
# nms
pick = nms(total_boxes, 0.4, 'Union')
total_boxes = total_boxes[pick, :]
# revise and convert to square
regh = total_boxes[:,3] - total_boxes[:,1]
regw = total_boxes[:,2] - total_boxes[:,0]
t1 = total_boxes[:,0] + total_boxes[:,5]*regw
t2 = total_boxes[:,1] + total_boxes[:,6]*regh
t3 = total_boxes[:,2] + total_boxes[:,7]*regw
t4 = total_boxes[:,3] + total_boxes[:,8]*regh
t5 = total_boxes[:,4]
total_boxes = np.array([t1,t2,t3,t4,t5]).T
total_boxes = rerec(total_boxes) # convert box to square
#print("[4]:",total_boxes.shape[0])
total_boxes[:,0:4] = np.fix(total_boxes[:,0:4])
#print("[4.5]:",total_boxes.shape[0])
#print(total_boxes)
[dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = pad(total_boxes, w, h)
'''
print(dy)
print(edy)
print(dx)
print(edx)
print(y)
print(ey)
print(x)
print(ex)
'''
#print(tmpw)
#print(tmph)
numbox = total_boxes.shape[0]
#print("window number after pnet+nms:",numbox)
#####
# 1 #
#####
if numbox > 0:
# second stage
#tempimg = np.load('tempimg.npy')
# construct input for RNet
out_conv5_2=np.zeros((0,4))
tempimg = np.zeros((numbox, 24, 24, 3)) # (24, 24, 3, numbox)
tmptarget = np.zeros((24, 24,3))
score=[]
#out_prob=0
'''
out_conv5_2=np.zeros((0,4))
img_test = cv2.imread('rnet-24_24_7.jpg')
print("load img_test successfully")
cv2.imshow('img_test',img_test)
ch = cv2.waitKey(10000) & 0xFF
img_test = np.swapaxes(img_test, 0, 2)
img_test = np.array([img_test], dtype = np.uint8)
out=RNet.inference(inputs=[img_test],data_format='nchw')
print("pent is fine")
tmp00 = np.zeros((24,24,3))
tmp00[0:24, 0:24,:] = img[24:48, 24:48,:]
tmptarget00 = np.zeros((24, 24,3))
tmptarget00 = cv2.resize(tmp00, (24, 24))
tmptarget00 = np.array(tmptarget00, dtype = np.uint8)
print("tmptarget00 shape:",tmptarget00.shape)
cv2.imshow('tmptarget00',tmptarget00)
ch = cv2.waitKey(10000) & 0xFF
print("try successfully")
cv2.imshow('img',img)#######################################
ch = cv2.waitKey(10000) & 0xFF
'''
for k in range(numbox):
tmp = np.zeros((int(tmph[k]) +1, int(tmpw[k]) + 1,3))
tmp[int(dy[k]):int(edy[k])+1, int(dx[k]):int(edx[k])+1,:] = img[int(y[k]):int(ey[k])+1, int(x[k]):int(ex[k])+1,:]
tmptarget = cv2.resize(tmp, (24, 24))
tmptarget = np.array(tmptarget, dtype = np.uint8)
tmptarget = np.swapaxes(tmptarget, 0, 2)
#print("tmptarget shape:",tmptarget.shape)
#print("tmptarget type",type(tmptarget))
#cv2.imshow('tmptarget',tmptarget)
#ch = cv2.waitKey(10000) & 0xFF
#tmptarget = np.array([tmptarget], dtype = np.uint8)
#print("tmptarget type",type(tmptarget))
#print("tmptarget shape:",tmptarget.shape)
#print(tmptarget)
#print("before pnet.inference")
out=RNet.inference(inputs=[tmptarget],data_format='nchw')
out_prob1=out[1]
score=np.append(score,out_prob1[:,1])
out_conv5_2=np.concatenate((out_conv5_2,out[0]),axis=0)
pass_t = np.where(score>threshold[1])[0]
score = np.array([score[pass_t]]).T
total_boxes = np.concatenate( (total_boxes[pass_t, 0:4], score), axis = 1)
mv = out_conv5_2[pass_t, :].T
if total_boxes.shape[0] > 0:
pick = nms(total_boxes, 0.5, 'Union')
#print('pick', pick)
if len(pick) > 0 :
total_boxes = total_boxes[pick, :]
#print("[6]:",total_boxes.shape[0])
total_boxes = bbreg(total_boxes, mv[:, pick])
#print("[7]:",total_boxes.shape[0])
total_boxes = rerec(total_boxes)
#print("[8]:",total_boxes.shape[0])
#print("rnet over")
#####
# 2 #
#####
numbox = total_boxes.shape[0]
#print("rnet numbox is %d",numbox)
if numbox > 0:
# third stage
total_boxes = np.fix(total_boxes)
[dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = pad(total_boxes, w, h)
tempimg = np.zeros((numbox, 48, 48, 3))
tmptarget = np.zeros((3, 48, 48))
out_conv6_2=np.zeros((0,4))
out_conv6_3=np.zeros((0,10))
score = []
for k in range(numbox):
tmp = np.zeros((int(tmph[k]), int(tmpw[k]),3))
tmp[int(dy[k]):int(edy[k])+1, int(dx[k]):int(edx[k])+1] = img[int(y[k]):int(ey[k])+1, int(x[k]):int(ex[k])+1]
tempimg[k,:,:,:] = cv2.resize(tmp, (48, 48))
tmptarget = np.swapaxes(tempimg[k], 0, 2)
tmptarget = np.array([tmptarget], dtype = np.uint8)
#tic()
out=ONet.inference(inputs=[tmptarget],data_format='nchw')
#toc()
out_conv6_3=np.concatenate((out_conv6_3,out[1]),axis=0)
out_conv6_2=np.concatenate((out_conv6_2,out[0]),axis=0)
score=np.append(score,out[2][:,1])
#tempimg = (tempimg-127.5)*0.0078125 # [0,255] -> [-1,1]
# ONet
points = out_conv6_3
pass_t = np.where(score>threshold[2])[0]#csqerr
points = points[pass_t, :]
score = np.array([score[pass_t]]).T
#print("total_boxes shape ",total_boxes.shape)
total_boxes = np.concatenate( (total_boxes[pass_t, 0:4], score), axis=1)
#print("[9]:",total_boxes.shape[0])
mv = out_conv6_2[pass_t, :].T
w = total_boxes[:,3] - total_boxes[:,1] + 1
h = total_boxes[:,2] - total_boxes[:,0] + 1
points[:, 0:5] = np.tile(w, (5,1)).T * points[:, 0:5] + np.tile(total_boxes[:,0], (5,1)).T - 1
points[:, 5:10] = np.tile(h, (5,1)).T * points[:, 5:10] + np.tile(total_boxes[:,1], (5,1)).T -1
#print("onet total_boxes.shape[0] ",total_boxes.shape[0])
if total_boxes.shape[0] > 0:
total_boxes = bbreg(total_boxes, mv[:,:])
#print("[10]:",total_boxes.shape[0])
pick = nms(total_boxes, 0.7, 'Min')
#print(pick)
if len(pick) > 0 :
total_boxes = total_boxes[pick, :]
#print("[11]:",total_boxes.shape[0])
points = points[pick, :]
#####
# 3 #
#####
#print("3:",total_boxes.shape)
#print("face_dect over")
return total_boxes, points
def init_pnet():
list = []
rknn_odd_name = "PNet_%d_%d.rknn" %(406,207);
pnet_odd_rknn = RKNN() #verbose=True,verbose_file='./mobilenet_build.log'
pnet_odd_rknn.load_rknn(rknn_odd_name)
ret = pnet_odd_rknn.init_runtime()
if ret != 0:
#print('Init pnet runtime environment failed')
exit(ret)
list.append(pnet_odd_rknn)
rknn_even_name = "PNet_%d_%d.rknn" %(289,147);
pnet_even_rknn = RKNN() #verbose=True,verbose_file='./mobilenet_build.log'
pnet_even_rknn.load_rknn(rknn_even_name)
ret = pnet_even_rknn.init_runtime()
if ret != 0:
#print('Init pnet runtime environment failed')
exit(ret)
list.append(pnet_even_rknn)
return list
def main():
imgthread = ShowImgThread()
winthread = MtcnnThread()
imgthread.start()
print("imgthread start")
winthread.start()
print("winthread start")
imgthread.join()
#print(IMAGE)
winthread.join()
#cv2.destroyAllWindows()
if __name__ == "__main__":
main()
| chenshiqin/mtcnn | demo_camera_spilt.py | demo_camera_spilt.py | py | 26,819 | python | en | code | 5 | github-code | 1 | [
{
"api_name": "threading.Lock",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number... |
41559504876 | #!/usr/bin/env python
def fit_lambda(root='j100025+021706', newfunc=True, bucket_name='aws-grivam'):
import time
import os
import numpy as np
import boto3
import json
from grizli_aws.fit_redshift_single import run_grizli_fit
beams, files = get_needed_paths(root, bucket_name=bucket_name)
if len(beams) == 0:
print('{0}: No beams to fit'.format(root))
for obj in beams:
print(obj)
event = {
's3_object_path': obj,
'verbose': "True",
'skip_started': "True",
'check_wcs' : "False",
'bucket' : bucket_name
}
try:
run_grizli_fit(event)
except:
pass
# Status again to check products
beams, files = get_needed_paths(root)
def get_needed_paths(root, get_string=False, bucket_name='aws-grivam'):
"""
Get the S3 paths of the "beams.fits" files that still need to be fit.
"""
import boto3
import time
s3 = boto3.resource('s3')
s3_client = boto3.client('s3')
bkt = s3.Bucket(bucket_name)
files = [obj.key for obj in bkt.objects.filter(Prefix='Pipeline/{0}/Extractions/'.format(root))]
beams = []
logs = []
full = []
start = []
for file in files:
if 'beams.fits' in file:
beams.append(file)
if 'log_par' in file:
logs.append(file)
if 'start.log' in file:
start.append(file)
if 'full.fits' in file:
full.append(file)
label = '{0} / {1} / Nbeams: {2}, Nfull: {3}, Nlog: {4}, Nstart: {5}'.format(root, time.ctime(), len(beams), len(full), len(logs), len(start))
if get_string:
return label
print(label)
for i in range(len(beams))[::-1]:
test = (beams[i].replace('.beams.fits', '.full.fits') in full)
test |= (beams[i].replace('.beams.fits', '.start.log') in start)
if test:
beams.pop(i)
return beams, files
if __name__ == "__main__":
import sys
import numpy as np
from grizli import utils
from grizli.pipeline import auto_script
utils.set_warnings()
if len(sys.argv) < 2:
print('Usage: fit_redshift_lambda.py {field}')
exit
root = sys.argv[1]
if len(sys.argv) == 3:
newfunc = bool(sys.argv[2].lower() == 'true')
else:
newfunc = False
bucket_name='aws-grivam'
bucket_name='grizli-grism'
fit_lambda(root=root, newfunc=newfunc, bucket_name=bucket_name)
| grizli-project/grizli-aws | scripts/fit_redshift_local.py | fit_redshift_local.py | py | 2,656 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "grizli_aws.fit_redshift_single.run_grizli_fit",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "boto3.resource",
"line_number": 41,
"usage_type": "call"
},
{
"api_name": "boto3.client",
"line_number": 42,
"usage_type": "call"
},
{
"api_nam... |
44221249022 | import torch
def tile_features_and_labels(x, y):
"""
Tile the features and lables along the sequence dimension.
Example: the sequence [(x_1,y_1), (x_2, y_2), (x_3, y_3)] encodes 3 different testing paradigms.
We can use [(x_1, y_1), (x_2, y_2), x_3] to predict y_3, [(x_2,y_2), (x_3,y_3), x_1] to predict y_1, etc.
Args:
x: torch.Tensor of shape [B, N, C]
y: torch.Tensor of shape [B, N, 1]
Returns:
(x,y,gather_idx) where x has shape [B*N, N, C], y has shape [B*N, N, 1] and gather_idx is the NxN identity matrix
stacked B times along the batch dimension.
"""
B, N, C = x.shape
# Repeat x so that batch_dim is b*n (n=seq length).
x = x.repeat_interleave(N, dim=0)
y = y.repeat_interleave(N, dim=0)
gather_idx = torch.arange(N, device=x.device).repeat(B)
return x, y, gather_idx
| cfifty/CAMP | models/context_model_utils.py | context_model_utils.py | py | 830 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "torch.arange",
"line_number": 24,
"usage_type": "call"
}
] |
41436655263 | import logging
from string import ascii_letters
import pytest
# Import TestListener with a leading underscore to prevent pytest from
# thinking that it's a test class.
from stomp.listener import TestListener as _TestListener
from streamsets.testframework.markers import jms, sdc_min_version
from streamsets.testframework.utils import get_random_string
logger = logging.getLogger(__name__)
DEFAULT_PASSWORD = 'admin'
DEFAULT_USERNAME = 'admin'
JMS_DESTINATION_TYPE = 'QUEUE'
JMS_INITIAL_CONTEXT_FACTORY = 'org.apache.activemq.jndi.ActiveMQInitialContextFactory'
JNDI_CONNECTION_FACTORY = 'ConnectionFactory'
@jms('activemq')
@sdc_min_version("4.4.0")
@pytest.mark.parametrize('include_headers, prefix_all_headers', [[True, True], [True, False], [False, False]])
def test_jms_headers_origin_to_destination(sdc_builder, sdc_executor, jms, include_headers, prefix_all_headers):
"""Validating that JMS standard headers are serialized into Record headers."""
message_data = 'This will be a message sent to JMS'
custom_header = 'This is my custom header'
custom_header_from_origin = 'This is my custom header from origin'
headers = {'custom_hedader_from_origin': custom_header_from_origin}
first_queue = get_random_string(ascii_letters, 5)
second_queue = get_random_string(ascii_letters, 5)
builder = sdc_builder.get_pipeline_builder()
# Configure the jms_consumer stage
jms_consumer = builder.add_stage('JMS Consumer')
jms_consumer.set_attributes(data_format='TEXT',
jms_destination_name=first_queue,
jms_destination_type=JMS_DESTINATION_TYPE,
jms_initial_context_factory=JMS_INITIAL_CONTEXT_FACTORY,
jndi_connection_factory=JNDI_CONNECTION_FACTORY,
password=DEFAULT_PASSWORD,
username=DEFAULT_USERNAME,
prefix_all_headers=prefix_all_headers)
jms_producer = builder.add_stage('JMS Producer', type='destination')
jms_producer.set_attributes(data_format='TEXT',
jms_destination_name=second_queue,
jms_destination_type=JMS_DESTINATION_TYPE,
jms_initial_context_factory=JMS_INITIAL_CONTEXT_FACTORY,
jndi_connection_factory=JNDI_CONNECTION_FACTORY,
password=DEFAULT_PASSWORD,
username=DEFAULT_USERNAME,
include_headers=include_headers)
expression_evaluator = builder.add_stage('Expression Evaluator')
expression_evaluator.set_attributes(header_attribute_expressions=[
{
"attributeToSet": "jms.header.customHeader",
"headerAttributeExpression": custom_header
}
])
jms_consumer >> expression_evaluator >> jms_producer
pipeline = builder.build().configure_for_environment(jms)
sdc_executor.add_pipeline(pipeline)
connection = jms.client_connection
try:
logger.info('Sending messages to JMS using ActiveMQ client ...')
listener = _TestListener()
connection.set_listener('', listener)
connection.start()
connection.connect(login=DEFAULT_USERNAME, passcode=DEFAULT_PASSWORD)
connection.send(first_queue, message_data, headers=headers, persistent='false')
connection.subscribe(destination=f'/queue/{second_queue}', id=second_queue)
sdc_executor.start_pipeline(pipeline)
sdc_executor.wait_for_pipeline_metric(pipeline, 'input_record_count', 1)
sdc_executor.stop_pipeline(pipeline)
assert len(listener.message_list) == 1
message = listener.message_list[0]
assert message_data + '\n' in message # JMS introduces a new line at the end of the message
message = str(message)
if include_headers:
assert custom_header in message
assert 'jms.header.messageId' in message
assert 'jms.header.timestamp' in message
assert 'jms.header.correlationId' in message
assert 'jms.header.deliveryMode' in message
assert 'jms.header.redelivered' in message
assert 'jms.header.type' in message
assert 'jms.header.expiration' in message
assert 'jms.header.priority' in message
if prefix_all_headers:
assert custom_header_from_origin in message
else:
assert custom_header_from_origin not in message
else:
assert custom_header not in message
assert 'jms.header.messageId' not in message
assert 'jms.header.timestamp' not in message
assert 'jms.header.correlationId' not in message
assert 'jms.header.deliveryMode' not in message
assert 'jms.header.redelivered' not in message
assert 'jms.header.type' not in message
assert 'jms.header.expiration' not in message
assert 'jms.header.priority' not in message
finally:
connection.send(first_queue, 'SHUTDOWN', persistent='false')
connection.send(second_queue, 'SHUTDOWN', persistent='false')
connection.disconnect()
| streamsets/datacollector-tests | pipeline/test_jms_stages.py | test_jms_stages.py | py | 5,338 | python | en | code | 17 | github-code | 1 | [
{
"api_name": "logging.getLogger",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "streamsets.testframework.utils.get_random_string",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "string.ascii_letters",
"line_number": 30,
"usage_type": "argument"
}... |
70547442913 | import logging
import ask_sdk_core.utils as ask_utils
import openai
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.dispatch_components import AbstractExceptionHandler
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_model import Response
# Set your OpenAI API key
openai.api_key = "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"
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
messages = [{"role": "system", "content": "Eres un asistente muy útil. Por favor responda de forma clara y concisa en castellano."}]
class LaunchRequestHandler(AbstractRequestHandler):
"""Handler for Skill Launch."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_request_type("LaunchRequest")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
speak_output = "¡Bienvenidos al Chat 'GPT4' de 'Open AI'! ¿Cuál es tu pregunta?"
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class GptQueryIntentHandler(AbstractRequestHandler):
"""Handler for Gpt Query Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_intent_name("GptQueryIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
query = handler_input.request_envelope.request.intent.slots["query"].value
response = generate_gpt_response(query)
return (
handler_input.response_builder
.speak(response)
.ask("¿Alguna otra pregunta?")
.response
)
class CatchAllExceptionHandler(AbstractExceptionHandler):
"""Generic error handling to capture any syntax or routing errors."""
def can_handle(self, handler_input, exception):
# type: (HandlerInput, Exception) -> bool
return True
def handle(self, handler_input, exception):
# type: (HandlerInput, Exception) -> Response
logger.error(exception, exc_info=True)
speak_output = "Disculpe, no conseguí obtener uma respuesta para esta pregunta. Intente preguntar de otra forma."
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class CancelOrStopIntentHandler(AbstractRequestHandler):
"""Single handler for Cancel and Stop Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return (ask_utils.is_intent_name("AMAZON.CancelIntent")(handler_input) or
ask_utils.is_intent_name("AMAZON.StopIntent")(handler_input))
def handle(self, handler_input):
# type: (HandlerInput) -> Response
speak_output = "Saliendo del modo Chat GPT."
return (
handler_input.response_builder
.speak(speak_output)
.response
)
def generate_gpt_response(query):
try:
messages.append(
{"role": "user", "content": query},
)
response = openai.ChatCompletion.create(
model="gpt-4",
messages=messages,
max_tokens=1000,
n=1,
stop=None,
temperature=0.5
)
reply = response['choices'][0]['message']['content'].strip()
messages.append({"role": "assistant", "content": reply})
return reply
except Exception as e:
return f"Error al generar una respuesta: {str(e)}"
sb = SkillBuilder()
sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(GptQueryIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_exception_handler(CatchAllExceptionHandler())
lambda_handler = sb.lambda_handler() | cainfoxy/Alexa-GPT4-CFX | Lambda/lambda_function.py | lambda_function.py | py | 4,046 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "openai.api_key",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "logging.getLogger",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "logging.INFO",
"line_number": 14,
"usage_type": "attribute"
},
{
"api_name": "ask_sdk_core.... |
32060238017 | from django.shortcuts import render
from core.forms import NameForm
def form_manual(request):
data = {}
if request.method == 'POST':
data['name'] = request.POST.get('name', 'name not found')
data['active'] = request.POST.get('active', 'off')
data['week'] = request.POST.get('week', 'week not found')
data['month'] = request.POST.get('month', 'month not found')
return render(request, 'core/index.html', data)
def django_form(request):
form = NameForm(request.POST or None)
name = ''
birth_year = ''
favorite_colors = ''
if request.method == 'POST':
if form.is_valid():
name = form.cleaned_data['name']
birth_year = form.cleaned_data['birth_year']
favorite_colors = form.cleaned_data['favorite_colors']
import pdb; pdb.set_trace()
return render(request, 'core/django-form.html', {'form': form, 'name': name}) | djangomoc/formularios | core/views.py | views.py | py | 927 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "django.shortcuts.render",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "core.forms.NameForm",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "pdb.set_trace",
"line_number": 29,
"usage_type": "call"
},
{
"api_name": "django.shor... |
9324774880 | import csv, re, os
from typing import List, Dict, Tuple
from cProfile import Profile
from pstats import Stats
from vacancy import InputConnect
from statistic import Report, get_statistic, get_salary_level, get_count_vacancies, print_statistic
from Task322 import get_stat_by_year
prof = Profile()
prof.disable()
class DataSet:
"""
Класс для формирования списка вакансий.
Attributes:
file_name (str): Название файла.
vacancies_objects (List[Vacancy]): Сформированный список вакансий.
"""
def __init__(self, file_name: str) -> None:
"""
Инициализирует объект DataSet.
Args:
file_name (str): Имя файла.
"""
self.file_name = file_name
self.vacancies_objects = [Vacancy(vac) for vac in self.csv_filer(*self.csv_reader(file_name))]
def clean_string(self, raw_html: str) -> str:
"""
Очищает строку от HTML кода
Args:
raw_html (str): Строка, которую нужно очистить
Returns:
str: Очищенная строка.
>>> DataSet('vacancies.csv').clean_string('<p>Группа компаний «МИАКОМ»</p>')
'Группа компаний «МИАКОМ»'
"""
result = re.sub("<.*?>", '', raw_html)
return result if '\n' in raw_html else " ".join(result.split())
def csv_reader(self, file_name: str) -> Tuple[List[str], List[List[str]]]:
"""
Считывает данные из файла
Args:
file_name (str): Название файла.
Returns:
Tuple[List[str], List[List[str]]]: Название колонок и соответствующие им данные по каждой вакансии.
"""
reader = csv.reader(open(file_name, encoding='utf_8_sig'))
data_base = [line for line in reader]
return data_base[0], data_base[1:]
def csv_filer(self, list_naming: List[str], reader: List[List[str]]) -> List[Dict[str, str]]:
"""
Преобразует данные в список словарей, где словарь содержит информацию об одной вакансии.
Args:
list_naming (List[str]): Поля вакансии
reader (List[List[str]]): Данные из файла
Returns:
List[Dict[str, str]]: Список словарей.
"""
new_vacans_list = list(filter(lambda vac: (len(vac) == len(list_naming) and vac.count('') == 0), reader))
return [dict(zip(list_naming, map(self.clean_string, vac))) for vac in new_vacans_list]
class Vacancy:
"""
Класс для представления вакансии
Attributes:
name (string): Название вакансии
description (str): Описание вакансии
key_skills (List[str]): Ключевые навыки для вакансии
experience_id (str): Требуемый опят для вакансии
premium (str): Атрибут, отвечающий за премиальность вакансии
employer_name (str): Название компании, где есть вакансия
salary (Salary): Информация о зарплате
area_name (str): Название города
published_at (str): Дата публикации вакансии
"""
def __init__(self, dict_vac: Dict[str, str]):
"""
Инициализирует объект Vacancy, проверяя наличие некоторых полей для вакансии
Args: dict_vac (Dict[str, str]): Словарь, хранящий информацию о вакансии. Ключи - это названия полей,
значения - информация о вакансии по соответствующему полю.
"""
self.name = dict_vac['name']
self.description = 'Нет данных' if 'description' not in dict_vac.keys() else dict_vac['description']
self.key_skills = 'Нет данных' if 'key_skills' not in dict_vac.keys() else dict_vac['key_skills'].split('\n')
self.experience_id = 'Нет данных' if 'experience_id' not in dict_vac.keys() else dict_vac['experience_id']
self.premium = 'Нет данных' if 'premium' not in dict_vac.keys() else dict_vac['premium']
self.employer_name = 'Нет данных' if 'employer_name' not in dict_vac.keys() else dict_vac['employer_name']
salary_gross = 'Нет данных' if 'salary_gross' not in dict_vac.keys() else dict_vac['salary_gross']
self.salary = Salary(dict_vac['salary_from'], dict_vac['salary_to'], salary_gross, dict_vac['salary_currency'])
self.area_name = dict_vac['area_name']
self.published_at = dict_vac['published_at']
class Salary:
"""
Класс для представления зарплаты.
Attributes:
salary_from (str): Нижняя граница зарплаты
salary_to (str): Верхняя граница зарплаты
salary_gross (str): Наличие налогов
salary_currency (str): Валюта оклада
"""
def __init__(self, salary_from, salary_to, salary_gross, salary_currency):
"""
Инициализирует объект Salary
Args:
salary_from (str): Нижняя граница зарплаты
salary_to (str): Верхняя граница зарплаты
salary_gross (str): Наличие налогов
salary_currency (str): Валюта оклада
"""
self.salary_from = salary_from
self.salary_to = salary_to
self.salary_gross = salary_gross
self.salary_currency = salary_currency
def to_RUB(self, salary: float) -> float:
"""
Вычисляет зарплату в рублях, при помощи словаря - currency_to_rub.
Args:
salary (float): Зарплата в другой валюте.
Returns:
float: Зарплата в рублях.
# >>> Salary('10', '1000', 'true', 'EUR').to_RUB(1000.0)
# 59900.0
# >>> Salary('10', '1000', 'true', 'RUR').to_RUB(1000)
# 1000.0
# >>> Salary('10', '1000', 'true', 'QWE').to_RUB(1000.0)
>>> Salary('10', '1000', 'false', 'EUR').to_RUB(559)
33484.1
>>> Salary('10', '1000', 'true', 'RUR').to_RUB(500)
500.0
>>> Salary('10', '1000', 'true', 'QWE').to_RUB(1000.0)
Traceback (most recent call last):
...
KeyError: 'QWE'
"""
return float(salary * currency_to_rub[self.salary_currency])
currency_to_rub = {"AZN": 35.68,
"BYR": 23.91,
"EUR": 59.90,
"GEL": 21.74,
"KGS": 0.76,
"KZT": 0.13,
"RUR": 1,
"UAH": 1.64,
"USD": 60.66,
"UZS": 0.0055, }
translation = {"name": "Название",
"description": "Описание",
"key_skills": "Навыки",
"experience_id": "Опыт работы",
"premium": "Премиум-вакансия",
"employer_name": "Компания",
"salary_from": "Нижняя граница вилки оклада",
"salary_to": "Верхняя граница вилки оклада",
"salary_gross": "Оклад указан до вычета налогов",
"salary_currency": "Идентификатор валюты оклада",
"area_name": "Название региона",
"published_at": "Дата публикации вакансии",
"Оклад": "Оклад",
"Нет данных": "Нет данных",
"True": "Да",
"TRUE": "Да",
"False": "Нет",
"FALSE": "Нет",
"noExperience": "Нет опыта",
"between1And3": "От 1 года до 3 лет",
"between3And6": "От 3 до 6 лет",
"moreThan6": "Более 6 лет",
"AZN": "Манаты",
"BYR": "Белорусские рубли",
"EUR": "Евро",
"GEL": "Грузинский лари",
"KGS": "Киргизский сом",
"KZT": "Тенге",
"RUR": "Рубли",
"UAH": "Гривны",
"USD": "Доллары",
"UZS": "Узбекский сум"}
reverse_translation = {"Название": "name",
"Описание": "description",
"Навыки": "key_skills",
"Опыт работы": "experience_id",
"Премиум-вакансия": "premium",
"Компания": "employer_name",
"Оклад": "Оклад",
"Название региона": "area_name",
"Дата публикации вакансии": "published_at",
"Идентификатор валюты оклада": "salary_currency"}
rang_experience_id = {"noExperience": 0,
"between1And3": 1,
"between3And6": 2,
"moreThan6": 3}
def get_year(date_vac) -> str:
"""
Возвращает год от даты.
Args:
date_vac (str): Дата публикации.
Returns:
str: Год публикации.
"""
return date_vac[:4]
def exit_from_file(message: str):
"""
Метод для выхода из программы.
Args:
message (str): Сообщение при выходе из программы
"""
print(message)
exit()
if __name__ == '__main__':
type_output = input('Введите данные для печати: ')
file_name = input('Введите название файла: ')
if os.stat(file_name).st_size == 0:
exit_from_file('Пустой файл')
prof.enable()
data = DataSet(file_name)
prof.disable()
if len(data.vacancies_objects) == 0:
exit_from_file('Нет данных')
if type_output == 'Статистика':
vacancy_name = input('Введите название профессии: ')
prof.enable()
for vac in data.vacancies_objects:
vac.published_at = get_year(vac.published_at)
dict_cities = {}
for vac in data.vacancies_objects:
if vac.area_name not in dict_cities.keys():
dict_cities[vac.area_name] = 0
dict_cities[vac.area_name] += 1
needed_vacancies_objects = list(
filter(lambda vac: int(len(data.vacancies_objects) * 0.01) <= dict_cities[vac.area_name],
data.vacancies_objects))
rp = Report()
stat_by_years = get_stat_by_year(file_name, vacancy_name)
print('Динамика уровня зарплат по годам:', stat_by_years[0])
print('Динамика уровня зарплат по годам для выбранной профессии:', stat_by_years[1])
print('Динамика количества вакансий по годам:', stat_by_years[2])
print('Динамика количества вакансий по годам для выбранной профессии:', stat_by_years[3])
list_statistic = [stat_by_years[0],
stat_by_years[1],
stat_by_years[2],
stat_by_years[3],
print_statistic(get_salary_level(needed_vacancies_objects, 'area_name').items(), 1,
'Уровень зарплат по городам (в порядке убывания): ', True, 10),
print_statistic(get_count_vacancies(needed_vacancies_objects, 'area_name', data).items(), 1,
'Доля вакансий по городам (в порядке убывания): ', True, 10)]
rp.generate_excel(vacancy_name, list_statistic)
rp.generate_image(vacancy_name, list_statistic)
rp.generate_pdf(vacancy_name)
prof.disable()
elif type_output == 'Вакансии':
parameter = input('Введите параметр фильтрации: ')
sorting_param = input('Введите параметр сортировки: ')
is_reversed_sort = input('Обратный порядок сортировки (Да / Нет): ')
interval = list(map(int, input('Введите диапазон вывода: ').split()))
columns = input('Введите требуемые столбцы: ')
prof.enable()
outer = InputConnect(parameter, sorting_param, is_reversed_sort, interval, columns)
outer.check_parameters()
outer.print_vacancies(data.vacancies_objects)
prof.disable()
prof.dump_stats('async')
with open('async_stats.txt', 'wt') as _output:
stats = Stats('async', stream=_output)
stats.sort_stats('cumulative', 'time')
stats.print_stats()
| Elenaz441/Zasypkina | main.py | main.py | py | 13,812 | python | ru | code | 0 | github-code | 1 | [
{
"api_name": "cProfile.Profile",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "re.sub",
"line_number": 46,
"usage_type": "call"
},
{
"api_name": "csv.reader",
"line_number": 59,
"usage_type": "call"
},
{
"api_name": "typing.Tuple",
"line_number": 4... |
16988584968 | import scipy.io as sio
import numpy as np
import matplotlib.pyplot as plt
def lsfit(data):
x = data[:,0]
y = data[:,1]
x_bar = np.mean(x)
y_bar = np.mean(y)
xy_bar = np.mean(x*y)
xx_bar = np.mean(x*x)
w1 = (xy_bar - y_bar*x_bar)/(xx_bar - x_bar*x_bar)
w0 = y_bar - w1*x_bar
loss = np.mean((y - w0 - w1*x)*(y - w0 - w1*x))
return w0, w1, loss
y = lambda x, w0, w1: w0 + w1*x
def lab1_scalar(data_m100, data_f100):
plt.figure(0)
plt.scatter(data_m100[:,0], data_m100[:,1], color='blue')
x = data_m100[:,0]
w0, w1, loss = lsfit(data_m100)
plt.plot(x,y(x,w0,w1), color='blue')
plt.hold(True)
plt.scatter(data_f100[:,0], data_f100[:,1], color='red')
x = data_f100[:,0]
w0, w1, loss = lsfit(data_f100)
plt.plot(x,y(x,w0,w1), color='red')
plt.legend(('Mens', 'Womens'))
plt.grid()
plt.title('Times on 100 meter sprint')
plt.xlabel('Year')
plt.ylabel('Time [s]')
plt.savefig('sprint100m.eps')
plt.figure(1)
x = np.linspace(2575, 2625, 20000)
w0, w1, loss = lsfit(data_m100)
y_m = y(x,w0,w1)
plt.plot(x, y_m, color='blue')
plt.hold(True)
w0, w1, loss = lsfit(data_f100)
y_f = y(x,w0,w1)
plt.plot(x, y_f, color='red')
idx = np.argwhere(np.diff(np.sign(y_m - y_f)) != 0).reshape(-1)
plt.scatter(x[idx], y(x,w0,w1)[idx], marker='x')
plt.text(x[idx]+3, y(x,w0,w1)[idx], 'Year: ' + str(round(float(x[idx]),2)))
plt.legend(('Mens', 'Womens'))
plt.grid()
plt.title('Intersection of times on 100 meter sprint')
plt.xlabel('Year')
plt.ylabel('Time [s]')
plt.savefig('sprint100m_intersection.eps')
size = lambda mat: (np.size(mat, 0), np.size(mat, 1))
inv = lambda mat: np.linalg.inv(mat)
def least_squares(data, poly_degree):
x = np.matrix([data[:,0]]).transpose()
t = np.matrix([data[:,1]]).transpose()
X = np.power(x, 0)
for i in range(1, poly_degree + 1):
X = np.concatenate((X, np.power(x, i)), axis=1)
X_T = X.transpose()
return np.asarray((inv(X_T * X) * X_T * t).transpose())[0]
def fitline(data, poly_degree):
coefficients = least_squares(data, poly_degree)
x = data[:,0]
y = [0] * len(x) #Preallocation
for i in range(0, len(coefficients)):
for j in range(0, len(x)):
y[j] += coefficients[i] * np.power(x[j], i)
return x, y
def compute_loocv(data, poly_degree): #Leave-one-out cross validation
err = 0
for i in range(0, data.shape[0]):
data_row_removed = np.delete(data, i, 0) #remove i-th element
y_test = data_row_removed[:,1]
_, y_fitline = fitline(data_row_removed, poly_degree)
err += (y_test - y_fitline) * (y_test - y_fitline)
err = np.mean(err)
return err
def lab1_vector(data_m100, data_f100):
[x, y] = fitline(data_f100, 2)
plt.figure(0)
plt.scatter(data_f100[:,0], data_f100[:,1])
plt.plot(x,y)
plt.grid()
poly_err = []
NUM_POLINOMIALS = 10
for i in range(1, NUM_POLINOMIALS + 1):
poly_err.append(compute_loocv(data_f100, i))
plt.figure(1)
plt.plot(np.arange(NUM_POLINOMIALS), poly_err)
print(np.arange(NUM_POLINOMIALS))
print(poly_err)
plt.show()
def main():
data = sio.loadmat('olympics.mat')
data_m100 = data['male100']
data_f100 = data['female100']
data_m200 = data['male200']
data_f200 = data['female200']
data_m400 = data['male400']
data_f400 = data['female400']
#lab1_scalar(data_m100, data_f100)
lab1_vector(data_m400, data_f400)
#a = np.matrix('1 2; 3 4') * np.matrix('1; 2')
#print(a)
main() | cartfjord/ASI | Lab1/lab1.py | lab1.py | py | 3,700 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "numpy.mean",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "numpy.mean",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "numpy.mean",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "numpy.mean",
"line_number": 11,
... |
36937439358 | import pprint
import sys
from os import path
import yaml
def to_upper(oldList):
newList = []
for element in oldList:
newList.append(element.upper())
return newList
def find_key(input_dict, target):
solutions = []
for key, value in input_dict.items():
for i in to_upper(value):
if i in target.upper():
solutions.append(key)
return solutions
def read_yml_as_dict(file_path: str):
if path.isfile(file_path):
f = open(file_path, "r")
input = f.read()
f.close()
try:
output = yaml.safe_load(input)
except Exception as e:
print(str(e))
sys.exit(1)
return output
if __name__=='__main__':
categories = read_yml_as_dict('./categories.yml')
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(categories)
print("\n --------------------------- \n")
print(f'test1 = {find_key(categories, "Amazoncom611WF3KX3 Amzncombill WA")}')
| richardphi1618/personal_finances | test/match_key.py | match_key.py | py | 999 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "os.path.isfile",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 24,
"usage_type": "name"
},
{
"api_name": "yaml.safe_load",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "sys.exit",
"line_number": 3... |
41405496993 | from http import HTTPStatus
from typing import Any
from fastapi import APIRouter, Depends, Request
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi_restful.cbv import cbv
from pydantic.schema import UUID
from src.api.response_models.error import generate_error_responses
from src.api.response_models.report import ReportResponse, ReportSummaryResponse
from src.core.db.models import Report
from src.core.services.authentication_service import AuthenticationService
from src.core.services.report_service import ReportService
from src.core.services.shift_service import ShiftService
router = APIRouter(prefix="/reports", tags=["Report"])
@cbv(router)
class ReportsCBV:
authentication_service: AuthenticationService = Depends()
token: HTTPAuthorizationCredentials = Depends(HTTPBearer())
shift_service: ShiftService = Depends()
report_service: ReportService = Depends()
@router.get(
"/{report_id}",
response_model=ReportResponse,
response_model_exclude_none=True,
status_code=HTTPStatus.OK,
summary="Получить информацию об отчёте участника.",
response_description="Полная информация об отчёте участника.",
responses=generate_error_responses(HTTPStatus.NOT_FOUND),
)
async def get_user_report(
self,
report_id: UUID,
) -> ReportResponse:
"""
Возвращает отчет участника.
- **user_id**:номер участника
- **report_id**: номер задачи, назначенной участнику на день смены (генерируется рандомно при старте смены)
- **task_id**: номер задачи
- **task_date**: дата получения задания
- **status**: статус задачи
- **photo_url**: url фото выполненной задачи
"""
await self.authentication_service.check_administrator_by_token(self.token)
return await self.report_service.get_report(report_id)
@router.patch(
"/{report_id}/approve",
status_code=HTTPStatus.OK,
summary="Принять задание. Будет начислен 1 \"ломбарьерчик\".",
response_model=ReportResponse,
responses=generate_error_responses(HTTPStatus.NOT_FOUND, HTTPStatus.BAD_REQUEST),
)
async def approve_task_status(
self,
report_id: UUID,
request: Request,
) -> ReportResponse:
"""Отчет участника проверен и принят."""
administrator = await self.authentication_service.get_current_active_administrator(self.token.credentials)
return await self.report_service.approve_report(report_id, administrator.id, request.app.state.bot_instance)
@router.patch(
"/{report_id}/decline",
status_code=HTTPStatus.OK,
summary="Отклонить задание.",
response_model=ReportResponse,
responses=generate_error_responses(HTTPStatus.NOT_FOUND, HTTPStatus.BAD_REQUEST),
)
async def decline_task_status(
self,
report_id: UUID,
request: Request,
) -> ReportResponse:
"""Отчет участника проверен и отклонен."""
administrator = await self.authentication_service.get_current_active_administrator(self.token.credentials)
return await self.report_service.decline_report(report_id, administrator.id, request.app.state.bot_instance)
@router.get(
"/",
response_model=list[ReportSummaryResponse],
summary="Получения списка заданий пользователя по полям status и shift_id.",
responses=generate_error_responses(HTTPStatus.NOT_FOUND),
)
async def get_report_summary(
self,
shift_id: UUID,
status: Report.Status = None,
) -> Any:
"""
Получения списка задач на проверку с возможностью фильтрации по полям status и shift_id.
Список формируется по убыванию поля started_at.
В запросе передаётся:
- **shift_id**: уникальный id смены, ожидается в формате UUID.uuid4
- **report.status**: статус задачи
"""
await self.authentication_service.check_administrator_by_token(self.token)
return await self.report_service.get_summaries_of_reports(shift_id, status)
| Studio-Yandex-Practicum/lomaya_baryery_backend | src/api/routers/report.py | report.py | py | 4,802 | python | ru | code | 26 | github-code | 1 | [
{
"api_name": "fastapi.APIRouter",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "src.core.services.authentication_service.AuthenticationService",
"line_number": 21,
"usage_type": "name"
},
{
"api_name": "fastapi.Depends",
"line_number": 21,
"usage_type": "call... |
74395034273 | from mlfromscratch.supervised.random_forest import Random_forest
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
def test():
iris = load_iris()
X = iris['data']
y = iris['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
# custom implementation
rf = Random_forest()
rf.fit(X_train,y_train)
y_pred = rf.predict(X_test)
accuracy = (y_test == y_pred).sum()/y_test.shape[0]
# sklearn implementation
rf_sklearn = RandomForestClassifier(n_estimators=10, criterion="entropy", random_state=0)
rf_sklearn.fit(X_train,y_train)
y_pred_sklearn = rf_sklearn.predict(X_test)
accuracy_sklearn = (y_test == y_pred_sklearn).sum()/y_test.shape[0]
# test
np.testing.assert_allclose(accuracy, accuracy_sklearn)
if __name__ == '__main__':
test()
| harjotsodhi/ML-from-scratch | mlfromscratch/testing/test_random_forest.py | test_random_forest.py | py | 965 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "sklearn.datasets.load_iris",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "sklearn.model_selection.train_test_split",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "mlfromscratch.supervised.random_forest.Random_forest",
"line_number": 15,
... |
33682119543 | """
28.06.23
@tcnicholas
Utility functions.
"""
import re
from typing import Tuple, List
import numpy as np
from numba import njit
def round_maxr(max_r: float, bin_width: float) -> float:
"""
Round the max_r value by flooring to a multiple of the bin_width.
:param max_r: maximum value of r.
:param bin_width: width of the bins.
:return: rounded max_r.
"""
# get the number of decimal points to round to.
try:
rv = len(str(bin_width).split(".")[-1])
except:
rv = 0
top_bin = bin_width * np.round(max_r / bin_width)
if top_bin > max_r:
top_bin -= bin_width
return np.round(top_bin, rv)
@njit
def unit_vector(v: np.ndarray(3)) -> np.ndarray(3):
"""
Transform 1x3 vector to a unit vector.
:param v: vector.
:return: unit vector.
"""
return v / np.sqrt(np.sum(np.square(v)))
@njit
def random_vector(rand1: float, rand2: float) -> np.ndarray(3):
"""
Generate random vector.
:param rand1: random number 1.
:param rand2: random number 2.
:return: random vector.
"""
# Generate two random variables.
phi = rand1 * 2 * np.pi
z = rand2 * 2 - 1
# Determine final unit vector.
z2 = z * z
x = np.sqrt(1 - z2) * np.sin(phi)
y = np.sqrt(1 - z2) * np.cos(phi)
return unit_vector(np.array([x,y,z]))
def eps2H(eps: float, sigma: float) -> float:
"""
The epsilon prefactor for the Gaussian potential in LAMMPS is defined as
\epsilon = \frac{H}{\sigma_h \sqrt{2\pi}}
where H determines--together with the standard deviation \sigma_h--the
peak height of the Guassian function. As such, given we have fit this to
epsilon, we need to compute H.
:param eps: epsilon.
:param sigma: sigma.
:return: H.
"""
# guass params: eps, r0, sigma
return -eps * np.sqrt(2*np.pi) * sigma
def extract_headers_and_index(line: str) -> Tuple[List[str], int]:
headers = re.split(r'\s+', re.sub(',', '', line.strip()))
if '|' not in headers:
raise ValueError("The log file does not contain a '|' symbol.")
ix = headers.index('|')
headers.remove('|')
return headers, ix
def handle_data_line(line: str, ix: int) -> List[float]:
try:
line_values = re.split(r'\s+', line.strip())
return [np.nan if v == '-' else float(v) for v in (
line_values[:ix] + line_values[ix+1:]
)]
except ValueError:
return []
def load_mc_ljg_log(filename: str) -> Tuple[List[str], np.ndarray]:
"""
Parse the log file output from LJG simulator Monte Carlo simulations and
return simulation headers and the corresponding data.
:param filename: The path to the log file.
:return: A tuple containing list of headers in the log file and the data.
"""
headers, data, ix = [], [], None
try:
with open(filename, 'r') as file:
for line in file:
stripped_line = line.strip()
if not stripped_line:
continue
if stripped_line.startswith('Tracking simulation progress:'):
headers, ix = extract_headers_and_index(file.readline())
file.readline() # skip one line
elif ix is not None:
data_line = handle_data_line(line, ix)
if data_line:
data.append(data_line)
else:
break
except FileNotFoundError:
raise FileNotFoundError(f"The file {filename} does not exist.")
except ValueError as ve:
raise ValueError(f"Error while reading the file: {ve}")
return {'headers': headers, 'data': np.array(data, dtype=float)}
| tcnicholas/amorphous-calcium-carbonate | ljg_simulator/utils.py | utils.py | py | 3,772 | python | en | code | 4 | github-code | 1 | [
{
"api_name": "numpy.round",
"line_number": 29,
"usage_type": "call"
},
{
"api_name": "numpy.round",
"line_number": 33,
"usage_type": "call"
},
{
"api_name": "numpy.ndarray",
"line_number": 37,
"usage_type": "call"
},
{
"api_name": "numpy.sqrt",
"line_number":... |
71112237794 | from AIPUBuilder.Optimizer.utils import *
from AIPUBuilder.Optimizer.framework import *
from AIPUBuilder.Optimizer.ops.activation import apply_with_activation, with_activation_out_is_signed, apply_with_activation_quantize, with_activation_allow_merge_out_zerop_to_bias
from AIPUBuilder.Optimizer.logger import *
from AIPUBuilder.Optimizer.ops.convwinograd import *
import torch
import math
import importlib
def _conv2d_torch_impl(self, *args):
inp = self.inputs[0].betensor.float()
weights = self.constants['weights'].betensor.clone().float()
bias = self.constants['biases'].betensor.clone().float()
stride = (self.get_param("stride_y"), self.get_param("stride_x"))
dilation = (self.get_param('dilation_y'), self.get_param('dilation_x'))
padding = (self.get_param('pad_left'), self.get_param('pad_right'),
self.get_param('pad_top'), self.get_param('pad_bottom'))
group = self.get_param('group')
pad_val = 0
if self.quantized:
# input's zerop has been absorbed to bias.
# inp += self.inputs[0].zerop
inp_zp = self.inputs[0].zerop if isinstance(self.inputs[0].zerop, (float, int)) else self.inputs[0].zerop[0]
pad_val = -inp_zp
w_zp = self.constants["weights"].zerop
w_zshape = [1] * weights.dim()
w_zshape[0] = -1
weights += w_zp.reshape(w_zshape) if isinstance(w_zp, torch.Tensor) else w_zp
bias += self.constants['biases'].zerop
inp = nhwc2nchw(inp)
weights = nhwc2nchw(weights)
if WinogradChecker.run(self) or self.get_param('with_winograd', optional=True, default_value=False):
x = WinogradAllocator(self, inp, weights, bias)
else:
inp = torch.nn.functional.pad(inp, padding, value=pad_val)
x = torch.nn.functional.conv2d(inp,
weights,
bias,
stride=stride,
padding=0,
dilation=dilation,
groups=group)
x = nchw2nhwc(x)
return x
@op_register(OpType.Convolution)
def conv2d(self, *args):
in_shape = self.inputs[0].shape
ih, iw = in_shape[1], in_shape[2]
ky = self.get_param('kernel_y')
kx = self.get_param('kernel_x')
if not torch.cuda.is_available() and (ih >= 2048 and iw >= 2048) and (ky == 1 and kx == 1):
OPT_DEBUG(f"when ih>=2048, iw>=2048 and ky==1, kw==1 with cpu device forward, we will use tf.nn.conv2d to execute.")
conv2d_tf = importlib.import_module('AIPUBuilder.Optimizer.ops.tf_ops.conv2d')
x = conv2d_tf.conv2d_tf_impl(self, *args)
else:
x = _conv2d_torch_impl(self, *args)
requant_scale = 1
requant_shift = 0
if self.quantized:
if 'scale_value' in self.params:
requant_scale = self.params['scale_value']
elif "scale" in self.constants:
requant_scale = self.constants["scale"].betensor
if 'shift_value' in self.params:
requant_shift = self.params['shift_value']
elif "shift" in self.constants:
requant_shift = self.constants["shift"].betensor
x = apply_with_activation(self,
x,
self.inputs[0].scale * self.constants["weights"].scale,
0,
requant_scale,
requant_shift,
*args)
self.outputs[0].betensor = x
return self.outputs[0].betensor
@quant_register(OpType.Convolution)
def conv2d_quantize(self, *args):
if WinogradChecker.run(self):
self.constants["weights"] = self.constants['WinogradWeights']
linear_op_quantize(self, *args)
self.constants.pop('WinogradWeights')
if self.get_param('with_winograd', optional=True, default_value=False):
self.attrs.update({'optimization_info': {'with_winograd': True}})
else:
linear_op_quantize(self, *args)
absorb_input_zp_to_bias_and_compress_bias_for_aiff(self, *args)
def linear_op_quantize(self, *args):
q_mode_bias = self.attrs["q_mode_bias"]
q_mode_weight = self.attrs["q_mode_weight"]
q_mode_activation = self.attrs["q_mode_activation"]
if q_mode_weight != q_mode_bias:
OPT_FATAL("Currently quantization mode of weight (q_mode_weight) and bias (q_mode_bias) must be the same!")
if QuantMode.is_per_channel(q_mode_activation) == True:
OPT_FATAL("Currently not support per-channel quantization of activations")
q_bits_weight = self.attrs["q_bits_weight"]
q_bits_bias = self.attrs["q_bits_bias"]
q_bits_activation = self.attrs["q_bits_activation"]
multiplier_bits = self.attrs['multiplier_bits']
inp = self.inputs[0]
w = self.constants["weights"]
key_axis = w.key_axis
w_out_cnum = w.shape[key_axis]
w_scale_expand = []
w_zerop_expand = []
group = self.get_param('group', optional=True, default_value=1)
out = self.outputs[0]
out_signed = with_activation_out_is_signed(self) or self.force_dtype_int
out.qbits = q_bits_activation
out.scale, out.zerop, out.qmin, out.qmax, out.dtype = get_linear_quant_params_from_tensor(
out, q_mode_activation, q_bits_activation, is_signed=out_signed)
out.qinvariant = False
if group > 1 or QuantMode.is_per_channel(q_mode_weight):
if QuantMode.is_per_channel(q_mode_weight):
mgroup = w_out_cnum
else:
mgroup = group
do_scale, do_scale_type, do_shift, do_shift_type = unify_shifts_for_aiff_with_per_n_channel_quant(
self, w, q_mode_weight, q_bits_weight, True, lambda xt: out.scale / (inp.scale * xt.scale), initial_group=mgroup)
w_scale_expand = w.scale
w_zerop_expand = w.zerop
self.constants["scale"] = PyTensor(self.name+"/scale",
do_scale.cpu().numpy().astype(dtype2nptype(do_scale_type)))
self.constants["scale"].dtype = do_scale_type
self.constants["shift"] = PyTensor(self.name+"/shift",
do_shift.cpu().numpy().astype(dtype2nptype(do_shift_type)))
self.constants["shift"].dtype = do_shift_type
else:
w.scale, w.zerop, w.qmin, w.qmax, w.dtype = get_linear_quant_params_from_tensor(w, q_mode_weight, q_bits_weight,
is_signed=True)
local_rescale = out.scale / (inp.scale * w.scale)
do_scale, do_scale_type, do_shift, do_shift_type = get_scale_approximation_params(local_rescale,
mult_bits=multiplier_bits,
force_shift_positive=self.force_shift_positive)
w_scale_expand.extend([w.scale] * w_out_cnum)
w_zerop_expand.extend([w.zerop] * w_out_cnum)
_, do_scale_type = range2dtype(0, do_scale)
self.params["shift_value"] = int(do_shift)
self.params["shift_type"] = do_shift_type
self.params["scale_value"] = int(do_scale)
self.params["scale_type"] = do_scale_type
# quantize weights
if not isinstance(w_scale_expand, torch.Tensor):
w_scale_expand = torch.tensor(w_scale_expand, device=inp.betensor.device)
w_zerop_expand = torch.tensor(w_zerop_expand, device=inp.betensor.device)
scale_zp_shape = [w.shape[ax] if ax == key_axis else 1 for ax in range(len(w.shape))]
w.betensor = linear_quantize_clip(w.betensor, w_scale_expand.reshape(scale_zp_shape),
w_zerop_expand.reshape(scale_zp_shape), w.qmin, w.qmax)
w.qbits = q_bits_weight
w.qinvariant = False
if 'biases' in self.constants:
b = self.constants["biases"]
# if self.get_param('with_activation', optional=True, default_value='none').lower() in with_activation_allow_merge_out_zerop_to_bias :
# #y_q = ((w_q + zp_w) (x_q + zp_x) + (b_q + zp_b)s_ws_x/s_b) s_y/s_ws_x - zp_y
# #y_q = ((w_q + zp_w) (x_q + zp_x) + (b_f - zp_y/s_y)s_ws_x) s_y/s_ws_x
# b.betensor = b.betensor - linear_dequantize(0, out.scale, out.zerop)
b.scale = inp.scale * w.scale
b.zerop = 0
if isinstance(b.scale, torch.Tensor):
b_scale_shape = [b.shape[ax] if ax == b.key_axis else 1 for ax in range(len(b.shape))]
b.scale = torch.reshape(b.scale, b_scale_shape)
if self.attrs['bias_effective_bits'] != q_bits_bias:
search_bias_bit_and_quantize(self, *args)
else:
b.qmin = -2 ** (q_bits_bias - 1)
b.qmax = 2 ** (q_bits_bias - 1) - 1
b.qbits = q_bits_bias
b.betensor = linear_quantize_clip(b.betensor, b.scale, b.zerop, b.qmin, b.qmax)
b.dtype = bits2dtype(b.qbits, is_signed=True)
b.qinvariant = False
apply_with_activation_quantize(self, out.qinvariant, *args)
def clear_lower_bits_for_bias(self, *args, grouped=False, dim=-1):
# AIFF will scale down biases to 16bit and rescale it back to 32bit later due to hardware restricts
b = self.constants["biases"]
lmin, lmax = bits2range(self.attrs['bias_effective_bits'], is_signed=True)
if not grouped:
bmin = min(b.betensor.min().item(), -1)
bmax = max(b.betensor.max().item(), 1)
lbits = math.ceil(max(math.log2(bmax/lmax), math.log2(bmin/lmin)))
if lbits > 0:
b.betensor = ((b.betensor.long() >> lbits) << lbits).float()
else:
bmin = torch.min(b.betensor, dim=dim)[0]
bmax = torch.max(b.betensor, dim=dim)[0]
lbits = torch.ceil(torch.maximum(torch.log2(bmax / lmax), torch.log2(bmin / lmin))).long().unsqueeze(dim)
b.betensor = ((b.betensor.long() >> lbits) << lbits).float()
def compute_input_zp_mul_reduce_weight(zp, w):
return w.reshape(w.shape[0], -1).sum(dim=1) * zp
def absorb_input_zp_to_bias(self, *args):
w = self.constants["weights"]
b = self.constants["biases"]
if self.get_attrs('is_winograd_checker_passed', optional=True, default_value=False):
device = w.betensor.device
BT, _, AT = ArcReactor.run(2, 3)
BT = torch.from_numpy(BT).to(device)
AT = torch.from_numpy(AT).to(device)
input_zp = construct_torch_tensor(self.inputs[0].zerop, device)
weight = w.betensor.permute(0, 3, 1, 2)
repeated_input_zp = input_zp.repeat([1, BT.shape[0]])
data_tmp = torch.matmul(repeated_input_zp.float(), BT.permute(1, 0))
data_repeat_shape = [*weight.shape[0:3]] + [1]
BT_out = data_tmp.repeat(data_repeat_shape)
BT_out = BT_out * weight
AT_out = torch.matmul(BT_out, AT.permute(1, 0))
input_zp_mul_weight = AT_out.sum(dim=[1, 2])[:, 0]
else:
input_zp_mul_weight = compute_input_zp_mul_reduce_weight(self.inputs[0].zerop, w.betensor)
input_zp_mul_weight = input_zp_mul_weight.item() if b.ir_shape == TensorShape([]) else input_zp_mul_weight
b.betensor += input_zp_mul_weight
b.betensor = b.betensor.clamp(b.qmin, b.qmax)
def absorb_input_zp_to_bias_and_compress_bias_for_aiff(self, *args):
absorb_input_zp_to_bias(self, *args)
clear_lower_bits_for_bias(self, *args)
def search_bias_bit_and_quantize(self, *args):
b = self.constants['biases']
q_bits_bias = self.attrs["q_bits_bias"]
bias_effective_bits = self.attrs['bias_effective_bits']
if bias_effective_bits > q_bits_bias:
OPT_WARN(f"layer_id = {self.attrs['layer_id']}, layer_type = {self.type}, layer_name = {self.name}",
f"the bias_effective_bits(={bias_effective_bits}) > bias_bits(={q_bits_bias}), "
f"we clip bias_effective_bits to bias_bits.")
bias_effective_bits = q_bits_bias
self.attrs['bias_effective_bits'] = bias_effective_bits
bias_float_data = b.betensor.clone()
b.qmin = -2 ** (q_bits_bias - 1)
b.qmax = 2 ** (q_bits_bias - 1) - 1
b.qbits = q_bits_bias
b.betensor = linear_quantize_clip(b.betensor, b.scale, b.zerop, b.qmin, b.qmax)
q_bias_data = b.betensor.clone()
clear_lower_bits_for_bias(self)
compressed_q_bias_data = b.betensor
float_softmax = bias_float_data.clone().softmax(dim=-1)
quantize_log_softmax = q_bias_data.log_softmax(dim=-1)
compress_log_softmax = compressed_q_bias_data.log_softmax(dim=-1)
float_quant_kld = torch.nn.functional.kl_div(quantize_log_softmax, float_softmax, reduction='batchmean')
float_compress_kld = torch.nn.functional.kl_div(compress_log_softmax, float_softmax, reduction='batchmean')
if (float_quant_kld - float_compress_kld).abs() > 0.05:
begin_bits = min(max(bias_effective_bits, 19), q_bits_bias - 1)
end_bits = q_bits_bias
bits = torch.arange(begin_bits, end_bits, device=b.betensor.device)
repeated_bias = torch.tile(bias_float_data, tuple([end_bits - begin_bits] + [1 for _ in range(len(b.shape))]))
clamp_min = -2 ** (bits - 1)
clamp_max = 2 ** (bits - 1) - 1
q_biases = linear_quantize_clip(repeated_bias, construct_torch_tensor(b.scale, device=b.betensor.device).unsqueeze(0), b.zerop,
clamp_min.unsqueeze(-1), clamp_max.unsqueeze(-1))
b.betensor = q_biases.clone()
clear_lower_bits_for_bias(self, grouped=True)
compress_biases = b.betensor
q_softmax = linear_dequantize(q_biases, b.scale, b.zerop).softmax(dim=-1)
cq_log_softmax = linear_dequantize(compress_biases, b.scale, b.zerop).log_softmax(dim=-1)
klds = []
for i in range(end_bits - begin_bits):
kld = torch.nn.functional.kl_div(cq_log_softmax[i], q_softmax[i], reduction='batchmean').abs()
klds.append(kld.item())
searched_bias_bits = klds.index(min(klds)) + begin_bits
b.qmin = -2 ** (searched_bias_bits - 1)
b.qmax = 2 ** (searched_bias_bits - 1) - 1
b.qbits = searched_bias_bits
b.betensor = linear_quantize_clip(bias_float_data, b.scale, b.zerop, b.qmin, b.qmax)
OPT_DEBUG((f"layer_id = {self.attrs['layer_id']}, layer_type = {self.type}, layer_name = {self.name} "
f"searched bias bits = {searched_bias_bits} for better quantize bias "
f"to reduce the compression bias impact in AIFF"))
else:
b.betensor = q_bias_data
| Arm-China/Compass_Optimizer | AIPUBuilder/Optimizer/ops/conv.py | conv.py | py | 14,605 | python | en | code | 18 | github-code | 1 | [
{
"api_name": "torch.Tensor",
"line_number": 30,
"usage_type": "attribute"
},
{
"api_name": "torch.nn.functional.pad",
"line_number": 38,
"usage_type": "call"
},
{
"api_name": "torch.nn",
"line_number": 38,
"usage_type": "attribute"
},
{
"api_name": "torch.nn.func... |
19609459955 | import flask
import threading
import os
import slackeventsapi
import slackweb
import bedroomtv
import youtube
import surveillance
slack_signing_secret=os.environ.get('SLACK_SIGNING_SECRET')
approved_user_id=os.environ.get('APPROVED_USER_ID')
app=flask.Flask(__name__)
slack_events_adapter=slackeventsapi.SlackEventAdapter(slack_signing_secret, "/slack/events", app)
@slack_events_adapter.on('app_mention')
def app_mentioned(event_data):
text=event_data['event']['text'].lower()
channel_id=event_data['event']['channel']
user_id=event_data['event']['user']
if user_id != approved_user_id:
message='You\'re not allowed to do that :police_car:'
slackweb.post_message(channel_id, message)
elif 'picture' in text:
thread=threading.Thread(target=surveillance.send_image, args=[channel_id])
thread.start()
elif 'youtube' in text:
thread=threading.Thread(target=youtube.send_stats, args=[channel_id])
thread.start()
elif 'tv state' in text:
thread=threading.Thread(target=bedroomtv.send_state, args=[channel_id])
thread.start()
elif 'tv off' in text:
thread=threading.Thread(target=bedroomtv.turn_off, args=[channel_id])
thread.start()
elif 'tv on' in text:
thread=threading.Thread(target=bedroomtv.turn_on, args=[channel_id])
thread.start()
else:
message='Sorry, didn\'t understand that :confused:'
slackweb.post_message(channel_id, message)
if __name__ == '__main__':
app.run()
| kriscfoster/my_rpi_personal_assistant | my_rpi_personal_assistant/app.py | app.py | py | 1,456 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "os.environ.get",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "os.environ",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "os.environ.get",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "os.environ",
"line_... |
438838700 | from functools import reduce
import numpy as np
from scipy import optimize, linalg
from utils import *
import itertools
# === Configure ===
np.set_printoptions(precision=3, linewidth=120, suppress=True)
# === Constants ===
ineq_coeff = None
# === Memory Locations ===
mem_loc = [2, 2, 2, 2, 7]
ps_A1, ps_A2, ps_B1, ps_B2, ps_rho = gen_memory_slots(mem_loc)
def unpack_param(param):
p_A1 = param[ps_A1]
p_A2 = param[ps_A2]
p_B1 = param[ps_B1]
p_B2 = param[ps_B2]
p_rho = param[ps_rho]
return p_A1, p_A2, p_B1, p_B2, p_rho
def get_context(param):
p_A1, p_A2, p_B1, p_B2, p_rho = unpack_param(param)
A1 = get_meas_on_bloch_sphere(*p_A1)
A2 = get_meas_on_bloch_sphere(*p_A2)
B1 = get_meas_on_bloch_sphere(*p_B1)
B2 = get_meas_on_bloch_sphere(*p_B2)
if (len(p_rho) == 7):
# === Pure State (switch mem_loc to 7) ===
psi = get_two_qubit_state(p_rho)
rho = ket_to_dm(psi)
elif (len(p_rho) == 16):
# === Mixed State (switch mem loc to 16) ===
rho = get_psd_herm(p_rho, 4)
else:
raise Exception("Parameterization of state rho needs either 7 or 16 real numbers.")
return A1, A2, B1, B2, rho
def E(A_x, B_y, rho):
joint_measure = tensor(A_x, B_y)
E_AB_xy = np.trace(np.dot(rho, joint_measure))
# E_AB_xy.imag << 1
return E_AB_xy.real
def objective(param):
A1, A2, B1, B2, rho = get_context(param)
CHSH = E(A1, B1, rho) + E(A1, B2, rho) + E(A2, B1, rho) - E(A2, B2, rho)
obj = 2 - CHSH
return obj
def log_results(param):
print("=== Complete ===")
print("Results:")
objective_res = objective(param)
print("Objective Result", objective_res)
print("{0} = <A1, B1> + <A1, B2> + <A2, B1> - <A2, B2> <= 2".format(2 - objective_res))
print("Violation:", 2 - objective_res)
print("Theo Max Violation:", 2 * np.sqrt(2))
A1, A2, B1, B2, rho = get_context(param)
print("A1:")
print(A1)
print("A2:")
print(A2)
print("A1 * A2:")
# x = 1/2*(A1 + I2)
# y = 1/2*(A2 + I2)
print(np.dot(A1, A2))
print("B1:")
print(B1)
print("B2:")
print(B2)
print("B1 * B2:")
print(np.dot(B1, B2))
print("rho:")
print(rho)
def after_iterate(param):
objective_res = objective(param)
print("Step result:", objective_res)
def find_max_violation():
initial_guess = np.random.random((sum(mem_loc))) * -1
log_results(initial_guess)
print("=== Minimizing ===")
res = optimize.minimize(
fun = objective,
x0 = initial_guess,
callback = after_iterate,
)
log_results(res.x)
def main():
# x = get_meas_on_bloch_sphere(np.pi / 4, np.pi / 2)
# y = get_meas_on_bloch_sphere(np.pi / 4, 0)
# print(x)
# print(y)
# print(np.dot(x,y))
# return
a = get_psd_herm(np.arange(16), size=4)
print(a)
print(np.dot(a,a))
print(np.dot(a,a) - a)
return
find_max_violation()
if __name__ == '__main__':
main() | tcfraser/quantum_tools | archive/chsh_violation.py | chsh_violation.py | py | 3,101 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "numpy.set_printoptions",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "numpy.trace",
"line_number": 44,
"usage_type": "call"
},
{
"api_name": "numpy.dot",
"line_number": 44,
"usage_type": "call"
},
{
"api_name": "numpy.sqrt",
"line_nu... |
8478882949 | from bs4 import BeautifulSoup
from selenium import webdriver
import requests
import csv
browser = webdriver.Chrome()
URL = "https://search.shopping.naver.com/search/all?query=%EB%B0%80%ED%82%A4%ED%8A%B8%20%EB%96%A1%EB%B3%B6%EC%9D%B4&pagingIndex=1"
URLTEST = "https://search.shopping.naver.com/search/all?query=%EC%83%9D%EC%88%98&prevQuery=todtn"
response = requests.get(URL)
html = browser.page_source
soup = BeautifulSoup(html, "lxml")
element = soup.find("a", attrs={
"class": "product_link__TrAac linkAnchor", "data-testid": "SEARCH_PRODUCT"})
price = soup.find("span", attrs={"class": "price_num__S2p_v"})
file = open("/users/famelee/desktop/dataset.csv", "w")
writer = csv.writer(file)
# elementhref = element.get("href")
# elementList = (soup.find_all(
# "a", attrs={"class": "product_link__TrAac linkAnchor"}))
writer
# for elementList in elementList:
# print(elementList.get_text())
# print(price.get_text())
| setda1494/MyCode | Python/1-1/home/data crawling/MultipleProduct.py | MultipleProduct.py | py | 954 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "selenium.webdriver.Chrome",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "selenium.webdriver",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "requests.get",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "bs4.Beautiful... |
34641424745 | import re
import uuid
from django import template
from django.utils.safestring import mark_safe
from django.template.loader import get_template
from django.utils.translation import gettext as _
from dal_select2.widgets import Select2WidgetMixin
register = template.Library()
@register.inclusion_tag('selia/components/list.html', takes_context=True)
def list_component(context, template_name, item_list, empty_message):
context['template_name'] = template_name
context['item_list'] = item_list
context['empty_message'] = empty_message
return context
@register.inclusion_tag('selia/components/detail.html', takes_context=True)
def detail_component(context, detail_template, object):
context['detail_template'] = detail_template
context['object'] = object
return context
@register.inclusion_tag('selia/components/help.html', takes_context=True)
def help_component(context, help_template):
context['help_template'] = help_template
return context
@register.inclusion_tag('selia/components/update.html', takes_context=True)
def update_component(context, update_template, form):
context['update_template'] = update_template
context['form'] = form
return context
@register.inclusion_tag('selia/components/summary.html', takes_context=True)
def summary_component(context, summary_template, object):
context['summary_template'] = summary_template
context['object'] = object
return context
@register.inclusion_tag('selia/components/filter.html', takes_context=True)
def filter_component(context, template, forms):
context['template'] = template
context['forms'] = forms
return context
@register.inclusion_tag('selia/components/delete.html', takes_context=True)
def delete_component(context, object):
context['object'] = object
return context
@register.inclusion_tag('selia/components/viewer.html', takes_context=True)
def viewer_component(context, viewer_template, object):
context['viewer_template'] = viewer_template
context['object'] = object
return context
@register.inclusion_tag('selia/components/create.html', takes_context=True)
def create_component(context, create_template, form):
context['create_template'] = create_template
context['form'] = form
return context
@register.inclusion_tag('selia/components/create_wizard.html', takes_context=True)
def create_wizard(context, wizard):
context['wizard'] = wizard
return context
@register.inclusion_tag('selia/components/annotator.html', takes_context=True)
def annotator_component(context, annotator_template, item, annotation_list, mode):
context['annotator_template'] = annotator_template
context['annotation_list'] = annotation_list
context['item'] = item
context['mode'] = mode
return context
@register.simple_tag
def autocomplete_media():
extra_script = r'''
<script>
$(document).on('click', '.dropdown-menu .select2*', function(e) {
e.stopPropagation();
});
</script>
'''
media = '''
{select2_media}
{extra_script}
'''.format(
select2_media=Select2WidgetMixin().media,
extra_script=extra_script)
return mark_safe(media)
@register.inclusion_tag('selia/components/filter_bar.html', takes_context=True)
def filter_bar(context, forms):
context['forms'] = forms
search_form = forms['search']
search_field = search_form.fields['search']
search_field = search_field.get_bound_field(search_form, 'search')
if search_field.data:
context['search'] = search_field.data
context['clear'] = True
context['form'] = {}
filter_form = forms['filter']
for field_name, field in filter_form._form.fields.items():
bound_field = field.get_bound_field(filter_form._form, field_name)
if bound_field.data:
context['form'][field_name] = {
'data': bound_field.data,
'label': field.label
}
context['clear'] = True
return context
@register.filter(name='remove_option')
def remove_option(value, field):
regex = r'({}=)([^&]+)'.format(field)
result = re.sub(regex, r'\1', value)
return result
FORM_ICONS = {
'exact': '<i class="fas fa-equals"></i>',
'iexact':'<i class="fas fa-equals"></i>',
'in': '<i class="fas fa-list-ol"></i>',
'lt': '<i class="fas fa-less-than"></i>',
'gt': '<i class="fas fa-greater-than"></i>',
'gte': '<i class="fas fa-greater-than-equal"></i>',
'lte': '<i class="fas fa-less-than-equal"></i>',
'icontains': '<i class="fas fa-font"></i>',
'contains': '<i class="fas fa-font"></i>',
'istartswith': '<i class="fas fa-font"></i>',
'startswith': '<i class="fas fa-font"></i>',
'iendswith': '<i class="fas fa-font"></i>',
'endswith': '<i class="fas fa-font"></i>',
'regex': '<i class="fas fa-terminal"></i>',
'iregex': '<i class="fas fa-terminal"></i>',
}
@register.filter(name='selia_form', is_safe=True)
def selia_form(form, label):
widget = form.field.widget
custom_attrs = ' form-control'
if widget.input_type == 'select':
custom_attrs += ' custom-select'
if widget.input_type == 'file':
custom_attrs = 'custom-file-input'
widget_attrs = widget.attrs.get('class', '')
class_for_html = widget_attrs + custom_attrs
input_html = form.as_widget(attrs={'class': class_for_html})
try:
lookup_expr = form.html_name.split('__')[-1]
icon = FORM_ICONS.get(lookup_expr, FORM_ICONS['exact'])
except:
icon = FORM_ICONS['exact']
prepend_html = '''
<div class="input-group-prepend">
<span class="input-group-text" id="{prepend_id}">
{prepend_icon}
</span>
</div>
'''.format(
prepend_id=form.html_name + '_prepend',
prepend_icon=icon
)
append_html = '''
<div class="input-group-append">
<button type="submit" class="btn btn-outline-success" type="button" id="{append_id}">
{append_icon} <i class="fas fa-plus"></i>
</button>
</div>
'''.format(
append_id=form.html_name + '_append',
append_icon=_('add')
)
help_text_html = '''
<small id="{help_text_id}" class="form-text text-muted">{help_text}</small>
'''.format(
help_text_id=form.html_name + '_help_text',
help_text=form.help_text
)
if label:
label_html = form.label_tag(contents=label)
elif label is None:
label_html = ''
else:
label_html = form.label_tag()
form_html = '''
<div class="form-group w-100">
<small>{label_html}</small>
<div class="input-group">
{prepend_html}
{input_html}
{append_html}
</div>
{help_text_html}
</div>
'''
form_html = form_html.format(
label_html=label_html,
prepend_html=prepend_html,
input_html=input_html,
append_html=append_html,
help_text_html=help_text_html
)
return mark_safe(form_html)
@register.inclusion_tag('selia/components/bootstrap_form.html')
def bootstrap_form(form):
return {'form': form}
@register.filter(name='update_metadata', is_safe=True)
def update_metadata(form, metadata):
form.update_metadata(metadata)
@register.filter(name='remove_fields', is_safe=True)
def remove_fields(query, fields):
fields = fields.split('&')
query = query.copy()
for field in fields:
try:
query.pop(field)
except KeyError:
pass
return query.urlencode()
@register.filter(name='add_chain', is_safe=True)
def add_chain(query, view_name):
query_copy = query.copy()
query_copy['chain'] = '{previous}|{new}'.format(
previous=query.get('chain', ''),
new=view_name)
return query_copy.urlencode()
@register.filter(name='add_fields', is_safe=True)
def add_fields(query, fields):
query_copy = query.copy()
try:
fields = fields.split('&')
except:
return query_copy.urlencode()
for field in fields:
try:
key, value = field.split("=")
query_copy[key] = value
except:
pass
return query_copy.urlencode()
@register.simple_tag
def remove_form_fields(query, forms):
query = query.copy()
if 'filter' in forms:
filter_form = forms['filter']
filter_prefix = filter_form._form.prefix
for field in filter_form._form.fields:
if filter_prefix:
field = '{}-{}'.format(filter_prefix, field)
try:
query.pop(field)
except:
pass
if 'search' in forms:
search_form = forms['search']
search_prefix = search_form.prefix
for field in search_form.fields:
if search_prefix:
field = '{}-{}'.format(search_prefix, field)
try:
query.pop(field)
except:
pass
if 'order' in forms:
order_form = forms['order']
order_prefix = order_form.prefix
for field in order_form.fields:
if order_prefix:
field = '{}-{}'.format(order_prefix, field)
try:
query.pop(field)
except:
pass
return query.urlencode()
@register.inclusion_tag('selia/components/selected_item.html')
def selected_item(template, item, label):
random_id = uuid.uuid4().hex.lower()[0:8]
full_template_name = 'selia/components/select_list_items/{name}.html'
return {
'template': full_template_name.format(name=template),
'item': item,
'id': random_id,
'label': label
}
@register.inclusion_tag('selia/components/is_own_checkbox.html')
def is_own_checkbox(form):
return {'form': form}
| CONABIO-audio/irekua | irekua/selia/templatetags/selia_components.py | selia_components.py | py | 9,880 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "django.template.Library",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "django.template",
"line_number": 10,
"usage_type": "name"
},
{
"api_name": "django.template",
"line_number": 50,
"usage_type": "name"
},
{
"api_name": "dal_select2.w... |
6609929946 | import pytest
from unittest.mock import MagicMock, patch
from cura.PrinterOutput.Models.ExtruderConfigurationModel import ExtruderConfigurationModel
from cura.PrinterOutput.Models.MaterialOutputModel import MaterialOutputModel
from cura.PrinterOutput.Models.PrinterConfigurationModel import PrinterConfigurationModel
from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel
from cura.PrinterOutput.PrinterOutputDevice import PrinterOutputDevice
test_validate_data_get_set = [
{"attribute": "connectionText", "value": "yay"},
{"attribute": "connectionState", "value": 1},
]
@pytest.fixture()
def printer_output_device():
with patch("UM.Application.Application.getInstance"):
return PrinterOutputDevice("whatever")
@pytest.mark.parametrize("data", test_validate_data_get_set)
def test_getAndSet(data, printer_output_device):
model = printer_output_device
# Convert the first letter into a capital
attribute = list(data["attribute"])
attribute[0] = attribute[0].capitalize()
attribute = "".join(attribute)
# mock the correct emit
setattr(model, data["attribute"] + "Changed", MagicMock())
# Attempt to set the value
with patch("cura.CuraApplication.CuraApplication.getInstance"):
getattr(model, "set" + attribute)(data["value"])
# Check if signal fired.
signal = getattr(model, data["attribute"] + "Changed")
assert signal.emit.call_count == 1
# Ensure that the value got set
assert getattr(model, data["attribute"]) == data["value"]
# Attempt to set the value again
getattr(model, "set" + attribute)(data["value"])
# The signal should not fire again
assert signal.emit.call_count == 1
def test_uniqueConfigurations(printer_output_device):
printer = PrinterOutputModel(MagicMock())
# Add a printer and fire the signal that ensures they get hooked up correctly.
printer_output_device._printers = [printer]
printer_output_device._onPrintersChanged()
assert printer_output_device.uniqueConfigurations == []
configuration = PrinterConfigurationModel()
printer.addAvailableConfiguration(configuration)
assert printer_output_device.uniqueConfigurations == [configuration]
# Once the type of printer is set, it's active configuration counts as being set.
# In that case, that should also be added to the list of available configurations
printer.updateType("blarg!")
loaded_material = MaterialOutputModel(guid = "", type = "PLA", color = "Blue", brand = "Generic", name = "Blue PLA")
loaded_left_extruder = ExtruderConfigurationModel(0)
loaded_left_extruder.setMaterial(loaded_material)
loaded_right_extruder = ExtruderConfigurationModel(1)
loaded_right_extruder.setMaterial(loaded_material)
printer.printerConfiguration.setExtruderConfigurations([loaded_left_extruder, loaded_right_extruder])
assert set(printer_output_device.uniqueConfigurations) == set([configuration, printer.printerConfiguration])
def test_uniqueConfigurations_empty_is_filtered_out(printer_output_device):
printer = PrinterOutputModel(MagicMock())
# Add a printer and fire the signal that ensures they get hooked up correctly.
printer_output_device._printers = [printer]
printer_output_device._onPrintersChanged()
printer.updateType("blarg!")
empty_material = MaterialOutputModel(guid = "", type = "empty", color = "empty", brand = "Generic", name = "Empty")
empty_left_extruder = ExtruderConfigurationModel(0)
empty_left_extruder.setMaterial(empty_material)
empty_right_extruder = ExtruderConfigurationModel(1)
empty_right_extruder.setMaterial(empty_material)
printer.printerConfiguration.setExtruderConfigurations([empty_left_extruder, empty_right_extruder])
assert printer_output_device.uniqueConfigurations == []
| Ultimaker/Cura | tests/PrinterOutput/TestPrinterOutputDevice.py | TestPrinterOutputDevice.py | py | 3,837 | python | en | code | 5,387 | github-code | 1 | [
{
"api_name": "unittest.mock.patch",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "cura.PrinterOutput.PrinterOutputDevice.PrinterOutputDevice",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "pytest.fixture",
"line_number": 15,
"usage_type": "call"
... |
18481811861 | # -*- coding: utf-8 -*-
"""
Functions to analyze the distances between given number inside a sudoku.
"""
# STD
from collections import defaultdict
import math
import functools
# EXT
import numpy
import matplotlib.pyplot as plt
from scipy.linalg import eigh
# PROJECT
from general import Sudoku, SudokuCollection, read_line_sudoku_file
# https://en.wikipedia.org/wiki/Spatial_descriptive_statistics
class SpatialAnalysisSudoku(Sudoku):
"""
Sudoku class with also measures the degree of spatial distribution of given numbers within the sudoku.
"""
given_coordinates = []
def __init__(self, raw_data):
super().__init__(raw_data)
self._build_distance_matrix()
# self.print_matrix(self.distance_matrix)
def _build_distance_matrix(self):
given_coordinates = self.given_coordinates
n_givens = len(given_coordinates)
# Calculate distance matrix
self.distance_matrix = numpy.zeros(shape=(n_givens, n_givens))
for i in range(n_givens):
for j in range(n_givens):
self.distance_matrix[i][j] += self.numbers_distance(given_coordinates[i], given_coordinates[j])
@property
def given_coordinates(self):
given_coordinates = []
# Get coordinates of given numbers
for x in range(9):
for y in range(9):
if self.list_representation[x][y] != 0:
given_coordinates.append((x, y))
return given_coordinates
@property
def metric(self):
shape = self.distance_matrix.shape
return sum([sum(row) for row in self.distance_matrix]) / (shape[0] * shape[1])
@property
def distance_variance(self):
average_distance = self.metric
shape = self.distance_matrix.shape
return sum([
sum([
(dist - average_distance)**2 for dist in row
])
for row in self.distance_matrix
]) / (shape[0] * shape[1])
@staticmethod
def numbers_distance(coordinates1, coordinates2):
return numpy.linalg.norm(
numpy.array(
[coordinates1[0] - coordinates2[0], coordinates1[1] - coordinates2[1]]
)
)
@staticmethod
def print_matrix(matrix):
numpy.set_printoptions(precision=2, suppress=True, linewidth=220)
print(matrix)
def update(self):
super().update()
self._build_distance_matrix()
class DeterminantSudoku(SpatialAnalysisSudoku):
"""
Use the determinant of the distance matrix as a measure of the dispersion of the given numbers.
"""
@property
def metric(self):
return numpy.linalg.det(self.distance_matrix)
@property
def distance_variance(self):
raise NotImplementedError
class EigenvalueSudoku(SpatialAnalysisSudoku):
"""
Use the biggest eigenvalue of the distance matrix as a measure of the dispersion of the given numbers.
"""
@property
def metric(self):
return eigh(self.distance_matrix, eigvals_only=True)[0]
@property
def distance_variance(self):
raise NotImplementedError
class CentroidSudoku(SpatialAnalysisSudoku):
"""
Create a centroid based on the distribution of the given numbers and measure the average distance to it.
"""
@property
def centroid(self):
given_coordinates = self.given_coordinates
x_coordinates, y_coordinates = zip(*given_coordinates)
return (
sum(x_coordinates)/len(x_coordinates), # x coordinate for centroid
sum(y_coordinates)/len(y_coordinates) # y coordinate for centroid
)
@property
def metric(self):
distance_matrix = self.distance_matrix
return sum(distance_matrix) / len(distance_matrix)
@property
def distance_variance(self):
distance_matrix = self.distance_matrix
average_distance = self.metric
return functools.reduce(
lambda sum_, dist: sum_ + (dist - average_distance)**2, distance_matrix
) / len(distance_matrix)
def _build_distance_matrix(self):
given_coordinates = self.given_coordinates
centroid = self.centroid
n_givens = len(given_coordinates)
# Calculate distance matrix
self.distance_matrix = numpy.zeros(shape=(n_givens, 1))
for coordinates, i in zip(given_coordinates, range(n_givens)):
self.distance_matrix[i] = self.numbers_distance(centroid, coordinates)
class SpatialAnalysisSudokuCollection(SudokuCollection):
"""
Collection that contains multiple distributiveness sudokus.
"""
average_distances = None
sorted_average_distances = None
distances_frequencies = None
sorted_distances_frequencies = None
def __init__(self, sudokus, precision=2):
assert precision in range(2, 4)
super().__init__(sudokus)
self.precision = precision
@property
def sudoku_cls(self):
return type(list(self.sudokus.values())[0])
def calculate_metric_distribution(self):
self.average_distances = {
sudoku_uid: sudoku.metric for sudoku_uid, sudoku in self
}
self.distances_frequencies = defaultdict(int)
for _, dist in self.average_distances.items():
self.distances_frequencies[math.ceil(dist*10**self.precision)/10**self.precision] += 1
# Sort average distances - sorted by value
self.sorted_average_distances = sorted(self.average_distances.items(), key=lambda x: x[1])
# Sort average distances frequencies - sorted by key
self.sorted_distances_frequencies = sorted(self.distances_frequencies.items(), key=lambda x: x[0])
def get_n_highest(self, n):
"""
Get the n sudokus with the highest average distance.
"""
return {
sudoku_uid: self.sudokus[sudoku_uid]
for sudoku_uid, _ in self.sorted_average_distances[len(self.sorted_average_distances)-n:]
}
def get_n_lowest(self, n):
"""
Get the n sudokus with the lowest average distance.
"""
return {
sudoku_uid: self.sudokus[sudoku_uid]
for sudoku_uid, _ in self.sorted_average_distances[:n]
}
def plot_average_metric_distribution(self, title=True):
assert self.average_distances is not None and self.distances_frequencies is not None, \
"Please run calculate_distance_distribution() first"
number_of_sudokus = len(self.sudokus)
plot_min = self.sorted_distances_frequencies[0][0]
plot_max = self.sorted_distances_frequencies[len(self.sorted_distances_frequencies)-1][0]
plot_range = plot_max - plot_min
fig, ax = plt.subplots()
ax.bar(
list(self.distances_frequencies.keys()),
list(self.distances_frequencies.values()),
width=plot_range/len(self.distances_frequencies)/self.precision,
align='center', edgecolor="black", facecolor="grey"
)
if title:
ax.set_title(
"Distribution of average distances of given numbers among {} sudokus".format(number_of_sudokus),
fontsize=10
)
print("Showing plot...")
plt.show()
def plot_average_and_variance(self, title=True):
averages_and_variances = {
sudoku_uid: (sudoku.metric, sudoku.distance_variance)
for sudoku_uid, sudoku in self
}
number_of_sudokus = len(self.sudokus)
fig, ax = plt.subplots()
x, y = zip(*list(averages_and_variances.values()))
ax.scatter(x, y)
if title:
ax.set_title(
"Distribution of {} Sudokus given their distance mean and average".format(number_of_sudokus),
fontsize=10
)
plt.xlabel("Average distance")
plt.ylabel("Distance variance")
plt.show()
def plot_heatmap(self, n=0):
"""
Generate heat map of given numbers for n sudokus. If n is 0, a heat map for all the sudokus in this collection
will be created. If n is positive, a heat map with the n highest scoring sudokus according to the metric of the
sudokus in this collection will be created, the same accordingly for the lowest ones when n is negative.
"""
heatmap_sudokus = None
if n == 0:
heatmap_sudokus = self.sudokus
if n > 0:
heatmap_sudokus = self.get_n_highest(n)
if n < 0:
heatmap_sudokus = self.get_n_lowest(-n)
heatmap_data = numpy.zeros(shape=(9, 9))
for _, sudoku in heatmap_sudokus.items():
for x, y in sudoku.given_coordinates:
heatmap_data[x][y] += 1
plt.imshow(heatmap_data, cmap="seismic", interpolation='nearest')
plt.axis('off')
plt.show()
if __name__ == "__main__":
sudoku_path = "../data/49k_17.txt"
sudokus = read_line_sudoku_file(sudoku_path, sudoku_class=CentroidSudoku)
sasc = SpatialAnalysisSudokuCollection(sudokus, precision=2)
sasc.calculate_metric_distribution()
highest = sasc.get_n_highest(3)
lowest = sasc.get_n_lowest(3)
print("Sudokus with highest average distances...")
for _, sudoku in highest.items():
print(str(sudoku))
print("Sudokus with lowest average distances...")
for _, sudoku in lowest.items():
print(str(sudoku))
#sasc.plot_average_metric_distribution(title=False)
#sasc.plot_average_and_variance()
#sasc.plot_heatmap()
#sasc.plot_heatmap(1000)
#sasc.plot_heatmap(-1000)
| Kaleidophon/shiny-robot | experiments/distances.py | distances.py | py | 9,676 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "general.Sudoku",
"line_number": 23,
"usage_type": "name"
},
{
"api_name": "numpy.zeros",
"line_number": 39,
"usage_type": "call"
},
{
"api_name": "numpy.linalg.norm",
"line_number": 74,
"usage_type": "call"
},
{
"api_name": "numpy.linalg",
"line... |
29448425552 | from PIL import Image
from flask import Flask, request, render_template
from glob import glob
import os
from imageTransfer import Transfer
import numpy as np
class PathInfo(object):
def __init__(self):
style_img_paths = glob('static/style/*.jpg') + glob('static/style/*.jpeg') + glob('static/style/*.png')
self.styles = [(path, os.path.basename(path)) for path in style_img_paths]
self.content_img_path = None
self.style_img_path = None
self.transfer_img_path =None
path_info = PathInfo()
transfer = Transfer()
def process(path_info):
transfer.load_data(path_info.style_img_path, path_info.content_img_path)
res = transfer.transfer()
print(res.shape)
return Image.fromarray(res.astype('uint8')).convert('RGB')
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# Request for content image
try:
content_file = request.files['content']
except Exception as e:
print(e)
else:
# Save content image
content_img = Image.open(content_file.stream) # PIL image
path_info.content_img_path = "static/content/" + content_file.filename
# print(path_info.content_img_path)
content_img.save(path_info.content_img_path)
return render_template('index.html',
styles=path_info.styles,
content=path_info.content_img_path,
transfer=path_info.transfer_img_path)
else:
# Request for style image
try:
style_basename = request.values['style_basename']
print(style_basename)
except Exception as e:
print(e)
else:
path_info.style_img_path = 'static/style/%s' % style_basename
# process images
transfer = process(path_info)
# Save transfer image
path_info.transfer_img_path = "static/transfer/%s_stylized_%s.png" % (
os.path.splitext(os.path.basename(path_info.content_img_path))[0],
os.path.splitext(os.path.basename(path_info.style_img_path))[0])
print(path_info.transfer_img_path)
transfer.save(path_info.transfer_img_path)
return render_template('index.html',
styles=path_info.styles,
content=path_info.content_img_path,
transfer=path_info.transfer_img_path)
if __name__=="__main__":
app.run("127.0.0.1", 7777)
| Jieqianyu/styleTransfer | server.py | server.py | py | 2,650 | python | en | code | 4 | github-code | 1 | [
{
"api_name": "glob.glob",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "os.path.basename",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "imageTransfer.Transfer",
... |
39994314829 | from GQA.functions.peaks import Peaks
from GQA.functions.rastrigin import Rastrigin
from GQA.functions.eggholder import Eggholder
from GQA.quantum.gqa_function import GQA_function
from GQA.utils.plotutils import plotList,average_evals
from tqdm import tqdm
# r = Rastrigin(-5.12,5.12,-5.12,5.12)
# r.plot_()
# e = Eggholder(-512,512,-512,512)
# e.plot_()
# p = Peaks(-3,3,-3,3)
# p.plot_()
l = []
params = []
runs = 50
generations = 200
num = 64
num_pop = 16
deltas = [0.0025,0.025,0.25,0.5]
seeds = range(runs)
verbose = 0
function = "rastrigin" # | "eggholder" | "rastrigin" | "peaks"
decay = 0
mutation_rate = 0.01
crossover_probability = 0.5
avg_evals = {}
bst_evals = {}
for i in tqdm(deltas):
evals = []
avg_evals[i] = 0
bst_evals[i] = 0
tmp = []
for s in tqdm(seeds):
gqa = GQA_function(generations,num,num_pop,i,s,verbose,function,decay,mutation_rate,crossover_probability)
gqa.run()
evals.append(gqa.best_evaluations)
tmp.append(gqa.best_fitness)
l.append(average_evals(evals))
avg_evals[i] = sum(tmp)/len(tmp)
bst_evals[i] = min(tmp)
params.append(i)
plotList(l,params,generations)
print(avg_evals)
print(bst_evals)
| simonetome/QuantumGeneticAlgorithm | experiments.py | experiments.py | py | 1,209 | python | en | code | 3 | github-code | 1 | [
{
"api_name": "tqdm.tqdm",
"line_number": 35,
"usage_type": "call"
},
{
"api_name": "tqdm.tqdm",
"line_number": 41,
"usage_type": "call"
},
{
"api_name": "GQA.quantum.gqa_function.GQA_function",
"line_number": 42,
"usage_type": "call"
},
{
"api_name": "GQA.utils.p... |
25092121024 | from __future__ import print_function
import os.path
from time import sleep
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from vidconvert import getframes
from time import time
SCOPES = ['https://www.googleapis.com/auth/drive.file']
DOCUMENT_ID = '1HbI9540qtaDd0W13Y9typazBgutqB08j7-E_Zm2OTEQ'
def main():
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
service = build('docs', 'v1', credentials=creds)
document = service.documents().get(documentId=DOCUMENT_ID).execute()
def createdoc():
title = 'My Document'
body = {
'title': title
}
doc = service.documents().create(body=body).execute()
print('Created document with title:', doc.get('title'))
def createrange():
# Create range for video
request = [
{
'createNamedRange': {
'name': 'main',
'range': {
'startIndex': 1,
'endIndex': 2,
}
}
},
]
service.documents().batchUpdate(documentId=DOCUMENT_ID, body={'requests': request}).execute()
def deleteallranges():
request = [
{
'deleteNamedRange': {
'name': 'main'
}
},
]
service.documents().batchUpdate(documentId=DOCUMENT_ID, body={'requests': request}).execute()
print('remaining ranges:')
print(document.get('namedRanges', {}).get('main'))
createrange()
request = [
{
'replaceNamedRangeContent': {
'text': 'youshouldntseethis',
'namedRangeName': 'main'
}
},
]
frames = getframes('badapple.mp4', 5)
prev_time = time()
for frame in frames:
while time() < prev_time + 1:
pass
else:
request[0]['replaceNamedRangeContent']['text'] = frame
service.documents().batchUpdate(documentId=DOCUMENT_ID, body={'requests': request}).execute()
prev_time = time()
print('DONE.')
request[0]['replaceNamedRangeContent']['text'] = 'DONE. '
service.documents().batchUpdate(documentId=DOCUMENT_ID, body={'requests': request}).execute()
deleteallranges()
if __name__ == '__main__':
main()
| ray1i/googledocs-bad-apple | main.py | main.py | py | 3,375 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "os.path.path.exists",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "os.path.path",
"line_number": 20,
"usage_type": "attribute"
},
{
"api_name": "os.path",
"line_number": 20,
"usage_type": "name"
},
{
"api_name": "google.oauth2.credentia... |
9196596468 | from collections import namedtuple
import altair as alt
import math
import pandas as pd
import streamlit as st
"""
# Welcome to Streamlit!
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:
If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
forums](https://discuss.streamlit.io).
In the meantime, below is an example of what you can do with just a few lines of code:
"""
import pygame
import os
import openai
import re
from os import path
from llama_index.node_parser import SimpleNodeParser
from llama_index import ServiceContext, set_global_service_context
from llama_index.llms import OpenAI
from llama_index.prompts import PromptTemplate
from llama_index import VectorStoreIndex, SimpleDirectoryReader
key = "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"
os.environ["OPENAI_API_KEY"] = key
openai.api_key = os.environ["OPENAI_API_KEY"]
documents = SimpleDirectoryReader('data').load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()
def load_data():
response = query_engine.query("Create a unique quiz question and answer from the content. Put Q in front of the question, A in front of the answer.")
print(response)
q_and_a = (str(response)).split("A: ")
return q_and_a
def load_data_questions():
response = query_engine.query("Create a list of quiz questions and answers from the content. Put Q in front of the question, A in front of the answer.")
print(response)
#res = [sub.split("A: ") for sub in response]
#print(str(res))
#q_and_a = (str(response)).split("A: ")
#return q_and_a
def check_answer(q, a):
response = query_engine.query(f"Given question {q}, is the answer {a} correct?")
return str(response)
pygame.init()
#clock = pygame.time.Clock()
screen = pygame.display.set_mode((1000, 1000), 0, 32)
load_data_questions()
all_sprites = pygame.sprite.Group()
explosion_anim = {}
explosion_anim['lg'] = []
explosion_anim['sm'] = []
img_dir = path.join(path.dirname(__file__), 'explosion')
for i in range(9):
filename = 'regularExplosion0{}.png'.format(i)
img = pygame.image.load(path.join(img_dir, filename)).convert()
img.set_colorkey((255, 255, 255))
img_lg = pygame.transform.scale(img, (75, 75))
explosion_anim['lg'].append(img_lg)
img_sm = pygame.transform.scale(img, (32, 32))
explosion_anim['sm'].append(img_sm)
class Explosion(pygame.sprite.Sprite):
def __init__(self, center, size):
pygame.sprite.Sprite.__init__(self)
self.size = size
self.image = explosion_anim[self.size][0]
self.rect = self.image.get_rect()
self.rect.center = center
self.frame = 0
self.last_update = pygame.time.get_ticks()
self.frame_rate = 50
def update(self):
now = pygame.time.get_ticks()
if now - self.last_update > self.frame_rate:
self.last_update = now
self.frame += 1
if self.frame == len(explosion_anim[self.size]):
self.kill()
else:
center = self.rect.center
self.image = explosion_anim[self.size][self.frame]
self.rect = self.image.get_rect()
self.rect.center = center
question_rect = pygame.Rect(100, 100, 500, 100)
input_rect = pygame.Rect(100, 250, 500, 100)
color = pygame.Color('lightskyblue3')
#pygame.draw.rect(screen, color, input_rect)
#base_font = pygame.freetype.Font(None, 32)
ques_ans = load_data()
width = screen.get_width()
height = screen.get_height()
user_text = "A: "
font = pygame.font.SysFont("Comic Sans MS", 14)
ai_text_surface = font.render(ques_ans[0], True, (255, 255, 255))
user_text_surface = font.render(user_text, True, (255, 255, 255))
ans_button = font.render('answer' , True , color)
next_button = font.render('next', True, color)
done = False
while done == False:
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
pygame.display.quit()
pygame.quit()
done = True
#checks if a mouse is clicked
if ev.type == pygame.MOUSEBUTTONDOWN:
#if the mouse is clicked on the
# button the game is terminated
if 500 <= mouse[0] <= 640 and height/2 <= mouse[1] <= height/2+40:
ai_text_surface = font.render(check_answer(ques_ans[0], user_text), True, (0, 60, 20))
expl = Explosion((mouse[0], mouse[1]), 'lg')
all_sprites.add(expl)
elif 250 <= mouse[0] <= 400 and height/2 <= mouse[1] <= height/2+40:
# Get next question
ques_ans = load_data_again()
ai_text_surface = font.render(ques_ans[0], True, (255, 255, 255))
user_text = "A: "
# Get user input
if ev.type == pygame.KEYDOWN:
# Check for backspace
if ev.key == pygame.K_BACKSPACE:
# get text input from 0 to -1 i.e. end.
user_text = user_text[:-1]
user_text_surface = font.render(user_text, True, (255, 255, 255))
# Unicode standard is used for string
# formation
else:
user_text += ev.unicode
user_text_surface = font.render(user_text, True, (255, 255, 255))
if (done == False):
# fills the screen with a color
screen.fill((0, 0, 0))
# stores the (x,y) coordinates into
# the variable as a tuple
mouse = pygame.mouse.get_pos()
pygame.draw.rect(screen, color, question_rect)
pygame.draw.rect(screen, color, input_rect)
all_sprites.update()
# superimposing the text onto our button
screen.blit(ans_button, (500,height/2))
screen.blit(next_button, (250,height/2))
screen.blit(ai_text_surface, (question_rect.x+5, question_rect.y+5))
screen.blit(user_text_surface, (input_rect.x+5, input_rect.y+5))
all_sprites.draw(screen)
# updates the frames of the game
pygame.display.update()
##with st.echo(code_location='below'):
## total_points = st.slider("Number of points in spiral", 1, 5000, 2000)
## num_turns = st.slider("Number of turns in spiral", 1, 100, 9)
##
## Point = namedtuple('Point', 'x y')
## data = []
##
## points_per_turn = total_points / num_turns
##
## for curr_point_num in range(total_points):
## curr_turn, i = divmod(curr_point_num, points_per_turn)
## angle = (curr_turn + 1) * 2 * math.pi * i / points_per_turn
## radius = curr_point_num / total_points
## x = radius * math.cos(angle)
## y = radius * math.sin(angle)
## data.append(Point(x, y))
##
## st.altair_chart(alt.Chart(pd.DataFrame(data), height=500, width=500)
## .mark_circle(color='#0068c9', opacity=0.5)
## .encode(x='x:Q', y='y:Q'))
| kathleenmariekelly/streamlit-example | streamlit_app.py | streamlit_app.py | py | 7,031 | python | en | code | null | github-code | 1 | [
{
"api_name": "os.environ",
"line_number": 31,
"usage_type": "attribute"
},
{
"api_name": "openai.api_key",
"line_number": 32,
"usage_type": "attribute"
},
{
"api_name": "os.environ",
"line_number": 32,
"usage_type": "attribute"
},
{
"api_name": "llama_index.Simpl... |
4295634182 | import streamlit as st
import requests
import streamlit.components.v1 as components
import streamlit.components.v1 as stc
from PIL import Image, UnidentifiedImageError
import PIL.Image
import os
import csv
import pandas as pd
import pymongo
from pymongo import MongoClient
from io import BytesIO
import base64
import markdown
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import yagmail
import urllib.parse
import joblib
import tensorflow as tf
from tensorflow import keras
import numpy as np
from bs4 import BeautifulSoup
import json
import streamlit_lottie
from streamlit_lottie import st_lottie
import time
import random
from model import Model
import urllib.request
import git
from pathlib import Path
st.set_page_config(page_title="P.E.T", page_icon=":paw_prints:")
st.markdown('<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">', unsafe_allow_html=True)
PAGE_1 = "Inicio"
PAGE_2 = "Adoptar un animal"
PAGE_3 = "Donar"
PAGE_4 = "Contacto"
PAGE_5 = "Voluntariado"
PAGE_6 = "Predictor"
def write_page_1():
st.write("<h1>Bienvenidos a la protectora P.E.T!</h1>", unsafe_allow_html=True)
st.write("<p>Somos una organización malagueña sin ánimo de lucro que se encarga de cuidar gatos y perros y darles un nuevo hogar.</p>", unsafe_allow_html=True)
st.header("Adopción")
st.write("En nuestra protectora contamos con un proceso de adopción muy sencillo y transparente. Si estás interesado en adoptar un animal, visita nuestra sección de Adoptar un animal para conocer los requisitos y los pasos a seguir.")
file_id = "1ZVdlLCMy-HsmG2HC1_ZgalBySg7Td5UY"
url = f'https://drive.google.com/uc?id={file_id}'
response = requests.get(url)
image = Image.open(BytesIO(response.content))
st.image(image, caption='Gatos y perros unidos')
st.header("Colabora con nosotros")
st.write("Si quieres colaborar con nuestra protectora, tienes varias opciones:")
st.write("- Haz una donación para ayudarnos a cubrir los gastos de alimentación, cuidado veterinario, etc.")
st.write("- Conviértete en voluntario y ayúdanos con las tareas diarias en la protectora.")
st.write("- Comparte nuestro mensaje en tus redes sociales para ayudarnos a llegar a más personas.")
with open("animations/dog.json") as source:
dog = json.load(source)
st_lottie(dog, width=200, height=200, speed=1.5)
st.header("Síguenos en redes sociales")
st.write("Síguenos en nuestras redes sociales para estar al tanto de las últimas noticias y novedades de nuestra protectora:")
st.markdown('<i class="fa fa-facebook-square"></i> [Facebook](https://www.facebook.com/mi_protectora)', unsafe_allow_html=True)
st.markdown('<i class="fa fa-instagram"></i> [Instagram](https://www.instagram.com/mi_protectora)', unsafe_allow_html=True)
st.markdown('<i class="fa fa-twitter"></i> [Twitter](https://www.twitter.com/mi_protectora)', unsafe_allow_html=True)
with open("animations/cat.json") as source:
dog = json.load(source)
st_lottie(dog, width=200, height=200, speed=1)
def write_page_2():
df_adopted = pd.read_csv("adopted.csv")
repo_url = "https://raw.githubusercontent.com/fl0rch/Pet_Enhacement_Transition/main"
img_dir = "img_predict"
st.write("<h2>Adoptar un animal:</h2>", unsafe_allow_html=True)
animals = ['Perro', 'Gato']
animal_choice = st.selectbox("¿Qué animal te gustaría adoptar?", animals)
breeds = {
'Perro': ['African Wild Dog', 'Basenji', 'American Spaniel', 'Afghan',
'Basset', 'Bearded Collie', 'Beagle', 'Bermaise',
'American Hairless', 'Airedale', 'Bull Terrier', 'Border Collie',
'Borzoi', 'Bloodhound', 'Bluetick', 'Bull Mastiff', 'Blenheim',
'Boxer', 'Boston Terrier', 'Bichon Frise', 'Chinese Crested',
'Chihuahua', 'Cocker', 'Chow', 'Collie', 'Corgi', 'Cockapoo',
'Clumber', 'Cairn', 'Bulldog', 'German Sheperd',
'Golden Retriever', 'Great Dane', 'Dhole', 'Coyote',
'French Bulldog', 'Doberman', 'Elk Hound', 'Dalmation', 'Dingo',
'Great Perenees', 'Labradoodle', 'Irish Spaniel', 'Greyhound',
'Lhasa', 'Groenendael', 'Japanese Spaniel', 'Irish Wolfhound',
'Komondor', 'Labrador', 'Pomeranian', 'Pit Bull', 'Pekinese',
'Rhodesian', 'Maltese', 'Mex Hairless', 'Malinois', 'Poodle',
'Pug', 'Newfoundland', 'Shih-Tzu', 'Shiba Inu', 'Rottweiler',
'Siberian Husky', 'Scotch Terrier', 'Vizsla', 'Saint Bernard',
'Shar_Pei', 'Schnauzer', 'Yorkie'],
'Gato': ['Bombay', 'Bengal', 'American Shorthair', 'Maine Coon',
'Egyptian Mau', 'Abyssinian', 'American Bobtail', 'Persian',
'British Shorthair', 'Birman', 'Ragdoll', 'Siamese',
'Russian Blue', 'Tuxedo', 'Sphynx']
}
breed_choice = st.selectbox("¿De qué raza te gustaría adoptar?", breeds[animal_choice])
st.write("Has seleccionado adoptar un", breed_choice)
st.write("Aquí hay alguna foto de los", breed_choice," disponibles para su adopción:")
for index, row in df_adopted.iterrows():
if row['breed'] == breed_choice:
img_url = f"{repo_url}/{img_dir}/{row['path']}"
try:
response = requests.get(f"https://raw.githubusercontent.com/fl0rch/Pet_Enhacement_Transition/main/img_predict/{urllib.parse.quote(row['path'])}")
img = Image.open(BytesIO(response.content))
except UnidentifiedImageError:
img = None
st.warning("La imagen no se pudo cargar. Verifica la URL o intenta cargar otra imagen.")
except requests.exceptions.RequestException as e:
img = None
st.warning(f"Hubo un problema al obtener la imagen: {e}")
if img is not None:
st.image(img, width=300)
st.write("**Nombre:**", row['name'])
st.write("**Descripción:**", row['description'])
image_data = {
"Sphynx_4.jpg": {"name": "Heimdallr", "description": "un gato curioso que vigila su hogar como el guardián mítico de la mitología nórdica."},
"Maine_Coon_05.jpg": {"name": "Perséfone", "description": "Cariñosa y le gusta estar cerca de humanos."},
"Lhasa_04.jpg": {"name": "Hades", "description": "Pequeñito pero matón."},
"Boxer_09.jpg": {"name": "Calíope", "description": "Es asustadiza pero cuando toma confianza es my juguetona."},
"Beagle_09.jpg": {"name": "Thor", "description": "Es muy bueno y cariñoso."}
}
st.write("Otros animales disponibles:")
for img_name in os.listdir(img_dir):
img_path = os.path.join(img_dir, img_name)
img = Image.open(img_path)
st.image(img, width=300)
# Obtener la información del nombre y la descripción de la imagen actual del diccionario
if img_name in image_data:
st.write("**Nombre:**", image_data[img_name]['name'])
st.write("**Descripción:**", image_data[img_name]['description'])
else:
st.write("No hay información disponible para esta imagen.")
def write_page_3():
st.write("<h2>Donar:</h2>", unsafe_allow_html=True)
st.write("<p>Gracias por considerar una donación a nuestro refugio de animales.</p>", unsafe_allow_html=True)
st.write("<p>Todas las donaciones serán utilizadas para:</p>", unsafe_allow_html=True)
st.write("<ul>", unsafe_allow_html=True)
st.write("<li>Proporcionar atención médica a los animales</li>", unsafe_allow_html=True)
st.write("<li>Comprar alimentos y suministros</li>", unsafe_allow_html=True)
st.write("<li>Construir nuevas instalaciones en el refugio</li>", unsafe_allow_html=True)
st.write("</ul>", unsafe_allow_html=True)
st.write("<p>Si prefieres donar en especie, estas son algunas opciones:</p>", unsafe_allow_html=True)
st.write("<ul>", unsafe_allow_html=True)
st.write("<li>Alimentos para animales</li>", unsafe_allow_html=True)
st.write("<li>Mantas</li>", unsafe_allow_html=True)
st.write("<li>Juguetes</li>", unsafe_allow_html=True)
st.write("</ul>", unsafe_allow_html=True)
st.write("<p>Por favor, póngase en contacto con nosotros si desea donar alguno de estos elementos.</p>", unsafe_allow_html=True)
donation = st.number_input("¿Cuánto te gustaría donar?", value=0, min_value=0, max_value=1000, step=1)
if st.button("Donar"):
st.write("<p>Gracias por tu aportación :)</p>", unsafe_allow_html=True)
st.write("<p>Has seleccionado donar ${}</p>".format(donation), unsafe_allow_html=True)
st.write("<p>Si lo prefieres, puedes donar con Paypal:</p>", unsafe_allow_html=True)
st.markdown("<a href='https://www.paypal.com'><img src='https://www.paypalobjects.com/webstatic/mktg/logo/AM_mc_vs_dc_ae.jpg' alt='Paypal'></a>", unsafe_allow_html=True)
st.write("<p>Además, ¡nos encantaría contar con tu ayuda como voluntario!</p>", unsafe_allow_html=True)
st.write("<p>Si estás interesado en ser voluntario, por favor ponte en contacto con nosotros.</p>", unsafe_allow_html=True)
def write_page_4():
st.write("<h2>Contacto:</h2>", unsafe_allow_html=True)
st.write("<p>Para cualquier consulta, por favor contáctenos en el siguiente formulario:</p>", unsafe_allow_html=True)
with st.form(key='contact_form'):
name = st.text_input('Nombre')
email = st.text_input('Email')
message = st.text_area('Mensaje')
submit = st.form_submit_button(label='Enviar mensaje')
if submit:
yag = yagmail.SMTP('pruebapet262@gmail.com', 'ahcvndowfanwyesa')
to = 'petprotectora@gmail.com'
subject = 'Mensaje desde Refugio de Animales P.E.T'
body = f'Nombre: {name}\nEmail: {email}\nMensaje: {message}'
yag.send(to, subject, body)
st.write(f"¡Gracias {name}! Tu mensaje ha sido enviado.")
st.write("<p>O puedes contactarnos directamente:</p>", unsafe_allow_html=True)
st.write("<ul>",unsafe_allow_html=True)
st.write("<li>Teléfono: 555-1234</li>", unsafe_allow_html=True)
st.write("<li>Dirección: Calle Principal 123</li>", unsafe_allow_html=True)
st.write("<li>Horario: Lunes a Viernes de 9am a 5pm</li>", unsafe_allow_html=True)
st.write("</ul>", unsafe_allow_html=True)
st.write("<p>Ubicación:</p>", unsafe_allow_html=True)
st.markdown('<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d60268.33258723767!2d-73.98750179272074!3d40.74881777062273!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x0!2zMzDCsDA0JzM1LjAiTiA3M8KwMTUnMTYuOCJX!5e0!3m2!1sen!2sus!4v1644866163477!5m2!1sen!2sus" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy"></iframe>', unsafe_allow_html=True)
st.write("<p>O puedes hablar con nuestro Agente por si necesitas algo a tiempo real</p>", unsafe_allow_html=True)
components.iframe("https://console.dialogflow.com/api-client/demo/embedded/d8988215-f3ba-4d6c-aeba-9a3a58d150da", width=500, height=700)
client = MongoClient('mongodb+srv://Diegovp97:12345@cluster0.rfquoc6.mongodb.net/test')
db = client['PET']
voluntarios = db["Voluntarios"]
def save_volunteer_to_mongo(volunteer):
"""
Función para guardar los datos del voluntario en MongoDB
"""
# Recuperar los datos existentes de MongoDB
existing_volunteer = voluntarios.find_one({"email": volunteer["email"]})
if not existing_volunteer:
# Si no hay datos antiguos, crear un nuevo objeto voluntario
volunteer_data = {
"nombre": volunteer["nombre"],
"email": volunteer["email"],
"telefono": volunteer["telefono"],
"direccion": volunteer["direccion"],
"ciudad": volunteer["ciudad"],
"provincia": volunteer["provincia"],
"pais": volunteer["pais"],
"intereses": volunteer["intereses"],
"disponibilidad": volunteer["disponibilidad"]
}
voluntarios.insert_one(volunteer_data)
send_volunteer_email(volunteer["nombre"], volunteer["email"])
st.success("Gracias por tu interés en ser voluntario. Nos pondremos en contacto contigo pronto.")
else:
# Si ya existen datos antiguos, actualizar el objeto voluntario
existing_volunteer["nombre"] = volunteer["nombre"]
existing_volunteer["telefono"] = volunteer["telefono"]
existing_volunteer["direccion"] = volunteer["direccion"]
existing_volunteer["ciudad"] = volunteer["ciudad"]
existing_volunteer["provincia"] = volunteer["provincia"]
existing_volunteer["pais"] = volunteer["pais"]
existing_volunteer["intereses"] = volunteer["intereses"]
existing_volunteer["disponibilidad"] = volunteer["disponibilidad"]
voluntarios.replace_one({"email": volunteer["email"]}, existing_volunteer)
st.warning("Este voluntario ya había sido registrado previamente y sus datos han sido actualizados")
def volunteer_already_registered(volunteer):
"""
Función para comprobar si un voluntario ya ha sido registrado previamente
"""
existing_volunteer = voluntarios.find_one({"email": volunteer["email"]})
if existing_volunteer:
return True
else:
return False
def send_volunteer_email(name, email):
"""
Función para enviar un correo electrónico al encargado del voluntariado cuando se registra un nuevo voluntario
"""
yag = yagmail.SMTP('pruebapet262@gmail.com', 'ahcvndowfanwyesa')
to = "petprotectora@gmail.com"
subject = "Nuevo voluntario registrado"
body = f"Hola encargado del voluntariado,\n\nTe informamos que {name} se ha registrado como voluntario en nuestra organización.\n\nSu dirección de correo electrónico es: {email}\n\n¡Gracias!"
yag.send(to=to, subject=subject, contents=body)
def write_page_5():
st.header("Voluntariado")
st.write("¡Únete a nuestro equipo de voluntarios y ayúdanos a mejorar el mundo!")
st.write("Rellena el siguiente formulario y nos pondremos en contacto contigo pronto.")
st.write("")
with st.form("volunteer_form"):
nombre = st.text_input("Nombre completo")
email = st.text_input("Email")
telefono = st.text_input("Teléfono")
direccion= st.text_input("Dirección")
ciudad = st.text_input("Ciudad")
provincia = st.text_input("Provincia")
pais = st.text_input("País")
intereses = st.text_area("Áreas de interés como voluntario")
disponibilidad = st.selectbox("Disponibilidad", ["Tiempo completo", "Medio tiempo", "Fines de semana"])
submit_button = st.form_submit_button(label="Enviar formulario")
if submit_button:
volunteer = {
"nombre": nombre,
"email": email,
"telefono": telefono,
"direccion": direccion,
"ciudad": ciudad,
"provincia": provincia,
"pais": pais,
"intereses": intereses,
"disponibilidad": disponibilidad
}
save_volunteer_to_mongo(volunteer)
allowed_passwords = ["Mascotas", "Perritos", "Gatitos"]
def authenticate(password):
if password in allowed_passwords:
# Establecer la sesión como autenticada
st.session_state["logged_in"] = True
return True
else:
return False
def write_restricted_page():
placeholder = st.empty()
if st.session_state.get("logged_in"):
placeholder.title("Predictor")
placeholder.write("Aquí puedes subir imágenes para predecir si es un perro o un gato.")
# Agregar el botón para subir imágenes
uploaded_file = st.file_uploader("Cargar imagen", type=["jpg", "jpeg", "png"])
# Si el usuario ha cargado una imagen, mostrarla en la página
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image, caption="Imagen cargada por el usuario", use_column_width=True)
name_pet = st.text_input("Nombre", placeholder="Toby", key="name_pet")
description_pet = st.text_area("Descripción", placeholder="Es una mascota muy cariñosa y sociable.", key="desc_pet")
with open("animations/prediction.json") as f:
animation = json.load(f)
if st.button('Guardar'):
with st.spinner("Cargando datos..."):
st_lottie(animation, speed=0.5, width=200, height=200)
model = Model(weights_path='inceptionV3.h5', classes_name_path='breeds.json')
pred = model.predict(uploaded_file)
st.write(f'La raza es {pred}')
df = pd.DataFrame(columns=['path', 'name', 'breed', 'description'])
df.loc[len(df)] = [uploaded_file.name, name_pet, pred, description_pet]
df.to_csv('adopted.csv', mode='a', header=False, index=False)
st.write("Datos guardados")
return
else:
# Mostrar la página de inicio de sesión
st.title("Iniciar sesión")
# Campo para ingresar la contraseña
password = st.text_input("Contraseña", type="password")
# Botón para iniciar sesión
if st.button("Iniciar sesión"):
if authenticate(password):
st.success("Inicio de sesión exitoso.")
# Reemplazar el espacio vacío con el contenido de la página restringida
placeholder.empty()
write_restricted_page()
else:
st.error("Contraseña incorrecta.")
def main():
pages = {
PAGE_1: write_page_1,
PAGE_2: write_page_2,
PAGE_3: write_page_3,
PAGE_4: write_page_4,
PAGE_5: write_page_5,
PAGE_6: write_restricted_page
}
page = st.sidebar.selectbox("Elige una pagina", list(pages.keys()))
selected_page = pages.get(page)
if selected_page:
selected_page()
if __name__ == "__main__":
main()
| fl0rch/Pet_Enhacement_Transition | pagina.py | pagina.py | py | 18,889 | python | es | code | 1 | github-code | 1 | [
{
"api_name": "streamlit.set_page_config",
"line_number": 36,
"usage_type": "call"
},
{
"api_name": "streamlit.markdown",
"line_number": 38,
"usage_type": "call"
},
{
"api_name": "streamlit.write",
"line_number": 54,
"usage_type": "call"
},
{
"api_name": "streamli... |
35881891250 | from selenium import webdriver
class ImageMonkeyChromeWebDriver(webdriver.Chrome):
def __init__(self, headless=True, delete_all_cookies=True):
options = webdriver.ChromeOptions()
if headless:
options.add_argument('--headless')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--no-sandbox')
super(ImageMonkeyChromeWebDriver, self).__init__(options=options)
if delete_all_cookies:
self.delete_all_cookies() | ImageMonkey/imagemonkey-core | tests/ui/webdriver.py | webdriver.py | py | 451 | python | en | code | 46 | github-code | 1 | [
{
"api_name": "selenium.webdriver.Chrome",
"line_number": 3,
"usage_type": "attribute"
},
{
"api_name": "selenium.webdriver",
"line_number": 3,
"usage_type": "name"
},
{
"api_name": "selenium.webdriver.ChromeOptions",
"line_number": 5,
"usage_type": "call"
},
{
"a... |
36427186703 | """
199. Binary Tree Right Side View
Medium
1076
46
Favorite
Share
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
"""
"""
Runtime: 40 ms, faster than 74.99% of Python3 online submissions for Binary Tree Right Side View.
Memory Usage: 13 MB, less than 96.13% of Python3 online submissions for Binary Tree Right Side View.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
level = 0
res = []
queue = deque()
if root is None:
return res
else:
queue.append(root)
while len(queue) > 0:
newqueue = deque()
curr_node = queue.popleft()
res.append(curr_node.val)
if curr_node.right is not None:
newqueue.append(curr_node.right)
if curr_node.left is not None:
newqueue.append(curr_node.left)
while len(queue) > 0:
curr_node = queue.popleft()
if curr_node.right is not None:
newqueue.append(curr_node.right)
if curr_node.left is not None:
newqueue.append(curr_node.left)
queue = newqueue
return res
| fengyang95/OJ | LeetCode/python3/199_BinaryTreeRightSideView.py | 199_BinaryTreeRightSideView.py | py | 1,718 | python | en | code | 2 | github-code | 1 | [
{
"api_name": "collections.deque",
"line_number": 45,
"usage_type": "call"
},
{
"api_name": "collections.deque",
"line_number": 51,
"usage_type": "call"
}
] |
30992767830 | from fastapi import HTTPException
from fastapi.param_functions import Depends
from fastapi_users.fastapi_users import FastAPIUsers
from sqlalchemy.sql import select, delete
from sqlalchemy.ext.asyncio.session import AsyncSession
from sqlalchemy.sql.expression import desc
from starlette.responses import Response
from fastapi_redis_cache import cache
from .tasks import on_new_location
from .models import (
Location,
Measurement,
CreateMeasurement,
User,
UpdateMeasurement,
FileReference,
Weather,
)
from .database import get_async_session, Measurements
from fastapi.routing import APIRouter
from .errors import errors, ErrorModel, get_error
import json
class MeasurementRouter:
def __init__(self, fastapi_users: FastAPIUsers, file_prefix: str):
self.fastapi_users = fastapi_users
self.file_prefix = file_prefix
def _table_to_model(self, source: Measurements) -> Measurement:
return Measurement(
measurement_id=source.id,
location=Location(
latitude=source.location_latitude or 0,
longitude=source.location_longitude or 0,
time=source.location_time,
),
notes=source.notes,
description=source.description,
title=source.title,
tags=source.tags.split(", "),
laeq=source.laeq or 0,
files=list(
[
FileReference(
file_id=x.id,
owner=x.author_id,
mime=x.mime,
original_name=x.original_name,
link="{}/file/{}".format(self.file_prefix, x.id),
measurement=x.measurement_id,
optimized_mime=x.optimized_mime,
)
for x in source.files
]
),
weather=Weather(
temperature=source.temperature,
wind_speed=source.wind_speed,
pressure=source.pressure,
humidity=source.humidity,
status=source.weather_status,
)
if source.temperature is not None
else None,
score=source.score,
deviation=source.deviation,
)
def _check_tags(
self, to_check: Measurement | CreateMeasurement | UpdateMeasurement
):
if "," in "".join(to_check.tags):
raise HTTPException(status_code=422, detail=errors.COMMA_ERROR)
async def get_all_measurements(
self, session: AsyncSession
) -> list[Measurement]:
result = await session.execute(
select(Measurements).order_by(Measurements.title)
)
return [
self._table_to_model(x) for x in result.unique().scalars().all()
]
async def get_one_measurement(
self, session: AsyncSession, id: int
) -> Measurement:
result = await session.execute(
select(Measurements).filter(id == Measurements.id)
)
res = result.unique().scalars().all()
if len(res) != 1:
raise HTTPException(status_code=404, detail=errors.ID_ERROR)
return self._table_to_model(res[0])
async def delete_measurment(
self,
session: AsyncSession,
delete_id: int,
current_user: User,
):
measurement = await session.execute(
select(Measurements).filter(delete_id == Measurements.id)
)
res = measurement.unique().scalars().all()
if len(res) != 1:
raise HTTPException(status_code=404, detail=errors.ID_ERROR)
target = res[0]
if target.author_id != current_user.id:
raise HTTPException(status_code=403, detail=errors.OWNER_ERROR)
if len(target.files) > 0:
raise HTTPException(status_code=412, detail=errors.FILES_EXIST)
await session.execute(
delete(Measurements).where(delete_id == Measurements.id)
)
async def update_measurements(
self,
session: AsyncSession,
edit_id: int,
new_data: UpdateMeasurement,
current_user: User,
) -> Measurement:
old = await session.execute(
select(Measurements).filter(Measurements.id == edit_id)
)
old = old.unique().scalars().all()
if len(old) != 1:
print(old)
raise HTTPException(status_code=404, detail=errors.ID_ERROR)
target = old[0]
if target.author_id != current_user.id:
raise HTTPException(status_code=403, detail=errors.OWNER_ERROR)
target.title = new_data.title
target.notes = new_data.notes
target.description = new_data.description
target.tags = ", ".join(new_data.tags)
target.location_latitude = new_data.location.latitude
target.location_longitude = new_data.location.longitude
target.location_time = new_data.location.time.replace(tzinfo=None)
target.laeq = new_data.laeq
return self._table_to_model(target)
async def get_my_measurements(
self, session: AsyncSession, current_user: User
) -> list[Measurement]:
result = await session.execute(
select(Measurements)
.filter(Measurements.author_id == current_user.id)
.order_by(desc(Measurements.location_time))
)
return [
self._table_to_model(x) for x in result.unique().scalars().all()
]
async def create_new_measurement(
self, session: AsyncSession, data: CreateMeasurement, current_user: User
) -> Measurement:
new_measurement = Measurements(
location_longitude=data.location.longitude,
location_latitude=data.location.latitude,
location_time=data.location.time.replace(tzinfo=None),
notes=data.notes,
description=data.description,
title=data.title,
laeq=data.laeq,
author_id=current_user.id,
tags=", ".join(data.tags),
)
session.add(new_measurement)
await session.flush()
await session.refresh(new_measurement)
model = self._table_to_model(new_measurement)
on_new_location.send(json.loads(model.json()))
return model
def get_router(self):
router = APIRouter()
@router.get("/", response_model=list[Measurement])
@cache(expire=120)
async def get_all_measurements(
session: AsyncSession = Depends(get_async_session),
):
"""Returns all Measurements, to be used on the map part, therefore public"""
return await self.get_all_measurements(session)
@router.get("/mine", response_model=list[Measurement])
async def get_users_measurements(
session: AsyncSession = Depends(get_async_session),
user: User = Depends(self.fastapi_users.current_user()),
):
"""Returns Measurements for the current user"""
return await self.get_my_measurements(session, user)
@router.patch(
"/{id}",
response_model=Measurement,
responses={
403: {
"model": ErrorModel,
"content": {
"application/json": {
"examples": {1: get_error(errors.OWNER_ERROR)}
}
},
},
404: {
"model": ErrorModel,
"content": {
"application/json": {
"examples": {1: get_error(errors.ID_ERROR)}
}
},
},
421: {
"model": ErrorModel,
"content": {
"application/json": {
"examples": {
1: get_error(errors.COMMA_ERROR),
}
}
},
},
500: {
"model": ErrorModel,
"content": {
"application/json": {
"examples": {1: get_error(errors.DB_ERROR)}
}
},
},
},
)
async def edit_measurement(
id: int,
new_data: UpdateMeasurement,
session: AsyncSession = Depends(get_async_session),
user: User = Depends(self.fastapi_users.current_user()),
) -> Measurement:
self._check_tags(new_data)
res = await self.update_measurements(session, id, new_data, user)
try:
await session.commit()
return res
except Exception as e:
print(e)
raise HTTPException(status_code=500, detail=errors.DB_ERROR)
@router.get(
"/{id}",
response_model=Measurement,
responses={
404: {
"model": ErrorModel,
"content": {
"application/json": {
"examples": {1: get_error(errors.ID_ERROR)}
}
},
},
},
)
async def get_one_measurement(
id: int,
session: AsyncSession = Depends(get_async_session),
) -> Measurement:
res = await self.get_one_measurement(session, id)
return res
@router.post(
"/create",
response_model=Measurement,
status_code=201,
responses={
421: {
"model": ErrorModel,
"content": {
"application/json": {
"examples": {1: get_error(errors.COMMA_ERROR)}
}
},
},
500: {
"model": ErrorModel,
"content": {
"application/json": {
"examples": {1: get_error(errors.DB_ERROR)}
}
},
},
},
)
async def add_measurement(
measurement: CreateMeasurement,
session: AsyncSession = Depends(get_async_session),
user: User = Depends(self.fastapi_users.current_user()),
) -> Measurement:
"""
Create new Measurement.
Tags must not contain `,`
"""
self._check_tags(measurement)
new_measurement = await self.create_new_measurement(
session, measurement, user
)
try:
await session.commit()
return new_measurement
except Exception as e:
print(e)
raise HTTPException(status_code=500, detail=errors.DB_ERROR)
@router.get(
"/delete/{id}",
status_code=204,
responses={
403: {
"model": ErrorModel,
"content": {
"application/json": {
"examples": {1: get_error(errors.OWNER_ERROR)}
}
},
},
404: {
"model": ErrorModel,
"content": {
"application/json": {
"examples": {1: get_error(errors.ID_ERROR)}
}
},
},
412: {
"model": ErrorModel,
"content": {
"application/json": {
"examples": {1: get_error(errors.FILES_EXIST)}
}
},
},
500: {
"model": ErrorModel,
"content": {
"application/json": {
"examples": {1: get_error(errors.DB_ERROR)}
}
},
},
},
)
async def delete_measurement(
id: int,
session: AsyncSession = Depends(get_async_session),
user: User = Depends(self.fastapi_users.current_user()),
) -> Response:
await self.delete_measurment(session, id, user)
try:
await session.commit()
return Response(status_code=204)
except Exception as e:
print(e)
raise HTTPException(status_code=500, detail=errors.DB_ERROR)
return router
| HakierGrzonzo/PBL-polsl-2022 | backend/backend/measurements.py | measurements.py | py | 13,022 | python | en | code | 3 | github-code | 1 | [
{
"api_name": "fastapi_users.fastapi_users.FastAPIUsers",
"line_number": 26,
"usage_type": "name"
},
{
"api_name": "fastapi_users.fastapi_users",
"line_number": 27,
"usage_type": "name"
},
{
"api_name": "database.Measurements",
"line_number": 30,
"usage_type": "name"
},... |
7074320791 | #!/usr/bin/env python
# coding: utf-8
# # Image_Segmentation
# ## 1. Contours
# ### Contours are continuous lines or curves that bound or cover the full-boundary of an object in an image
# In[1]:
import cv2 #importing necessary libraries
import numpy as np
# In[2]:
image=cv2.imread("2.jpg") #loading our image
# In[3]:
cv2.imshow("Input Image", image) #displaying our original image
cv2.waitKey(0)
# In[4]:
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) #displaying the grayscale-image
# In[5]:
edged=cv2.Canny(gray,30,200) #finding canny edges
cv2.imshow("Canny Edges",edged)
cv2.waitKey(0)
# In[6]:
contours,hierarchy=cv2.findContours(edged,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) #finding contours
cv2.imshow("Canny Edges after Contouring",edged)
cv2.waitKey(0)
# In[7]:
print("Number of contours found= " +str(len(contours)))
# In[8]:
cv2.drawContours(image,contours,-1,(0,255,0),3) #drawing all contours
# In[9]:
cv2.imshow("Contours",image) #displaying all contours
cv2.waitKey(0)
# In[10]:
cv2.destroyAllWindows()
# In[ ]:
| Prasad3617/IMAGE-MANIPULATIONS | Image_Segmentation.py | Image_Segmentation.py | py | 1,228 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "cv2.imread",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "cv2.imshow",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "cv2.waitKey",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "cv2.cvtColor",
"line_number": 3... |
16069403722 | import json
from qwikidata.sparql import (get_subclasses_of_item,
return_sparql_query_results)
import logging
queries_log = logging.getLogger('QUERIES')
class Queries:
@staticmethod
def query(query=None, json_path=None, log="", already_asked=False, limit=None):
if limit is not None:
query += "LIMIT"+str(limit)
if not already_asked:
res = return_sparql_query_results(query)
res = res['results']['bindings']
queryset = json.dumps(res, sort_keys=True, indent=2)
f = open(json_path, 'w')
f.write(queryset)
queries_log.warn(f"{queries_log.name}: {log}")
else:
query = open(json_path, 'r')
res = json.load(query)
queries_log.warn(f"{queries_log.name}: {log}")
return res
# CANTIDAD DE CIENTÍFICOS POR PAIS
ccbc = """
# Cantidad de científicos agrupados por países
#notas:Rusia-URSS muchas veces, como primera ocupación scientist (no se pide sub clase por que la querrá muere)
SELECT DISTINCT ?country (COUNT(distinct ?human) as ?number)
WHERE {
?human wdt:P31 wd:Q5;
(wdt:P106| wdt:P279*) wd:Q901 ;
wdt:P27 ?nationality ;
rdfs:label ?name .
?nationality rdfs:label ?country .
FILTER (lang(?name)="en")
FILTER (lang(?country)="en")
}
GROUP BY ?country
ORDER BY DESC(?number)
"""
ccbc_asked = False
@staticmethod
def get_ccbc(limit=None):
res = Queries.query(query=Queries.ccbc,
json_path="cc7220/templates/json/q1.json",
log="ccbc retrieved" if Queries.ccbc_asked else "ccbc asked",
already_asked=Queries.ccbc_asked,
limit=limit)
Queries.ccbc_asked = True
return res
# Mayores causas de muerte de los científicos = mcmc
mcmc = """
SELECT ?causes (count(?human) as ?humans)
WHERE {
?human wdt:P31 wd:Q5;
(wdt:P106|wdt:P279*) wd:Q901 ;
wdt:P1196 ?mannerOfDeath;
wdt:P509 ?causesOfDeath;
rdfs:label ?name .
?causesOfDeath rdfs:label ?causes.
?mannerOfDeath rdfs:label ?manner.
FILTER (lang(?name)="en")
FILTER (lang(?causes)="en")
FILTER (lang(?manner)="en")
}
GROUP BY ?causes
ORDER BY DESC(?humans)
"""
mcmc_asked = False
@staticmethod
def get_mcmc(limit=None):
res = Queries.query(query=Queries.mcmc,
json_path="cc7220/templates/json/q2.json",
log="mcmc retrieved" if Queries.mcmc_asked else "mcmc asked",
already_asked=Queries.mcmc_asked,
limit=limit)
Queries.mcmc_asked = True
return res
# Lista de ocupaciones científicas
loc = """
SELECT DISTINCT ?scientific_occupations
WHERE {
?occupation wdt:P31 wd:Q28640;
(wdt:P106|wdt:P279*) wd:Q901;
rdfs:label ?scientific_occupations .
FILTER(lang(?scientific_occupations)="en") .
}
ORDER BY ?scientific_occupations
"""
loc_asked = False
@staticmethod
def get_loc():
res = Queries.query(query=Queries.loc,
json_path="cc7220/templates/json/q3.json",
log="loc retrieved" if Queries.loc_asked else "loc asked",
already_asked=Queries.loc_asked)
Queries.loc_asked = True
return res
# cantidad de cientificos por campo de estudio
ccce = """SELECT ?subjectname (COUNT(?scientist) as ?count)
WHERE {
?scientist wdt:P31 wd:Q5;
(wdt:P106|wdt:P279*) wd:Q901 ;
wdt:P800 ?work;
wdt:P101 ?field .
?field rdfs:label ?fieldname .
?work wdt:P921 ?subject .
?subject wdt:P31 wd:Q11862829 ;
rdfs:label ?subjectname .
FILTER (lang(?subjectname)="en") .
FILTER (lang(?fieldname)="en") .
}
group by ?subjectname
order by desc(?count)
"""
ccce_asked = False
@staticmethod
def get_ccce(limit=None):
res = Queries.query(query=Queries.ccce,
json_path="cc7220/templates/json/q4.json",
log="ccce retrieved" if Queries.ccce_asked else "ccce asked",
already_asked=Queries.ccce_asked,
limit=limit)
Queries.ccce_asked = True
return res
#paises donde NACIERON los cientificos
pdnc = """
SELECT ?country (count(?human) as ?humans)
WHERE {
?human wdt:P31 wd:Q5;
(wdt:P106|wdt:P279*) wd:Q901 ;
wdt:P19 ?placeOfBirth;
rdfs:label ?name .
?placeOfBirth wdt:P17 ?c.
?c rdfs:label ?country.
FILTER (lang(?name)="en")
FILTER (lang(?country)="en")
}
GROUP BY ?country
ORDER BY DESC(?humans)
"""
pdnc_asked = False
@staticmethod
def get_pdnc(limit=None):
res = Queries.query(query=Queries.pdnc,
json_path="cc7220/templates/json/q5.json",
log="pdnc retrieved" if Queries.pdnc_asked else "pdnc asked",
already_asked=Queries.pdnc_asked,
limit=limit)
Queries.pdnc_asked = True
return res
# científicos en guerras
ceg = """
SELECT DISTINCT ?warname ?countryname (GROUP_CONCAT (DISTINCT ?name; SEPARATOR=", ") as ?scientists)
WHERE {
?scientist (wdt:P106|wdt:P279*) wd:Q901 ;
wdt:P607 ?war;
wdt:P27 ?country ;
rdfs:label ?name .
?war rdfs:label ?warname .
?country rdfs:label ?countryname .
FILTER (lang(?name)="en") .
FILTER (lang(?warname)="en") .
FILTER (lang(?countryname)="en") .
}
GROUP BY ?warname ?countryname
ORDER BY ?warname
"""
ceg_asked = False
@staticmethod
def get_ceg(limit=None):
res = Queries.query(query=Queries.ceg,
json_path="cc7220/templates/json/q6.json",
log="ceg retrieved" if Queries.ceg_asked else "ceg asked",
already_asked=Queries.ceg_asked,
limit=limit)
Queries.ceg_asked = True
return res
# RELIGIÓN DE LOS CIENTÍFICOS
rdlc = """
SELECT ?reg (count(?human) as ?humans)
WHERE {
?human wdt:P31 wd:Q5;
(wdt:P106|wdt:P279*) wd:Q901 ;
wdt:P140 ?religion ;
rdfs:label ?name .
?religion rdfs:label ?reg .
FILTER (lang(?name)="en")
FILTER (lang(?reg)="en")
}
GROUP BY ?reg
ORDER BY DESC(?humans)
"""
rdlc_asked = False
@staticmethod
def get_rdlc(limit=None):
res = Queries.query(query=Queries.rdlc,
json_path="cc7220/templates/json/q7.json",
log="rdlc retrieved" if Queries.rdlc_asked else "rdlc asked",
already_asked=Queries.rdlc_asked,
limit=limit)
Queries.rdlc_asked = True
return res
| lucastorrealba/CC7220 | app/cc7220/extra/queries.py | queries.py | py | 7,412 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "logging.getLogger",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "qwikidata.sparql.return_sparql_query_results",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "json.dumps",
"line_number": 17,
"usage_type": "call"
},
{
"api_name... |
34305147841 | import random as rn
import os
from art import logo2
def clear():
'''this clears the terminal'''
os.system('cls')
def number_game():
'''This is a number guessing game function'''
print(logo2)
print("Welcome to the number guessing game \nI am thinking of a number between 1 and 100")
numbers = [x for x in range(1, 101)]
computers_choice = rn.choice(numbers)
def guess():
'''The criteria for guessing the number'''
your_choice = int(input("What's the number? "))
if computers_choice == your_choice:
print(f"Psst, the number is {computers_choice}")
return True # placeholder for when the guess actually becomes true aka equal to the computer's choice
elif computers_choice > your_choice:
print(f"Too low")
return False # placeholder for when the guess is false, not necessary
else:
print(f'Too high')
return False
def easy():
'''If the difficulty is easy'''
num_choices = 10
while num_choices > 0:
print(f"You have {num_choices} chances left")
num_choices -= 1
if guess(): # if the guess function is true (return True), going back to the guess function, means the guessed number is equal to the computer's choice
print(f'Psst you guessed correctly, the random number was {computers_choice}')
return
print('Game over, you lost')
def hard():
'''If the difficulty is hard'''
num_choices = 5
for i in range(num_choices):
print(f"You have {num_choices-i} chances left") # it does 5-1,5-2,5-3, etc until it does it 5 times, which equals 0 chances left
if guess():
print(f'Psst you guessed correctly, the random number was {computers_choice}')
return # ending the loop
print('Game over, you lost')
while True:
difficulty = input('Choose your difficulty between easy and hard (or type "exit" to quit): ')
if difficulty == 'easy':
easy()
elif difficulty == 'hard':
hard()
elif difficulty == 'exit':
print('Thanks for playing!')
break
else:
print('Invalid input, please try again.')
while True:
if input("Do you want to restart the game? Type 'y' for yes and 'n' for no: ") == 'y':
clear()
number_game() # absolutely just copied this from my blackjack game, because recursion seems cool to me
else:
print('Game over')
break
number_game() | Samthesurf/Practice-and-Learn | guessing_game.py | guessing_game.py | py | 2,677 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "os.system",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "art.logo2",
"line_number": 13,
"usage_type": "argument"
},
{
"api_name": "random.choice",
"line_number": 16,
"usage_type": "call"
}
] |
15405786193 | #!/usr/bin/env python3
"""
https://adventofcode.com/2022/day/9
"""
from collections import namedtuple
from operator import add, sub
import aoc
PUZZLE = aoc.Puzzle(day=9, year=2022)
class Point(namedtuple('Point', ('x', 'y'))):
"""A point class with overridden operators"""
def __abs__(self):
return Point(*map(abs, self))
def __add__(self, right):
return Point(*map(add, self, right))
def __sub__(self, right):
return Point(*map(sub, self, right))
def __repr__(self):
return '(' + ', '.join(map(str, self)) + ')'
def unit(self):
"""Return a Point() with each attribute set to -1, 0 or 1"""
elements = []
for element in self:
sign = 0
if element > 0:
sign = 1
elif element < 0:
sign = -1
elements.append(sign)
return Point(*elements)
HEAD_DIRS = {
'U': Point(1, 0),
'D': Point(-1, 0),
'L': Point(0, -1),
'R': Point(0, 1),
}
def solve(part='a'):
"""Solve puzzle"""
count = 2
if part == 'b':
count = 10
knots = [Point(0, 0)] * count
visited = set(knots[-1:])
for line in PUZZLE.input.splitlines():
direction, count = line.split()
for _ in range(int(count)):
knots[0] = knots[0] + HEAD_DIRS[direction]
previous = knots[0]
for offset, knot in enumerate(knots[1:], 1):
diff = previous - knot
if diff.x in (-1, 0, 1) and diff.y in (-1, 0, 1):
# tail is still "touching" head
previous = knot
continue
knot = knot + diff.unit()
knots[offset] = knot
previous = knot
visited.add(knots[-1])
return len(visited)
if __name__ == "__main__":
PUZZLE.report_a(solve('a'))
PUZZLE.report_b(solve('b'))
| trosine/advent-of-code | 2022/day09.py | day09.py | py | 1,929 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "aoc.Puzzle",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "collections.namedtuple",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "operator.add",
"line_number": 20,
"usage_type": "argument"
},
{
"api_name": "operator.sub",
... |
29499148195 | from flask import render_template, url_for, flash, redirect, request, abort, jsonify, make_response
from app import app, db, bcrypt, mail
from forms import *
from models import *
from flask_login import login_user, current_user, logout_user, login_required
from routes.commonRoutes import commonTempRoute
@app.route("/supplier", methods=['GET', 'POST'])
@login_required
def suppliers():
info = commonTempRoute(Supplier, AddSuppliers())
return render_template('supplier/supplier.html', mainArray=info["mainArray"], funName='listing', mainLabel='Supplier',
formMain=info["formMain"], formLocation=info["formLocation"], formArea=info["formArea"], mainInd = 'listingInd')
@app.route("/supplier/new", methods=['POST'])
@login_required
def addSupplier():
if (request.json!=None):
if request.json.get('submit')=='supplier':
checkName = Supplier.query.filter_by(name=request.json.get('name').strip()).all()
locations = Location.query.filter_by(
numberAndStreet=request.json.get('address').strip(),
suburb=request.json.get('suburb').strip(),
state_id = request.json.get('state')).first()
if(len(checkName)>0):
return jsonify({'status':'fail','reason':'Name already taken'})
if(locations==None):
return jsonify({'status':'fail','reason':'Location has not been registered'})
if(len(request.json.get('name').strip())<1):
return jsonify({'status':'fail','reason':'Invalid Name'})
if(locations!=None and len(checkName)==0 and len(request.json.get('name').strip())>0):
location_id = locations.id
supplier = Supplier(name=request.json.get('name').strip(), location_id=location_id, contact=request.json.get('contact'), website=request.json.get('website'))
db.session.add(supplier)
db.session.commit()
return jsonify({'status':'success'})
return redirect(url_for('storage'))
else:
return jsonify({'status':'fail', 'reason':'Please try again'})
else:
return jsonify({'status':'fail', 'reason':'No data'})
@app.route("/getSupplierInfo/<int:supplier_id>", methods=['GET'])
@login_required
def getSupplierInfo(supplier_id):
info=Supplier.query.filter_by(id=supplier_id).first()
infoJson={}
infoJson["product_storage_listing"]=Product_Storage_Listing.query.filter_by(supplier_id=supplier_id).count()
infoJson["verify_product_storage_listing"]=Verify_Product_Storage_Listing.query.filter_by(supplier_id=supplier_id).count()
infoJson["id"]=info.id
infoJson["name"]=info.name
infoJson["contact"]=info.contact
infoJson["website"]=info.website
return jsonify(infoJson)
@app.route("/supplier/remove", methods=['POST'])
@login_required
def removeSupplier():
if (request.json!=None):
if request.json.get('submit')=='removeSupplier':
deleteRecord = Supplier.query.filter_by(id=request.json.get('supplier_id')).first()
if deleteRecord != None:
db.session.delete(deleteRecord)
db.session.commit()
return jsonify({"status":"success"})
return jsonify({"status":"fail"})
else:
return jsonify({'status':'fail', 'reason':'No data'})
@app.route("/supplier/edit", methods=['POST'])
@login_required
def editSupplier():
if (request.json!=None):
if request.json.get('submit')=='supplier edit':
editRecord = Supplier.query.filter_by(id=request.json.get('supplier_id')).first()
if editRecord != None:
editRecord.name=request.json.get('newName')
editRecord.contact=request.json.get('newContact')
editRecord.website=request.json.get('newWebsite')
db.session.commit()
return jsonify({"status":"success"})
return jsonify({"status":"fail"})
else:
return jsonify({'status':'fail', 'reason':'No data'})
@app.route("/supplier/area/<area_id>")
@login_required
def supplierFromArea(area_id):
supplier = Supplier.query.filter(Supplier.location.has(Location.area_id==area_id)).all()
supplierArray = []
for sup in supplier:
supObj = {}
supObj['name']=sup.name+': '+ sup.location.numberAndStreet+' '+ sup.location.suburb+' '+ sup.location.area_loc.name+' '+sup.location.state_loc.name
supObj['id']=sup.id
supplierArray.append(supObj)
return jsonify({'suppliers':supplierArray})
@app.route("/supplier/state/<state_id>")
@login_required
def supplierFromState(state_id):
supplier = Supplier.query.filter(Supplier.location.has(Location.state_id==state_id)).all()
supplierArray = []
for sup in supplier:
supObj = {}
supObj['name']=sup.name+': '+ sup.location.numberAndStreet+' '+ sup.location.suburb+' '+ sup.location.area_loc.name+' '+sup.location.state_loc.name
supObj['id']=sup.id
supplierArray.append(supObj)
return jsonify({'suppliers':supplierArray})
| alankhoangfr/NilStock_Inventory | routes/supplierRoutes.py | supplierRoutes.py | py | 5,120 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "routes.commonRoutes.commonTempRoute",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "flask.render_template",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "app.app.route",
"line_number": 10,
"usage_type": "call"
},
{
"api_name"... |
23033727735 | # gets grupy data and runs a plotting function
import matplotlib.pyplot as plt
def GruPlot( prefix, q_labels, gru_data):
fig, axes = plt.subplots(nrows=1, ncols=1)
x = []
lab = []
for i in xrange( len(q_labels) ):
lab.append( q_labels[i][1] )
x.append( q_labels[i][0] )
plt.setp(axes, xticks=x, xticklabels=lab)
plt.title(prefix, fontsize=24)
plt.ylabel(r"$\gamma$", fontsize=20, weight="bold")
for i in xrange( len(gru_data) ): # 3N columns
if i != 0:
plt.plot( gru_data[0] , gru_data[i], 'o' )
plt.show()
return 0
| alex-miller-0/grupy | Versions/1.0/grupy/GruPlot.py | GruPlot.py | py | 561 | python | en | code | 5 | github-code | 1 | [
{
"api_name": "matplotlib.pyplot.subplots",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "matplotlib.pyplot.setp",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "mat... |
4474723624 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 19:24:35 2020
@author: Scott T. Small
This module demonstrates documentation as specified by the `NumPy
Documentation HOWTO`_. Docstrings may extend over multiple lines. Sections
are created with a section header followed by an underline of equal length.
"""
import numpy as np
import allel
from itertools import combinations
from project.stat_modules import afibs
from project.stat_modules import afs
from project.stat_modules import ibs
from project.stat_modules import ld as ldfx
from project.stat_modules import popstats
from project.stat_modules import pwpopstats
class PopSumStats:
"""Calculates stats from pos/gt and msprime object."""
def __init__(self, pos=None, haparr=None, counts=None, stats=None):
self.pos = pos
self.haparr = haparr
self.counts = counts
self.stats = stats
def split_pop(self, pop_ix):
hap_p = self.haparr[pop_ix, :]
seg = hap_p.sum(axis=0).astype(int)
seg_mask = seg > 0
pos_p = self.pos[seg_mask]
hap_p = hap_p[:, seg_mask]
counts_p = hap_p.sum(axis=0).astype(int)
return hap_p, pos_p, counts_p
def pi(self):
gt = allel.HaplotypeArray(self.haparr.T)
pos = allel.SortedIndex(self.pos)
win_size = self.stats["win_size1"]
length_bp = self.stats["length_bp"]
stats_ls = []
for pop in self.stats["pop_config"]:
gtpop = gt.take(pop, axis=1)
pi_, pi_std = popstats.pi_window(pos, gtpop, win_size, length_bp)
stats_ls.extend([pi_, pi_std])
return stats_ls
def tajd(self):
gt = allel.HaplotypeArray(self.haparr.T)
pos = allel.SortedIndex(self.pos)
win_size = self.stats["win_size1"]
length_bp = self.stats["length_bp"]
stats_ls = []
for pop in self.stats["pop_config"]:
gtpop = gt.take(pop, axis=1)
tajd_, tajd_std = popstats.tajimaD(pos, gtpop, win_size, length_bp)
stats_ls.extend([tajd_, tajd_std])
return stats_ls
def classic(self):
stats_ls = []
for p in self.stats["pop_config"]:
hap_p, pos_p, counts_p = self.split_pop(p)
het_, pi_, tajd_ = popstats.classical_stats(len(p), counts_p)
stats_ls.extend([het_, pi_, tajd_])
return stats_ls
def hap_het(self):
win_size = self.stats["win_size1"]
length_bp = self.stats["length_bp"]
stats_ls = []
for p in self.stats["pop_config"]:
hap_p, pos_p, counts_p = self.split_pop(p)
res_hh = popstats.haplo_win(pos_p, hap_p, win_size, length_bp)
stats_ls.extend(res_hh) # het_win, het_win_std
return stats_ls
def spatial_sfs(self):
stats_ls = []
fold = self.stats["spat_fold"]
for p in self.stats["pop_config"]:
hap_p, pos_p, counts_p = self.split_pop(p)
n_haplo = len(p)
spat_ = afs.spatial_histo_fast(pos_p, counts_p, n_haplo-1)
if fold:
spat_flip = np.flip(spat_, axis=0)
spat_fold = (spat_flip + spat_)
haps = int(len(p)/2)
spat_fold = spat_fold[0:haps]
spat_ = spat_fold
stats_ls.extend(spat_)
return stats_ls
def afibs(self, durbin=True):
stats_ls = []
fold = self.stats["afibs_fold"]
for p in self.stats["pop_config"]:
hap_p, pos_p, counts_p = self.split_pop(p)
res_afibs = afibs.distrib_afibs(hap_p, pos_p, counts_p, durbin)
afibs_m = res_afibs[::2] # mean afibs
afibs_std = res_afibs[1::2] # afibs_std
if fold:
for a in [afibs_m, afibs_std]:
afibs_flip = np.flip(a, axis=0)
afibs_fold = (afibs_flip + a)
haps = int(len(p)/2)
stats_ls.extend(afibs_fold[0:haps])
else:
stats_ls.extend(afibs_m) # mean afibs
stats_ls.extend(afibs_std) # afibs_std
return stats_ls
def ibs(self, moments=False):
dmax = self.stats["length_bp"]
size = self.stats["ibs_params"][1]
prob = self.stats["ibs_params"][0]
stats_ls = []
for m in size:
if moments:
for p in self.stats["pop_config"]:
hap_p, pos_p, counts_p = self.split_pop(p)
res_ibs = ibs.ibs_quantiles_from_data(m, pos_p, hap_p, prob, dmax, moments=True)
stats_ls.extend(res_ibs) # mean, variance, skewness, kurtosis
else:
for p in self.stats["pop_config"]:
hap_p, pos_p, counts_p = self.split_pop(p)
res_ibs = ibs.ibs_quantiles_from_data(m, pos_p, hap_p, prob, dmax)
stats_ls.extend(res_ibs)
# dict(zip(size_list, [ss.ibs_quantiles_from_data(size, self.pos, 1, self.haparr, prob, dmax, quantiles=False, moments=True) for size in size_list]))
# pd_ibs_mom = pd.DataFrame(res_ibs_mom, index=['mean', 'variance', 'skewness', 'kurtosis'])
return stats_ls
def ld(self):
stats_ls = []
intervals = self.stats["ld_params"]
for p in self.stats["pop_config"]:
hap_p, pos_p, counts_p = self.split_pop(p)
#pw_ld = ldfx.distrib_r2(pos_p, hap_p, intervals) # Boitard 2015 r2
pw_ld = ldfx.ld_pop_mp(pos_p, hap_p, intervals) # momentsLD 100 snps
#pw_ld3 = ldfx.ld_pop_mb(pos_p, hap_p, intervals) # momentsLD + Boitard 2015 selection
#pw_ld2 = ldfx.ld_pop_complete(pos_p, hap_p, intervals) # momentsLD pw-all very slow
stats_ls.extend(pw_ld)
return stats_ls
def sfs(self, fold=False):
fold = self.stats["sfs_fold"]
gt = allel.HaplotypeArray(self.haparr.T)
pos = allel.SortedIndex(self.pos)
stats_ls = []
for pop in self.stats["pop_config"]:
gtpop = gt.take(pop, axis=1)
sfs = afs.asfs_stats(gtpop, pos, fold)
stats_ls.extend(sfs)
return stats_ls
def jsfs(self, fold=False):
gt = allel.HaplotypeArray(self.haparr.T)
pos = allel.SortedIndex(self.pos)
stats_ls = []
for p1, p2 in combinations(self.stats["pop_config"], 2):
gtpops = gt.take(p1+p2, axis=1)
props = afs.jsfs_stats(len(p1), gtpops, pos, fold)
stats_ls.extend(props)
return stats_ls
def delta_tajD(self):
gt = allel.HaplotypeArray(self.haparr.T)
pos = allel.SortedIndex(self.pos)
win_size = self.stats["win_size1"]
length_bp = self.stats["length_bp"]
quants = self.stats["pw_quants"]
stats_ls = []
for p1, p2 in combinations(self.stats["pop_config"], 2):
gtpops = gt.take(p1+p2, axis=1)
flt = pwpopstats.d_tajD(len(p1), pos, gtpops, win_size, length_bp, quants)
stats_ls.extend(flt)
return stats_ls
def ld_2pop(self, D=0):
# ld_pop2_avg(p1, gt, pos, win_size, length_bp, ld, maf=0.05)
# D2 = 0; Dz = 1; pi2 = 2
quants = self.stats["pw_quants"]
stats_ls = []
for p1, p2 in combinations(self.stats["pop_config"], 2):
hap_p, pos_p, counts_p = self.split_pop(p1+p2)
pw_ld = ldfx.ld_pop2(len(p1), pos_p, hap_p, quants)
stats_ls.extend(pw_ld)
return stats_ls
def ld_2pop_win(self, D=0):
# D2 = 0; Dz = 1; pi2 = 2
win_size = self.stats["win_size2"]
length_bp = self.stats["length_bp"]
stats_ls = []
for p1, p2 in combinations(self.stats["pop_config"], 2):
hap_p, pos_p, counts_p = self.split_pop(p1+p2)
pw_ld = ldfx.ld_pop2_win(len(p1), pos_p, hap_p, win_size, length_bp)
stats_ls.extend(pw_ld)
return stats_ls
def FST(self):
gt = allel.HaplotypeArray(self.haparr.T)
pos = allel.SortedIndex(self.pos)
quants = self.stats["pw_quants"]
stats_ls = []
for p1, p2 in combinations(self.stats["pop_config"], 2):
gtpops = gt.take(p1+p2, axis=1)
flt = pwpopstats.fst(len(p1), pos, gtpops, quants)
try:
stats_ls.extend(flt)
except TypeError:
flt = [np.nan]*len(quants)
stats_ls.extend(flt)
return stats_ls
def dXY(self):
gt = allel.HaplotypeArray(self.haparr.T)
pos = allel.SortedIndex(self.pos)
quants = self.stats["pw_quants"]
win_size = self.stats["win_size2"]
length_bp = self.stats["length_bp"]
stats_ls = []
for p1, p2 in combinations(self.stats["pop_config"], 2):
gtpops = gt.take(p1+p2, axis=1)
flt = pwpopstats.dxy(len(p1), pos, gtpops, win_size, length_bp)
if quants[0] < 0:
dxy_ = [np.nanmean(flt)]
else:
dxy_ = np.nanquantile(flt, quants)
stats_ls.extend(dxy_)
return stats_ls
def dmin(self):
gt = allel.HaplotypeArray(self.haparr.T)
pos = allel.SortedIndex(self.pos)
quants = self.stats["pw_quants"]
win_size = self.stats["win_size2"]
length_bp = self.stats["length_bp"]
stats_ls = []
for p1, p2 in combinations(self.stats["pop_config"], 2):
gtpops = gt.take(p1+p2, axis=1)
flt = pwpopstats.dmin(len(p1), pos, gtpops, win_size, length_bp)
if quants[0] < 0:
dminq = [np.nanmean(flt)]
else:
dminq = np.nanquantile(flt, quants)
stats_ls.extend(dminq)
return stats_ls
def gmin(self):
gt = allel.HaplotypeArray(self.haparr.T)
pos = allel.SortedIndex(self.pos)
quants = self.stats["pw_quants"]
win_size = self.stats["win_size2"]
length_bp = self.stats["length_bp"]
stats_ls = []
for p1, p2 in combinations(self.stats["pop_config"], 2):
gtpops = gt.take(p1+p2, axis=1)
flt = pwpopstats.gmin(len(p1), pos, gtpops, win_size, length_bp, quants)
stats_ls.extend(flt)
return stats_ls
def dd12(self):
gt = allel.HaplotypeArray(self.haparr.T)
pos = allel.SortedIndex(self.pos)
quants = self.stats["pw_quants"]
win_size = self.stats["win_size2"]
length_bp = self.stats["length_bp"]
stats_ls = []
for p1, p2 in combinations(self.stats["pop_config"], 2):
gtpops = gt.take(p1+p2, axis=1)
flt = pwpopstats.dd1_2(len(p1), pos, gtpops, win_size, length_bp, quants)
stats_ls.extend(flt) # 2 values returned as list [dd1, dd2]
return stats_ls
def ddRank12(self):
gt = allel.HaplotypeArray(self.haparr.T)
pos = allel.SortedIndex(self.pos)
quants = self.stats["pw_quants"]
win_size = self.stats["win_size2"]
length_bp = self.stats["length_bp"]
stats_ls = []
for p1, p2 in combinations(self.stats["pop_config"], 2):
gtpops = gt.take(p1+p2, axis=1)
flt = pwpopstats.ddRank1_2(len(p1), pos, gtpops, win_size, length_bp, quants)
stats_ls.extend(flt) # 2 values returned as list [dd1, dd2]
return stats_ls
def Zx(self):
win_size = self.stats["win_size2"]
quants = self.stats["pw_quants"]
length_bp = self.stats["length_bp"]
stats_ls = []
stats_ls = []
for p1, p2 in combinations(self.stats["pop_config"], 2):
hap_p, pos_p, counts_p = self.split_pop(p1+p2)
flt = pwpopstats.zx(len(p1), pos_p, hap_p, win_size, length_bp, quants)
stats_ls.extend(flt)
return stats_ls
def IBS_maxXY(self):
stats_ls = []
length_bp = self.stats["length_bp"]
for p1, p2 in combinations(self.stats["pop_config"], 2):
hap_p, pos_p, counts_p = self.split_pop(p1+p2)
flt = pwpopstats.ibs_maxxy(len(p1), pos_p, hap_p, length_bp)
stats_ls.append(flt)
return stats_ls
| stsmall/abc_scripts2 | project/stat_modules/sumstats.py | sumstats.py | py | 12,274 | python | en | code | 3 | github-code | 1 | [
{
"api_name": "allel.HaplotypeArray",
"line_number": 43,
"usage_type": "call"
},
{
"api_name": "allel.SortedIndex",
"line_number": 44,
"usage_type": "call"
},
{
"api_name": "project.stat_modules.popstats.pi_window",
"line_number": 50,
"usage_type": "call"
},
{
"ap... |
30675767566 | from .values import *
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
def setParagraphType(paragraph):
if paragraph[:7].upper() == CHAPTER_TEXT:
type = CHAPTER_TEXT
elif paragraph[:10].upper() == DEDICATION_TEXT:
type = EXTRA_SECTION
elif paragraph[:14].upper() == ACKNOWLEDGMENT_TEXT:
type = EXTRA_SECTION
elif paragraph[:9].upper() == BIOGRAPHY_TEXT:
type = EXTRA_SECTION
elif paragraph[:16].upper() == ABOUT_THE_AUTHOR_TEXT:
type = EXTRA_SECTION
elif paragraph[:4].upper() == PART_TEXT:
type = PART_TEXT
elif paragraph[:3] == SCENE_BREAK_1:
type = SCENE_BREAK_1
elif paragraph[:3] == SCENE_BREAK_2:
type = SCENE_BREAK_2
else:
type = PARAGRAPH
return type
def setHalfTitleFormat(document, dataFromHtml):
paragraphWrite = document.add_paragraph(dataFromHtml.bookTitle)
paragraphWrite.style = document.styles['Book Title']
document.add_section()
document.add_section()
def setTitleFormat(document, dataFromHtml):
paragraphWrite = document.add_paragraph(dataFromHtml.bookTitle)
paragraphWrite.style = document.styles['Book Title']
paragraphWrite2 = document.add_paragraph(dataFromHtml.bookSubTitle)
paragraphWrite2.style = document.styles['Book Subtitle']
document.add_paragraph('')
document.add_paragraph('')
document.add_paragraph('')
document.add_paragraph('')
document.add_paragraph('')
document.add_paragraph('')
paragraphWrite3 = document.add_paragraph(dataFromHtml.author.upper())
paragraphWrite3.style = document.styles['Author']
document.add_section()
def setCopyrightFormat(document, dataFromHtml):
i= 0
while i <= 22:
document.add_paragraph('')
i = i + 1
paragraphWrite = document.add_paragraph(dataFromHtml.bookTitle +' by ' + dataFromHtml.author)
paragraphWrite.style = document.styles['Copyright']
paragraphWrite = document.add_paragraph('Copyright© 2022 ' + dataFromHtml.author)
paragraphWrite.style = document.styles['Copyright']
paragraphWrite = document.add_paragraph(COPYRIGHT_TEXT)
paragraphWrite.style = document.styles['Copyright']
paragraphWrite = document.add_paragraph('ISBN: XXXX-XXXX')
paragraphWrite.style = document.styles['Copyright']
document.add_section()
def setPartFormat(document, paragraphRead):
paragraphWrite = document.add_paragraph(paragraphRead)
paragraphWrite.style = document.styles['Part']
def setChapterTitleFormat(document, paragraphRead, isPreviousAPart):
paragraphWrite = document.add_paragraph(paragraphRead)
paragraphWrite.style = document.styles['Chapter Title']
paragraph_format = paragraphWrite.paragraph_format
if isPreviousAPart:
paragraph_format.space_before = Pt(45)
else:
paragraph_format.space_before = Pt(70)
paragraph_format.space_after = Pt(20)
paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
paragraph_format.line_spacing = 1
def setChapterDescriptionFormat(document, paragraphRead):
paragraphWrite = document.add_paragraph(paragraphRead)
paragraphWrite.style = document.styles['Chapter Description']
paragraphWrite.style.paragraph_format.line_spacing = 1
paragraph_format = paragraphWrite.paragraph_format
paragraph_format.space_before = Pt(10)
paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
paragraph_format.right_indent = Inches(0.7)
paragraph_format.left_indent = Inches(0.7)
def setParagraphFormat(document, paragraphRead, indentFirstLine, paragrapghReadNext, chapterDescription, previousTitle, data):
paragraphWrite = document.add_paragraph(paragraphRead)
if (chapterDescription):
paragraphWrite.style = document.styles['Chapter Description']
else:
if data.PublishOrEdit == 'toEdit':
paragraphWrite.style = document.styles['Paragraph Editor']
font = paragraphWrite.style.font
font.size = Pt(12)
else:
paragraphWrite.style = document.styles['Paragraph']
font = paragraphWrite.style.font
font.size = Pt(11)
paragraph_format = paragraphWrite.paragraph_format
paragraph_format.keep_together = keep_together
if indentFirstLine:
paragraph_format.first_line_indent = Pt(18)
typeNextParagraph = setParagraphType(paragrapghReadNext)
if (typeNextParagraph == PART_TEXT or typeNextParagraph == CHAPTER_TEXT or typeNextParagraph == EXTRA_SECTION) :
if previousTitle == EXTRA_SECTION:
document.add_section()
document.add_section()
else:
document.add_section()
def setSceneBreakFormat(document, paragraph):
paragraphWrite = document.add_paragraph(paragraph)
paragraphWrite.style = document.styles['Scene Break']
def setSectionFormat(document, dataFromHtml, doc):
section = document.sections[0]
#paragraphsCount = len(doc.paragraphs)
#paragraphReadChapterCount = 0
#countWords = 0
#while paragraphReadChapterCount < paragraphsCount:
# paragraphRead = doc.paragraphs[paragraphReadChapterCount].text.strip()
# count = paragraphRead.split(" ")
# countWords = countWords + len(count)
#paragraphReadChapterCount = paragraphReadChapterCount + 1
countWords = 100000
if dataFromHtml.PageSize == '5" x 8" (12.7 x 20.32 cm)':
section.page_width = Inches(5)
section.page_height = Inches(8)
elif dataFromHtml.PageSize == '5.25" x 8"(13.34 x 20.32 cm)':
section.page_width = Inches(5.25)
section.page_height = Inches(8)
elif dataFromHtml.PageSize =='5.5" x 8.5"(13.97 x 21.59 cm)':
section.page_width = Inches(5.5)
section.page_height = Inches(8.5)
elif dataFromHtml.PageSize == '6" x 9" (15.24 x 22.86 cm)':
section.page_width = Inches(6)
section.page_height = Inches(9)
elif dataFromHtml.PageSize == '7" x 10" x (17.78 x 25.4 cm)':
section.page_width = Inches(7)
section.page_height = Inches(10)
elif dataFromHtml.PageSize == '8" x 10" (20.32 x 25.4 cm)':
section.page_width = Inches(8)
section.page_height = Inches(10)
elif dataFromHtml.PageSize == 'Letter 8.5" x 11" (21,59 x 27,94 cm)':
section.page_width = Inches(8.5)
section.page_height = Inches(11)
elif dataFromHtml.PageSize == 'A4 8.27" x 11.69" (21 x 29,7 cm)':
section.page_width = Inches(8.27)
section.page_height = Inches(11.69)
section.top_margin = Inches(0.8)
section.bottom_margin = Inches(0.8)
if dataFromHtml.PublishOrEdit == 'toEdit':
section.left_margin = Inches(1)
section.right_margin = Inches(1)
else:
section.right_margin = Inches(0.3)
pageCount = countWords/250
if pageCount < 150:
marginCalc = 0.375
elif pageCount < 300:
marginCalc = 0.5
elif pageCount < 500:
marginCalc = 0.625
elif pageCount < 700:
marginCalc = 0.75
elif pageCount < 828:
marginCalc = 0.875
else:
marginCalc = 0.875
margin = 0.375
if margin > marginCalc:
section.left_margin = Inches(margin)
else:
section.left_margin = Inches(marginCalc)
section.different_first_page_header_footer = True
document.settings.odd_and_even_pages_header_footer = True
header = section.header
#footer = section.footer
evenHeader = section.even_page_header
evenFooter = section.even_page_footer
header.is_linked_to_previous = False
textHeader = header.paragraphs[0]
textHeader.text = dataFromHtml.bookTitle.upper()
textEvenHeader = evenHeader.paragraphs[0]
textEvenHeader.text = dataFromHtml.author.upper()
| Cristian-G-P/Writer-Apps | Flask-Web-App-Tutorial-main/website/callistoAuxFunctions.py | callistoAuxFunctions.py | py | 7,872 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "docx.shared.Pt",
"line_number": 87,
"usage_type": "call"
},
{
"api_name": "docx.shared.Pt",
"line_number": 89,
"usage_type": "call"
},
{
"api_name": "docx.shared.Pt",
"line_number": 91,
"usage_type": "call"
},
{
"api_name": "docx.enum.text.WD_PARAGR... |
22549796737 | from PIL import Image
import PIL.ImageOps
from shutil import move
def alpha_channel_upscale(inpath, outpath, workingImage, settings):
"""Opens the current working image as well as the original image, resizes (BICUBIC) the original image and copies the alpha channel"""
originalImage = Image.open(workingImage.originalPath)
if originalImage.mode != 'RGBA':
# No alpha channel existed in the original image, so no need to do anything
# Move the file to the outpath
move(inpath, outpath)
return True
currentImage = Image.open(inpath)
resizedImage = originalImage.resize(currentImage.size, Image.BICUBIC)
# Extract the alpha channel
alpha = resizedImage.split()[-1]
currentImage.putalpha(alpha)
currentImage.save(outpath, 'PNG')
return True
| RainbowRedux/TextureUpscalingPipeline | TextureUpscaler/AlphaChannelUpscale.py | AlphaChannelUpscale.py | py | 833 | python | en | code | 5 | github-code | 1 | [
{
"api_name": "PIL.Image.open",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "PIL.Image",
"line_number": 7,
"usage_type": "name"
},
{
"api_name": "shutil.move",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "PIL.Image.open",
"line_number"... |
73587061154 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 26 2017
Description:
Input: symbols of chosen stocks
Randomly assign weights to given stocks.
Calculate portfolio return, volatility, and Sharp Ratio.
Output: portfolio with maximum SR or minimum volatility
@author: chenkai
"""
import numpy as np
import pandas as pd
import pandas_datareader.data as web
import matplotlib.pyplot as plt
#list of stocks in portfolio, i.e. stocks = ['AAPL','AMZN','MSFT','YHOO']
my_position = pd.read_csv('/Users/chenkai/Documents/Financial Analysis/cqa_challenge/OpenPosition_11_26_2017.csv')
stocks = my_position['Symbol']
#download daily price data for each of the stocks in the portfolio
data = web.DataReader(stocks,data_source='google',start='01/01/2010')['Close']
#convert daily stock prices into daily returns
returns = data.pct_change()
#calculate mean daily return and covariance of daily returns
mean_daily_returns = returns.mean()
cov_matrix = returns.cov()
#set number of runs of random portfolio weights
num_portfolios = 25000
#set up array to hold results
#We have increased the size of the array to hold the weight values for each stock
results = np.zeros((4+len(stocks)-1,num_portfolios))
for i in range(num_portfolios):
#select random weights for portfolio holdings
weights = np.array(np.random.random(len(stocks)))
#rebalance weights to sum to 1
weights /= np.sum(weights)
#calculate portfolio return and volatility
portfolio_return = np.sum(mean_daily_returns * weights) * 250
portfolio_std_dev = np.sqrt(np.dot(weights.T,np.dot(cov_matrix, weights))) * np.sqrt(250)
#store results in results array
results[0,i] = portfolio_return
results[1,i] = portfolio_std_dev
#store Sharpe Ratio (return / volatility) - risk free rate element excluded for simplicity
results[2,i] = results[0,i] / results[1,i]
#iterate through the weight vector and add data to results array
for j in range(len(weights)):
results[j+3,i] = weights[j]
#convert results array to Pandas DataFrame
results_frame = pd.DataFrame(results.T)
result_list = pd.Series(['ret','stdev','sharpe'])
result_list = result_list.append(stocks)
result_list = result_list.reset_index(drop=True)
results_frame.rename(columns=result_list,inplace=True)
#locate position of portfolio with highest Sharpe Ratio
max_sharpe_port = results_frame.iloc[results_frame['sharpe'].idxmax()]
#locate positon of portfolio with minimum standard deviation
min_vol_port = results_frame.iloc[results_frame['stdev'].idxmin()]
#create scatter plot coloured by Sharpe Ratio
plt.scatter(results_frame.stdev,results_frame.ret,c=results_frame.sharpe,cmap='RdYlBu')
plt.xlabel('Volatility')
plt.ylabel('Returns')
plt.colorbar()
#plot red star to highlight position of portfolio with highest Sharpe Ratio
plt.scatter(max_sharpe_port[1],max_sharpe_port[0],marker=(5,1,0),color='r',s=1000)
#plot green star to highlight position of minimum variance portfolio
plt.scatter(min_vol_port[1],min_vol_port[0],marker=(5,1,0),color='g',s=1000) | chenkai0208/Quantitative_Finance_in_Python | portfolio_optimization.py | portfolio_optimization.py | py | 3,072 | python | en | code | 3 | github-code | 1 | [
{
"api_name": "pandas.read_csv",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "pandas_datareader.data.DataReader",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "pandas_datareader.data",
"line_number": 25,
"usage_type": "name"
},
{
"api_name... |
18187098239 | import re
import sqlite3
import os
import glob
import datetime as dt
import bokeh.models
import xarray
import numpy as np
from functools import lru_cache
from forest.exceptions import FileNotFound, IndexNotFound
from forest.old_state import old_state, unique
import forest.util
import forest.map_view
from forest import geo, locate
ENGINE = "h5netcdf"
MIN_DATETIME64 = np.datetime64("0001-01-01T00:00:00.000000")
def _natargmax(arr):
"""Find the arg max when an array contains NaT's"""
no_nats = np.where(np.isnat(arr), MIN_DATETIME64, arr)
return np.argmax(no_nats)
class Dataset:
def __init__(self, pattern=None, database_path=None, minutes=15, **kwargs):
self.pattern = pattern
if database_path is None:
database_path = ":memory:"
self.database = Database(database_path)
self.locator = Locator(self.pattern, self.database, minutes=minutes)
def navigator(self):
return Navigator(self.locator, self.database)
def map_view(self, color_mapper):
loader = Loader(self.locator)
return forest.map_view.map_view(
loader, color_mapper, use_hover_tool=False
)
class Database:
"""Meta-data store for EIDA50 dataset"""
def __init__(self, path=":memory:"):
self.fmt = "%Y-%m-%d %H:%M:%S"
self.path = path
self.connection = sqlite3.connect(self.path)
self.cursor = self.connection.cursor()
# Schema
query = """
CREATE TABLE IF NOT EXISTS file (
id INTEGER PRIMARY KEY,
path TEXT,
UNIQUE(path));
"""
self.cursor.execute(query)
query = """
CREATE TABLE IF NOT EXISTS time (
id INTEGER PRIMARY KEY,
time TEXT,
file_id INTEGER,
FOREIGN KEY(file_id) REFERENCES file(id));
"""
self.cursor.execute(query)
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(self):
"""Close connection gracefully"""
self.connection.commit()
self.connection.close()
def insert_times(self, times, path):
"""Store times"""
# Update file table
query = """
INSERT OR IGNORE INTO file (path) VALUES (:path);
"""
self.cursor.execute(query, {"path": path})
self.connection.commit()
# Update time table
query = """
INSERT INTO time (time, file_id)
VALUES (:time, (SELECT id FROM file WHERE path = :path));
"""
texts = [time.strftime(self.fmt) for time in times]
args = [{"path": path, "time": text} for text in texts]
self.cursor.executemany(query, args)
self.connection.commit()
def fetch_times(self, path=None):
"""Retrieve times"""
if path is None:
query = """
SELECT time
FROM time;
"""
rows = self.cursor.execute(query)
else:
query = """
SELECT time.time
FROM time
JOIN file
ON file.id = time.file_id
WHERE file.path = :path;
"""
rows = self.cursor.execute(query, {"path": path})
rows = self.cursor.fetchall()
texts = [text for text, in rows]
times = [dt.datetime.strptime(text, self.fmt) for text in texts]
return list(sorted(times))
def fetch_paths(self):
"""Retrieve paths"""
query = """
SELECT path FROM file;
"""
rows = self.cursor.execute(query).fetchall()
texts = [text for text, in rows]
return list(sorted(texts))
class Locator:
"""Locate EIDA50 satellite images"""
def __init__(self, pattern, database, minutes=15):
self.minutes = minutes
self.pattern = pattern
self._glob = forest.util.cached_glob(
dt.timedelta(minutes=self.minutes)
)
self.database = database
def all_times(self, paths):
"""All available times"""
# Parse times from file names not in database
unparsed_paths = []
filename_times = []
database_paths = set(self.database.fetch_paths())
for path in paths:
if path in database_paths:
continue
time = self.parse_date(path)
if time is None:
unparsed_paths.append(path)
continue
filename_times.append(time)
# Store unparsed files in database
for path in unparsed_paths:
times = self.load_time_axis(path) # datetime64[s]
self.database.insert_times(times.astype(dt.datetime), path)
# All recorded times
database_times = self.database.fetch_times()
# Combine database/timestamp information
arrays = [
np.array(database_times, dtype="datetime64[s]"),
np.array(filename_times, dtype="datetime64[s]"),
]
return np.unique(np.concatenate(arrays))
def find(self, paths, date):
"""Find file and index related to date
.. note:: Find should not write to disk
"""
# Search file system
path = self.find_file(paths, date)
# Load times from database
if path in self.database.fetch_paths():
times = self.database.fetch_times(path)
times = np.array(times, dtype="datetime64[s]")
else:
times = self.load_time_axis(path) # datetime64[s]
index = self.find_index(
times, date, dt.timedelta(minutes=self.minutes)
)
return path, index
def glob(self):
return self._glob(self.pattern)
@staticmethod
@lru_cache()
def load_time_axis(path):
with xarray.open_dataset(path, engine=ENGINE) as nc:
values = nc["time"]
return np.array(values, dtype="datetime64[s]")
def find_file(self, paths, user_date):
""" "Find file likely to contain user supplied date
.. note:: Search based on timestamp only
.. warning:: Not suitable for searching unparsable file names
"""
if isinstance(user_date, (dt.datetime, str)):
user_date = np.datetime64(user_date, "s")
dates = np.array(
[self.parse_date(path) for path in paths], dtype="datetime64[s]"
)
mask = ~(dates <= user_date)
if mask.all():
msg = "No file for {}".format(user_date)
raise FileNotFound(msg)
before_dates = np.ma.array(dates, mask=mask, dtype="datetime64[s]")
i = _natargmax(before_dates.filled())
return paths[i]
@staticmethod
def find_index(times, time, length):
"""Search for index inside array of datetime64[s] values"""
print(f"FIND_INDEX: {times} {time} {length}")
dtype = "datetime64[s]"
if isinstance(times, list):
times = np.asarray(times, dtype=dtype)
if isinstance(time, (dt.datetime, str)):
time = np.datetime64(time, "s")
bounds = locate.bounds(times, length)
inside = locate.in_bounds(bounds, time)
valid_times = np.ma.array(times, mask=~inside)
if valid_times.mask.all():
msg = "{}: not found".format(time)
raise IndexNotFound(msg)
return _natargmax(valid_times.filled())
@staticmethod
def parse_date(path):
"""Parse timestamp into datetime or None"""
for regex, fmt in [
(r"([0-9]{8})\.nc", "%Y%m%d"),
(r"([0-9]{8}T[0-9]{4}Z)\.nc", "%Y%m%dT%H%MZ"),
]:
groups = re.search(regex, path)
if groups is None:
continue
else:
return dt.datetime.strptime(groups[1], fmt)
class Loader:
def __init__(self, locator):
self.locator = locator
self.empty_image = {"x": [], "y": [], "dw": [], "dh": [], "image": []}
self.cache = {}
paths = self.locator.glob()
if len(paths) > 0:
with xarray.open_dataset(paths[-1], engine=ENGINE) as nc:
self.cache["longitude"] = nc["longitude"].values
self.cache["latitude"] = nc["latitude"].values
@property
def longitudes(self):
return self.cache["longitude"]
@property
def latitudes(self):
return self.cache["latitude"]
def image(self, state):
if state.valid_time is None:
data = self.empty_image
else:
try:
data = self._image(forest.util.to_datetime(state.valid_time))
except (FileNotFound, IndexNotFound) as e:
print(f"EIDA50: {e}")
data = self.empty_image
return data
def _image(self, valid_time):
paths = self.locator.glob()
path, itime = self.locator.find(paths, valid_time)
return self.load_image(path, itime)
def load_image(self, path, itime):
lons = self.longitudes
lats = self.latitudes
with xarray.open_dataset(path, engine=ENGINE) as nc:
values = nc["data"][itime].values
# Use datashader to coarsify images from 4.4km to 8.8km grid
scale = 2
return geo.stretch_image(
lons,
lats,
values,
plot_width=int(values.shape[1] / scale),
plot_height=int(values.shape[0] / scale),
)
class Navigator:
"""Facade to map Navigator API to Locator"""
def __init__(self, locator, database):
self.locator = locator
self.database = database
def __call__(self, store, action):
"""Middleware interface"""
import forest.db.control
kind = action["kind"]
if kind == forest.db.control.SET_VALUE:
key, time = (action["payload"]["key"], action["payload"]["value"])
if key == "valid_time":
# Detect missing file
paths = self.locator.glob()
path = self.locator.find_file(paths, time)
if path not in self.database.fetch_paths():
times = self.locator.load_time_axis(path) # datetime64[s]
self.database.insert_times(times.astype(dt.datetime), path)
# Update stale state
store_times = store.state.get("valid_times", [])
database_times = self._times()
if len(store_times) != len(database_times):
yield forest.db.control.set_value(
"valid_times", database_times
)
yield action
def variables(self, pattern):
return ["EIDA50"]
def initial_times(self, pattern, variable):
return [dt.datetime(1970, 1, 1)]
def valid_times(self, pattern, variable, initial_time):
"""Get available times given application state"""
return self._times()
def _times(self):
"""Get available times given user selected valid_time
:param valid_time: application state valid time
"""
paths = self.locator.glob()
datetimes = self.locator.all_times(paths)
return np.array(datetimes, dtype="datetime64[s]")
def pressures(self, pattern, variable, initial_time):
return []
| MetOffice/forest | forest/drivers/eida50.py | eida50.py | py | 11,480 | python | en | code | 38 | github-code | 1 | [
{
"api_name": "numpy.datetime64",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "numpy.where",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "numpy.isnat",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "numpy.argmax",
"line_num... |
23670216784 | import pandas as pd, numpy as np
import re
import pickle
dataset = pd.read_csv("Restaurant_Reviews.csv")
dataset['Review']
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
corpus = []
for i in range(0, 1000):
review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i])
review = review.lower()
review = review.split()
ps = PorterStemmer()
all_stopwords = stopwords.words('english')
all_stopwords.remove('not')
review = [ps.stem(word) for word in review if not word in set(all_stopwords)]
review = ' '.join(review)
corpus.append(review)
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features = 1500)
X = cv.fit_transform(corpus).toarray()
y = dataset.iloc[:, -1].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.30, random_state=42)
# Creating a pickle file for the CountVectorizer
pickle.dump(cv, open('cv-transform.pkl', 'wb'))
from sklearn.naive_bayes import MultinomialNB
classifier = MultinomialNB(alpha=0.2)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))
from sklearn.metrics import confusion_matrix, accuracy_score
cm = confusion_matrix(y_test, y_pred)
print(cm)
accuracy_score(y_test, y_pred)
pickle.dump(classifier,open('model.pkl','wb'))
| MM1026-DS/Ml-web-nlp-app | app_1.py | app_1.py | py | 1,549 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "pandas.read_csv",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "nltk.download",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "re.sub",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "nltk.stem.porter.PorterStemmer",
... |
23015193717 | from dataclasses import field
from rest_framework import serializers
from django.contrib.auth import get_user_model
import requests
import json
from apps.core.models import UserRole
from apps.core.serializers import MyAccountSerializer, UserAppointment, UserSerializer
from apps.profiles.serializers import CounsellorProfileSerializer, ListCounsellorProfileSerializer
from .models import *
from zoom_api_functions import generateToken
# UserRole = get_user_model()
class AppointmentRequestSerializer(serializers.ModelSerializer):
class Meta:
model = AppointmentRequest
fields = '__all__'
class ListAppointmentRequestSerializer(serializers.ModelSerializer):
requested_by = MyAccountSerializer()
# counsellor =
class Meta:
model = AppointmentRequest
fields = '__all__'
class CreateAppointmentSerializer(serializers.ModelSerializer):
appointment_meeting = serializers.ReadOnlyField()
class Meta:
model = Appointment
fields = '__all__'
class ListAppointmentSerializer(serializers.ModelSerializer):
class Meta:
model = Appointment
fields = '__all__'
class AppointmentDetailsSerializer(serializers.ModelSerializer):
user = MyAccountSerializer(read_only=True)
counsellor = ListCounsellorProfileSerializer(read_only=True)
class Meta:
model = Appointment
fields = '__all__'
class LiveMeetingSerializer(serializers.ModelSerializer):
zoom_meeting = serializers.ReadOnlyField()
status = serializers.ReadOnlyField(default='upcoming')
api_url = serializers.ReadOnlyField(required=False)
start_meeting_url = serializers.ReadOnlyField(required=False)
invitation_url = serializers.ReadOnlyField(source='get_meeting_invitation')
class Meta:
model = AppointmentMeeting
fields = '__all__'
class GetAppointmentMeetingSerializer(serializers.ModelSerializer):
zoom_meeting = serializers.SerializerMethodField()
status = serializers.ReadOnlyField(default='upcoming')
join_meeting_url = serializers.ReadOnlyField(source='get_join_meeting_url')
invitation_url = serializers.ReadOnlyField(source='get_meeting_invitation')
api_url = serializers.ReadOnlyField(source='get_api_url')
class Meta:
model = AppointmentMeeting
exclude = ('created_by', 'created_date',
'last_modified_by', 'last_modified_date',)
def get_zoom_meeting(self, obj):
meeting_id = obj.zoom_meeting_id
# Getting the Zoom Meeting
headers = {'authorization': 'Bearer %s' % generateToken(),
'content-type': 'application/json'}
r = requests.get(
f'https://api.zoom.us/v2/meetings/{meeting_id}',
headers=headers)
# print(r.json())
return r.json()
class DashboardSerializer(serializers.ModelSerializer):
total_counsellor_user = serializers.SerializerMethodField()
total_business_user = serializers.SerializerMethodField()
total_customer_user = serializers.SerializerMethodField()
class Meta:
model = UserRole
fields = ['total_counsellor_user', 'total_business_user', 'total_customer_user']
def get_total_counsellor_user(self, obj):
return UserRole.objects.filter(user_role__title="Counsellor").count()
def get_total_business_user(self, obj):
return UserRole.objects.filter(user_role__title="Business").count()
def get_total_customer_user(self, obj):
return UserRole.objects.filter(user_role__title="Customer").count()
class ReportSerializer(serializers.ModelSerializer):
class Meta:
model = Report
fields = '__all__'
class ReportInfoSerializer(serializers.ModelSerializer):
appointment = AppointmentDetailsSerializer(read_only=True)
counsellor = ListCounsellorProfileSerializer(read_only=True)
reported_by = MyAccountSerializer(read_only=True)
class Meta:
model = Report
fields = '__all__'
class FeedbackSerializer(serializers.ModelSerializer):
class Meta:
model = Feedback
fields = '__all__'
class FeedbackInfoSerializer(serializers.ModelSerializer):
appointment = AppointmentDetailsSerializer(read_only=True)
counsellor = ListCounsellorProfileSerializer(read_only=True)
feedback_by = MyAccountSerializer(read_only=True)
class Meta:
model = Feedback
fields = '__all__'
| rupendra-p/ekurakani | apps/appointment/serializers.py | serializers.py | py | 4,487 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "rest_framework.serializers.ModelSerializer",
"line_number": 16,
"usage_type": "attribute"
},
{
"api_name": "rest_framework.serializers",
"line_number": 16,
"usage_type": "name"
},
{
"api_name": "rest_framework.serializers.ModelSerializer",
"line_number": 22,
... |
24412532866 | from appFile import request, app, ma, cross_origin
from models.index import db, Events, Timeline
from flask import jsonify
from controllers.auth import JWTcheck
class EventSchema(ma.Schema):
class Meta:
fields = ('id', 'name', 'info', 'timeline_id', 'day', 'month', 'year', 'time', 'date_created')
event_schema = EventSchema()
@app.route('/addEvent', methods=['POST'])
@cross_origin()
@JWTcheck
def addEvent(data):
info = request.json['info']
name = request.json['name']
timeline_id = request.json['timeline_id']
day = request.json['day']
month = request.json['month']
year = request.json['year']
time = request.json['time']
new_event = Events(name, info, timeline_id, day, month, year, time)
db.session.add(new_event)
db.session.commit()
return event_schema.jsonify(new_event)
@app.route('/getEvents', methods=['POST'])
@cross_origin()
@JWTcheck
def getEvents(data):
timelineID = request.json['timeline_id']
if (Timeline.query.filter_by(id=timelineID).first().user_id!=data['user']):
return jsonify(message='You do not own this timeline'), 403
events = Events.query.filter_by(timeline_id=timelineID).all()
output = []
for element in events:
output.append({'name':element.name, 'id':element.id, 'info':element.info, 'day':element.day, 'month':element.month, 'year':element.year, 'time':element.time})
return jsonify(output)
@app.route('/eventEdit', methods=['PATCH'])
@cross_origin()
@JWTcheck
def eventEditInfo(data):
id = request.json['id']
info = request.json['info']
name = request.json['name']
day = request.json['day']
month = request.json['month']
year = request.json['year']
time = request.json['time']
event = Events.query.filter_by(id=id).first()
if (Timeline.query.filter_by(id=event.timeline_id).first().user_id!=data['user']):
return jsonify(message='You do not own this timeline'), 403
event.info = info
event.name = name
event.day = day
event.month = month
event.year = year
event.time = time
db.session.commit()
return jsonify({'name':event.name,'info':event.info, 'day':event.day, 'month':event.month, 'year':event.year, 'time':event.time, 'id':event.id}) | Snugles/onTimeline | server/controllers/events.py | events.py | py | 2,173 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "appFile.ma.Schema",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "appFile.ma",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "appFile.request.json",
"line_number": 16,
"usage_type": "attribute"
},
{
"api_name": "appFile.req... |
11343329447 | import re
from utils import logger
BIO_PATTERN = re.compile(r'\[(.+?)\](_[A-Z]{3}_)')
BIO_BEGIN = re.compile(r'_[A-Z]{3}_\[')
BIO_END = re.compile(r'\]_[A-Z]{3}_')
def pre_process(text):
text = BIO_PATTERN.sub(r'\2[\1]\2', text)
i = 0
res = []
label = ''
is_begin = False
is_inner = False
length = len(text)
while i < length:
c = text[i]
if '_' == c and i + 5 < length and BIO_BEGIN.fullmatch(text, i, i + 6):
label = text[i + 1:i + 4]
i += 6
is_begin = True
is_inner = True
continue
if ']' == c and i + 5 < length and BIO_END.fullmatch(text, i, i + 6) and is_inner:
i += 6
is_inner = False
continue
if is_begin:
res.append([c, f'B-{label}'])
is_begin = False
elif is_inner:
res.append([c, f'I-{label}'])
else:
res.append([c, 'O'])
i += 1
return res
def post_process(text, predict):
res = []
end_idx = len(text) - 1
for i in range(end_idx):
token = text[i]
label1 = predict[i]
label2 = predict[i + 1]
if 'O' == label1:
res.append(token)
else:
if label1.startswith('B-'):
res.append('[')
res.append(token)
if not label2.startswith('I-'):
res.append(f']_{label1[2:5]}_')
token = text[end_idx]
label1 = predict[end_idx]
if label1.startswith('B-'):
res.append('[')
res.append(token)
if 'O' != label1:
res.append(f']_{label1[2:5]}_')
return ''.join(res)
if __name__ == '__main__':
text = '我喷了[chanel]_PRO_香水,在[澳大利亚]_LOC_吃着[肯德基]_COM_炸鸡'
bio = pre_process(text)
labeled = post_process([char[0] for char in bio], [char[1] for char in bio])
logger.info(text)
logger.info(bio)
logger.info(labeled)
logger.info(f'check status: {text == labeled}')
| henryhyn/caesar-next | ner/ner_utils.py | ner_utils.py | py | 2,017 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "re.compile",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "re.compile",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "re.compile",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "utils.logger.info",
"line_number": ... |
37749262526 | import os
import requests
import shutil
import boto3
from PIL import Image
import urllib.request
access_key_src = os.environ.get("AWS_ACCESS_KEY_ID")
secret_key_src = os.environ.get("AWS_SECRET_ACCESS_KEY")
region_name = os.environ.get("AWS_REGION_NAME")
bucket_name = os.environ.get("AWS_MEDIA_BUCKET_NAME")
bucket_folder = os.environ.get("AWS_BUCKET_BASE_FOLDER","")
def convert_image_name(old_name, append_name):
names = old_name.split(".")
extension = names[1]
new_name = names[0] + "-" + append_name + "." + extension
return new_name
def create_thumb_s3(image_file):
s3 = boto3.resource('s3', region_name=region_name,
aws_access_key_id=access_key_src,
aws_secret_access_key=secret_key_src)
bucket = s3.Bucket(bucket_name)
if not os.path.exists("__sized__/products"):
os.makedirs("__sized__/products")
keys = {
"products": [
("product_gallery", "thumbnail__540x540"),
("product_gallery_2x", "thumbnail__1080x1080"),
("product_small", "thumbnail__60x60"),
("product_small_2x", "thumbnail__120x120"),
("product_list", "thumbnail__255x255"),
("product_list_2x", "thumbnail__510x510"),
]
}
for output in keys['products']:
values = output[1].split("__")
if len(values) != 2:
return
output_size_str = values[1].split("x")
output_size = tuple(list(map(int, output_size_str)))
img = Image.open(image_file)
img.thumbnail(output_size)
image_path_thumb = convert_image_name(
image_file.replace("images", "__sized__/products"),
values[0] + "-" + values[1])
img.save(image_path_thumb)
new_image_name = bucket_folder+image_path_thumb.replace(
"app/media/", "")
bucket.upload_file(image_path_thumb, new_image_name,
ExtraArgs={"ContentType": "image/webp"})
os.remove(image_path_thumb)
os.remove(image_file)
pass
"""download image from url
"""
def download_image(url):
fileName = url.split("/")[-1]
fileName = os.path.join("images", fileName)
path = os.path.dirname(fileName)
if not os.path.exists(path):
os.makedirs(path)
opener = urllib.request.URLopener()
opener.addheader('User-Agent', 'Upload media service')
fileName, headers = opener.retrieve(url, fileName)
# fileName = opener.retrieve(url, fileName)
return fileName
| trungannl/globallink-upload-media-master | uploadwebp/cron.py | cron.py | py | 2,536 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "os.environ.get",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "os.environ",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "os.environ.get",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "os.environ",
"line_num... |
186882541 | import json
import pandas as pd
import numpy as np
def processing_title(title):
return title.upper()
def processing_author(author):
return author.title()
def processing_discount(discount):
try:
discount = discount.replace('%dcto', '')
return int(discount)
except ValueError:
return 0
def processing_price_now(price):
try:
price = price.replace('.','')[2:]
return int(price)
except ValueError:
return np.nan
def processing_price_before(row):
if row['Discount'] == 0:
return row['Price now']
else:
price = row['Price before'].replace('.','')[2:]
return int(price)
def processing_info(info):
info = info.split(',')
info_sorted = [i.strip().upper() for i in info]
return info_sorted
def extracting_editorial(info_sorted):
editorial = info_sorted[0]
return editorial
def extracting_year(info_list):
for i in info_list:
if i.isdigit() and len(i) == 4:
return i
return np.nan
def process_data(df):
df['Title'] = df['Title'].apply(processing_title)
df['Author'] = df['Author'].apply(processing_author)
df['Discount'] = df['Discount'].apply(processing_discount)
df['Price now'] = df['Price now'].apply(processing_price_now)
df['Price before'] = df.apply(processing_price_before, axis=1)
df['Info_p'] = df['Info'].apply(processing_info)
df['Editorial'] = df['Info_p'].apply(extracting_editorial)
df['Year'] = df['Info_p'].apply(extracting_year)
df['Year'] = df['Year'].fillna(0).astype('int64')
df = df.drop(['Info', 'Info_p'], axis='columns')
return df
if __name__ == "__main__":
data_json = r"E:\Practicas\Proyects\book_tracker_buddy\data\buscabooks.json"
with open(data_json) as file:
books = json.load(file)
df = pd.DataFrame(books)
df = process_data(df)
data_csv = r"E:\Practicas\Proyects\book_tracker_buddy\data\buscabooks_process.csv"
df.to_csv(data_csv, index=False)
| avilanac/book_tracker_buddy | processing.py | processing.py | py | 2,114 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "numpy.nan",
"line_number": 23,
"usage_type": "attribute"
},
{
"api_name": "numpy.nan",
"line_number": 45,
"usage_type": "attribute"
},
{
"api_name": "json.load",
"line_number": 74,
"usage_type": "call"
},
{
"api_name": "pandas.DataFrame",
"line_... |
33820929017 | from werkzeug.utils import secure_filename
import sqlite3
import json
import os
class DatabaseHelper:
"""
This help to manage databases.
"""
def __init__(self) -> None:
pass
def save_image(self, main_dir: str, user_token: str, images: dict) -> bool:
"""
save_image() will save given images to given path.
Args:
main_dir (str): Main directory
user_token (str): Sub directory (image directory)
images (dict): Set of images
Returns:
bool: Return code (False -> Failed, True -> Success)
"""
try:
os.mkdir(f"{main_dir}/{user_token}")
for img in images:
img_name, img_ext = os.path.splitext(
secure_filename(images[img].filename)
)
images[img].filename = f"{img}{img_ext}"
location = os.path.join(main_dir, user_token, images[img].filename)
images[img].save(location)
return True # Success
except Exception as e:
print(f"An Error occured : {e}")
return False # Failure
| s3h4n/CVIS | packages/db_helper/db_helper.py | db_helper.py | py | 1,171 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "os.mkdir",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "os.path.splitext",
"line_number": 31,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 31,
"usage_type": "attribute"
},
{
"api_name": "werkzeug.utils.secure_filename... |
35942244086 | import heapq
from collections import defaultdict
from typing import List
start_and_end_times = [[4, 7], [2, 5], [1, 3], [5, 8]]
# test_tuples = [(1, 5), (3, 4), (3, 3), (2, 1), (2, 7), (1, 1)]
# heapq.heapify(test_tuples)
def max_concurrency_best(s):
"""Naive method to solve max_concurrency. Passes all tests!"""
heap = []
count = 0
answer = 0
heapq.heapify(s)
if s:
# from the min start time to the max end time
for i in range(s[0][0], s[len(s) - 1][1]):
for start_and_end_time in s:
if i == start_and_end_time[0]:
count += 1
if len(heap) < 1:
heapq.heappush(heap, count)
elif len(heap) == 1:
# fast push, then pop
heapq.heappushpop(heap, count)
else:
heapq.heappop(heap)
elif i == start_and_end_time[1]:
count -= 1
if heap:
answer = heap[0]
return answer
def max_concurrency_attempt_1(s):
"""Efficient method to solve max_concurrency. Passes 4 tests."""
heap = []
start = 0
end = 1
heapq.heapify(s[:])
if s:
count = len(s)
heapq.heappush(heap, s[0])
for i in range(len(s)):
top = s[0]
if top[end] < s[i][start]:
heapq.heappush(heap, s[i])
count -= 1
elif top[end] < s[i][end]:
# top[end] = s[i][end]
heapq.heappop(heap)
heapq.heappush(heap, top)
count += 1
else:
count = 0
return count
def max_concurrency_attempt_2(s):
"""Efficient method to solve max_concurrency. Doesn't even compile."""
import heapq
h = []
heapq.heappush(h, 10000)
res = 0
for (start, end) in s:
while heapq.nsmallest(1, h)[0] < s:
heapq.heappop(h)
res = res + len(h) - 1
heapq.heappush(h, end)
return res
def max_concurrency_attempt_3(s):
"""Fails 9 tests."""
es = []
for start, end in s:
es.append((start, -1))
es.append((end, 1))
es.sort()
result = 0
n = 0
for start, s in es:
if s == -1:
result += n
n -= s
return result
def max_concurrency_attempt_4(intervals):
"""Fails all tests."""
intervals = sorted(intervals)
first_start, first_end = intervals[0]
current_intervals = []
heapq.heappush(current_intervals, first_start)
overlaps = 0
for start, end in intervals[1:]:
if current_intervals:
if current_intervals[0] < start:
heapq.heappop(current_intervals)
overlaps += len(current_intervals)
return overlaps
def max_concurrency_attempt_5(points):
"""
If len of intervals is 0 or 1 return immediately. Passes 2 tests.
"""
if len(points) in [0, 1]:
return len(points)
"""
Push all intervals to heap
"""
q = []
for point in points:
heapq.heappush(q, (point[0], point[1]))
"""
Start with the top element in the heap
"""
cur = heapq.heappop(q)
cur_max = cur[1]
res = []
while q:
point = heapq.heappop(q)
"""
check if the last seen max falls in the new point interval. If it is then change the last seen max
"""
if point[0] <= cur_max:
cur_max = min(cur_max, point[1])
else:
"""
In this case last seen max doesn't fall in the new point interval. Push last seen max to ans and then res assign to new point end
"""
res.append(cur_max)
cur_max = point[1]
res.append(cur_max)
return len(res)
def max_concurrency(s):
concurrent_jobs = 0
max_jobs = 0
heap = []
if s:
for start, end in s:
heapq.heappush(heap, end)
while heap[0] <= start:
heapq.heappop(heap)
concurrent_jobs -= 1
concurrent_jobs += 1
if concurrent_jobs > max_jobs:
max_jobs = concurrent_jobs
return max_jobs
def max_concurrency_attempt_7(self, trips: List[List[int]], capacity: int) -> bool:
"""Does not compile."""
start = defaultdict(int)
end = defaultdict(int)
for trip in trips:
start[trip[1]] += trip[0]
end[trip[2]] += trip[0]
curr = 0
heapStart = []
for key, value in start.items():
heapq.heappush(heapStart, (key, value))
heapEnd = []
for key, value in end.items():
heapq.heappush(heapEnd, (key, value))
while heapStart:
if heapEnd[0][0] <= heapStart[0][0]:
curr -= heapq.heappop(heapEnd)[1]
else:
if heapStart[0][1] + curr > capacity:
return False
curr += heapq.heappop(heapStart)[1]
return True
def max_concurrency_attempt_8(s):
"""Passes 4 tests."""
intervalPoints = []
for interval in s:
heapq.heappush(intervalPoints, (interval[0], -1))
heapq.heappush(intervalPoints, (interval[1], 1))
maxOverlap = 0
maxOverlapLocation = 0
overlaps = 0
while intervalPoints:
index, val = heapq.heappop(intervalPoints)
overlaps -= val
if overlaps > maxOverlap:
maxOverlap = overlaps
maxOverlapLocation = index
return maxOverlapLocation
def max_concurrency_pre_attempt_9(s):
"""Passes 7 tests."""
s.sort(key=lambda x: x[1])
f = 0
heap = []
for start, end in s:
heapq.heappush(heap, -start)
f += start
if f >= end:
f += heapq.heappop(heap)
return len(heap)
def max_concurrency_attempt_9(s):
pq = []
start = 0
for start_end in sorted(s, key=lambda x: x[1]):
st, end = start_end[0], start_end[1]
start += st
heapq.heappush(pq, -st)
while start >= end:
start += heapq.heappop(pq)
return len(pq)
def max_concurrency_attempt_10(s):
"""Fails all tests."""
starts, ends = zip(*s)
overlap = range(max(starts), min(ends) + 1)
if not overlap:
return ([], range(min(starts), max(ends) + 1), [])
less_non_overlap = range(*heapq.nsmallest(2, starts))
end, start = heapq.nlargest(2, ends)
greater_non_overlap = range(start + 1, end + 1)
return (overlap, less_non_overlap, greater_non_overlap)
def max_concurrency_attempt_11(s):
"""Fails all tests."""
meetings = sorted(s, key=lambda k: k[1])
heap = [(meetings[0][1], 0)]
overlaps = {}
for i in range(1, len(meetings)):
if meetings[i][0] == heap[0][0]:
heapq.heappush(heap, (meetings[i][1], i))
else:
heapq.heappop(heap)
heapq.heappush(heap, (meetings[i][1], i))
if meetings[i][0] <= heap[0][0]:
p = (meetings[i][0], heap[0][0])
if p in overlaps:
overlaps[p] = max(overlaps[p], len(heap))
else:
overlaps[p] = len(heap)
return [x for x, y in overlaps.items() if y == max(overlaps.values())]
# print(max_concurrency(start_and_end_times))
# start_time, end_time = start_and_end_time[0], start_and_end_time[1]
# overlap = min(end_time)
| eforgacs/schoolSandbox | fundamental_algorithms/Midterm/max_concurrency.py | max_concurrency.py | py | 7,345 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "heapq.heapify",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "heapq.heappush",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "heapq.heappushpop",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "heapq.heappop",
"l... |
70205998754 | from typing import List
from .. import DeviceModel, _template_env
from . import signed_weight
class IntegratorModel(DeviceModel):
ng_spice_model_name = 'int'
def __init__(
self,
model_name: str,
in_offset: float = 0.0,
gain: float = 1.0,
out_lower_limit: float = -10.0,
out_upper_limit: float = 10.0,
limit_range: float = 1e-6,
out_ic: float = 0.0,
comments: List[str] = ['integrator'],
):
super().__init__(
model_name,
comments=comments,
in_offset=in_offset,
gain=gain,
out_lower_limit=out_lower_limit,
out_upper_limit=out_upper_limit,
out_ic=out_ic,
limit_range=limit_range,
)
# indicate that this model has a verilog-ams implementation
self.verilog_ams = True
def get_ngspice(self):
return _template_env.get_template('ngspice/model.cir.j2').render(
{
'model_instance_name': self.model_name,
'model_name': self.ng_spice_model_name,
'parameters': self.parameters,
}
)
def get_verilog_ams(self):
return _template_env.get_template('verilog_ams/integrator.vams.j2').render(
{
'module_instance_name': self.model_name,
'model_name': self.ng_spice_model_name,
'parameters': {
'in_offset': {
'active': float(self.parameters['in_offset']) != 0.0,
'magnitude': float(self.parameters['in_offset']),
'sign': ['+', '-'][float(self.parameters['in_offset']) < 0],
},
'gain': float(self.parameters['gain']),
'out_lower_limit': signed_weight(
float(self.parameters['out_lower_limit'])
),
'out_upper_limit': signed_weight(
float(self.parameters['out_upper_limit'])
),
'limit_range': signed_weight(float(self.parameters['limit_range'])),
'out_ic': {
'magnitude': abs(float(self.parameters['out_ic'])),
'sign': ['+', '-'][float(self.parameters['out_ic']) < 0],
},
},
'description': 'A simplistic integrator model',
'terminals': ['in', 'out'],
}
)
| hammal/cbadc | src/cbadc/circuit/models/integrator.py | integrator.py | py | 2,546 | python | en | code | 8 | github-code | 1 | [
{
"api_name": "typing.List",
"line_number": 18,
"usage_type": "name"
}
] |
71773999394 | """EJERCICIO 3
El día juliano correspondiente a una fecha es un número entero que indica los días que han
transcurrido desde el 1 de enero del año indicado. Queremos crear un programa principal que
al introducir una fecha nos diga el día juliano que corresponde. Para ello podemos hacer las
siguientes subrutinas:
LeerFecha: Nos permite leer por teclado una fecha (día, mes y año).
DiasDelMes: Recibe un mes y un año y nos dice los días de ese mes en ese año.
EsBisiesto: Recibe un año y nos dice si es bisiesto.
Calcular_Dia_Juliano: recibe una fecha y nos devuelve el día juliano."""
from datetime import datetime
def leer_fecha():
try:
n1=int(input("Introduce un día del mes: "))
n2=int(input ("Introduce un mes de en formato numérico, 1 para Enero y 12 para diciembre: "))
n3=int(input ("Introduce un año: "))
if n1<1 or n1>31 or n2<1 or n2>13:
return "La fecha introducida no es correcta"
elif (n2==11 or n2==4 or n2==6 or n2==9 or n2==2) and n1>30:
return "La fecha introducida no es correcta"
elif n2==2 and n1>29:
return "La fecha introducida no es correcta"
elif n2==2 and n3%4!=0 and n1>28:
return "La fecha introducida no es correcta"
elif n2==2 and (n3%4==0 and n3%100==0 and n3%400!=0) and n1>28:
return"La fecha introducida no es correcta"
else:
#return "La fecha introducida es correcta"
return n1,n2,n3
except:
"Sólo se admiten enteros"
#return n1,n2,n3
def dias_del_mes():
treinta=[11,4,6,9]
treinta_y_uno=[1,3,5,7,8,10,12]
try:
dia,mes,anho=leer_fecha()
except:
print("Los valores introducidos no son correctos")
if mes in treinta:
n1=30
elif mes in treinta_y_uno:
n1=31
elif mes==2:
if anho%4==0:
if anho%100==0 and anho%400!=0:
n1=28
else:
n1=29
else:
n1=28
else:
print("Los meses sólo van del 1 al 12")
exit()
print ("Los días de ese mes en ese año son "+ str(n1))
return n1
def es_bisiesto():
dia,mes,anho=leer_fecha()
bandera=True
if anho%4==0:
if anho%100==0 and anho%400!=0:
print ("El año "+str(anho)+" no es bisiesto")
else:
print("El año "+str(anho)+" es bisiesto")
bandera=False
else:
print ("El año "+str(anho)+" no es bisiesto")
def calcular_dia_juliano():
try:
dia,mes,anho=leer_fecha()
d1=str(anho)+'-01-01'
d2=str(anho)+'-'+str(mes)+'-'+str(dia)
d1 = datetime.strptime(d1, "%Y-%m-%d")
d2 = datetime.strptime(d2, "%Y-%m-%d")
resultado= abs((d2 - d1).days)
except:
resultado="Los valores introducidos no son correctos"
return resultado
print (calcular_dia_juliano())
| dvidals/python | ejercicios_clase_interfaces/ejer_funciones3.py | ejer_funciones3.py | py | 2,974 | python | es | code | 0 | github-code | 1 | [
{
"api_name": "datetime.datetime.strptime",
"line_number": 86,
"usage_type": "call"
},
{
"api_name": "datetime.datetime",
"line_number": 86,
"usage_type": "name"
},
{
"api_name": "datetime.datetime.strptime",
"line_number": 87,
"usage_type": "call"
},
{
"api_name"... |
26481678278 | import torch
import gym
from model import Model
from collections import deque
import numpy as np
from env_wrapper import FlappyBirdEnv
env = FlappyBirdEnv(render_mode = "human")
policy = Model(4, 2)
def reinforce(policy, n_training_episodes, max_t, gamma, print_every):
is_pick = True
scores_deque = deque(maxlen=100)
scores = []
for i_episode in range(1, n_training_episodes+1):
saved_log_probs = []
rewards = []
state, info = env.reset()
# Line 4 of pseudocode
for t in range(max_t):
# print(state)
# import ipdb; ipdb.set_trace()
pick = np.random.uniform()
action, log_prob = policy.act(torch.tensor(state))
saved_log_probs.append(log_prob)
# if is_pick and pick <= 0.1:
# state, reward, done, _ = env.step(env.action_space.sample())
# else:
state, reward, done, _ = env.step(action)
rewards.append(reward)
if done:
break
scores_deque.append(sum(rewards))
scores.append(sum(rewards))
returns = deque(maxlen=max_t)
n_steps = len(rewards)
for t in range(n_steps)[::-1]:
disc_return_t = (returns[0] if len(returns)>0 else 0)
returns.appendleft( gamma*disc_return_t + rewards[t] )
eps = np.finfo(np.float32).eps.item()
returns = torch.tensor(returns, dtype = torch.float32)
returns = (returns - returns.mean()) / (returns.std() + eps)
policy_loss = []
for log_prob, disc_return in zip(saved_log_probs, returns):
policy_loss.append(-log_prob * disc_return)
# print(policy_loss)
policy_loss = torch.cat(policy_loss).sum()
policy.optimizer.zero_grad()
policy_loss.backward()
policy.optimizer.step()
if i_episode % print_every == 0:
print('Episode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque)))
if i_episode % print_every == 200:
is_pick = False
return scores
reinforce(
policy=policy,
n_training_episodes=1000,
max_t = 500,
gamma = 0.98,
print_every=100
) | qvd808/flappy-bird-policy-gradient | flappy_bird_env.py | flappy_bird_env.py | py | 2,299 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "env_wrapper.FlappyBirdEnv",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "model.Model",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "collections.deque",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "numpy.random.u... |
22374085933 | from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication, QFrame
from PyQt5.QtWidgets import QApplication, QGridLayout, QLabel, QMainWindow, QPushButton, QWidget, QTableWidget, QTableWidgetItem, QMessageBox, QMenuBar, QLineEdit
from PyQt5.QtGui import QBrush, QColor
from PyQt5 import QtCore
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import matplotlib
from sqlite3 import IntegrityError, OperationalError
import sqlite3
from datetime import datetime
import pandas as pd
import numpy as np
import string
import sys
matplotlib.use('Qt5Agg')
class ExpenseTracker(QMainWindow):
def __init__(self):
super().__init__()
# db
self.db = sqlite3.connect(
r'App_projects\expense_tracker\expenses.db')
self.cursor = self.db.cursor()
# geometry
self.setGeometry(0, 0, 900, 900)
self.setWindowTitle('Expense tracker')
self.setStyleSheet('background: #FFFFFF')
# menu bar
self.menubar = self.menuBar()
self.statusBar()
self.budgets = QAction(text='Budgets', parent=self)
self.budgets.setShortcut('Ctrl+P')
self.budgets.setStatusTip('Budget overview')
self.budgets.triggered.connect(self.get_budgets)
budget_menu = self.menubar.addMenu('&Budgets')
budget_menu.addAction(self.budgets)
balance = QAction(text='Balance', parent=self)
balance.setShortcut('Ctrl+P')
balance.setStatusTip('Balance overview')
balance.triggered.connect(self.get_balance)
statistics_menu = self.menubar.addMenu('&Statistics')
statistics_menu.addAction(balance)
exitAction = QAction('&Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(qApp.quit)
exit_menu = self.menubar.addMenu('&Exit')
exit_menu.addAction(exitAction)
# widgets
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.central_widget.show()
self.grid = QGridLayout(self.central_widget)
self.frame_1 = QFrame(self.central_widget)
self.grid.addWidget(self.frame_1, 0, 0)
self.frame_2 = QFrame(self.central_widget)
self.grid.addWidget(self.frame_2, 1, 0)
self.grid_1 = QGridLayout(self.frame_1)
self.grid_2 = QGridLayout(self.frame_2)
self.label_1 = Label('Expense tracker')
self.grid_1.addWidget(self.label_1, 0, 1, 1, 2)
self.label_2 = Label('Balance: ')
self.grid_1.addWidget(self.label_2, 1, 0)
self.adjust_button = QPushButton('CHANGE BALANCE')
self.adjust_button.clicked.connect(self.new_balance)
self.grid_1.addWidget(self.adjust_button, 1, 1)
self.label_4 = Label('Account: ')
self.grid_1.addWidget(self.label_4, 2, 0)
self.change_acc = QPushButton(self)
self.change_acc.setText('CHANGE ACCOUNT')
self.change_acc.clicked.connect(self.change_account)
self.grid_1.addWidget(self.change_acc, 2, 1)
self.add_account_button = QPushButton('NEW RECORD')
self.add_account_button.clicked.connect(self.add_an_expense)
self.grid_1.addWidget(self.add_account_button, 1, 2)
self.zapisi_button = QPushButton('RECORDS')
self.zapisi_button.clicked.connect(self.get_records)
self.grid_1.addWidget(self.zapisi_button, 2, 2)
self.label_3 = Label('Expense composition')
self.grid_2.addWidget(self.label_3, 0, 1)
try:
self.account = self.cursor.execute(
'SELECT user FROM expenses ORDER BY time DESC LIMIT 1;').fetchall()[0][0]
self.label_4.setText(self.label_4.text() + self.account)
except IndexError:
self.account = 'unknown'
self.get_account_balance(self.account)
self.button_frame = QFrame(self)
self.grid.addWidget(self.button_frame, 3, 0)
self.button_grid = QGridLayout(self.button_frame)
self.month = QPushButton(self)
self.month.setText('Last 30 days')
self.month.clicked.connect(self.show_graph_time)
self.month.setMaximumWidth(200)
self.button_grid.addWidget(self.month, 1, 0)
self.year = QPushButton(self)
self.year.setText('This year')
self.year.clicked.connect(self.show_graph_time)
self.year.setMaximumWidth(200)
self.button_grid.addWidget(self.year, 1, 1)
self.show_graph()
def show_graph(self, table_name='expenses', amount='amount', asset='category', date='Last 30 days'):
l_of_time = list(self.get_time())
if date == 'Last 30 days':
if l_of_time[4:6] == ['0', '1']:
l_of_time[4] = '1'
l_of_time[5] = '2'
l_of_time[3] = str(int(l_of_time[3]) - 1)
else:
nums = int(''.join(l_of_time[4:6]))
nums -= 1
if nums < 10:
l_of_time[4] = '0'
l_of_time[5] = str(nums)
else:
l_of_time[4] = str(nums)[0]
l_of_time[5] = str(nums)[1]
else:
l_of_time[3] = str(int(l_of_time[3]) - 1)
l_of_time = ''.join(l_of_time)
try:
query = self.cursor.execute(
f'SELECT {asset}, SUM({amount}) FROM "{table_name}" WHERE type = "expense" AND time BETWEEN "{l_of_time}" AND "{self.get_time()}" AND user = "{self.account}" GROUP BY {asset}').fetchall()
except OperationalError:
query = self.cursor.execute(
f'SELECT {asset}, SUM({amount}) FROM "expenses" WHERE type = "expense" AND time BETWEEN "{l_of_time}" AND "{self.get_time()}" AND user = "{self.account}" GROUP BY {asset}').fetchall()
self.pie = MplCanvasPie(self, width=6, height=5, dpi=100)
if date == 'Last 30 days':
time = 'Last 30 days'
else:
time = 'This year'
try:
self.pie.show_overview(amounts=[float(item[1]) for item in query], assets=[
item[0] for item in query], table_name=table_name.upper(), table_title=sum([float(item[1]) for item in query]), time_period=time)
except AttributeError:
self.pie.show_overview(amounts=[float(item[1]) for item in query], assets=[
item[0] for item in query], table_name="EXPENSES", table_title=sum([float(item[1]) for item in query]), time_period=time)
self.grid_2.addWidget(self.pie, 2, 0, 1, 3)
self.pie.show()
def show_graph_time(self):
date = self.sender().text()
self.chart_1 = self.show_graph(date=date)
def get_account_balance(self, account, initial=True):
try:
self.label_2.setText('Balance: ' + [item[0] for item in self.cursor.execute(
f'SELECT amount FROM account WHERE name = "{account}";').fetchall()][0] + '€')
if initial == False:
self.label_4.setText(self.label_4.text().split(' ')[
0] + ' ' + self.account)
except IndexError:
self.label_2.setText('no data')
self.label_4.setText('no data')
def get_time(self):
return ''.join([item for item in datetime.now().strftime(
'%Y/%m/%d, %H:%M:%S') if item.isalnum()])
def new_balance(self):
self.balance_window = NewBalance()
self.balance_window.show()
def add_an_expense(self):
self.expense_window = NewExpense()
self.expense_window.show()
def get_records(self):
self.records_window = RecordsWindow()
if type(self.records_window.table) == QTableWidget:
self.records_window.show()
else:
self.records_window.close()
def get_budgets(self):
self.budget_window = BudgetWindow()
self.budget_window.show()
def get_balance(self):
self.balance_window = BalanceWindow()
self.balance_window.show()
def clear_expenses(self):
self.cursor.execute('DELETE FROM expenses')
self.db.commit()
def hide_pie(self):
self.pie.hide()
def change_account(self):
self.change_account_window = AccountPicker(self, initial=True)
self.change_account_window.show()
class NewBalance(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(0, 0, 300, 300)
self.setWindowTitle('SET BALANCE')
self.setStyleSheet('background: #FFFFFF')
self.grid = QGridLayout(self)
self.label = QLabel(self)
self.label.setText('Set balance')
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.grid.addWidget(self.label, 0, 0, 1, 2)
self.edit = QLineEdit(self)
self.grid.addWidget(self.edit, 1, 0, 1, 2)
self.insert_button = QPushButton(self)
self.insert_button.setText('UMETNI')
self.insert_button.clicked.connect(self.change_balance)
self.grid.addWidget(self.insert_button, 2, 0)
self.close_button = QPushButton(self)
self.close_button.setText('ODUSTANI')
self.close_button.clicked.connect(self.close)
self.grid.addWidget(self.close_button, 2, 1)
def change_balance(self, a='11', account='cele'):
user_found = e.cursor.execute(
f'SELECT name FROM account WHERE name = "{account}";').fetchall()
if user_found != []:
e.cursor.execute(
f'UPDATE account SET amount = "{self.edit.text()}" WHERE name = "{account}";')
else:
e.cursor.execute(
f'INSERT INTO account VALUES ("{account}", "{self.edit.text()}");')
e.db.commit()
e.get_account_balance(e.account)
self.close()
class NewExpense(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(0, 0, 300, 300)
self.setWindowTitle('ADD AN ENTRY')
self.setStyleSheet('background: #FFFFFF')
# grid + frames
self.grid = QGridLayout(self)
self.frame_1 = QFrame(self)
self.grid.addWidget(self.frame_1, 0, 0)
self.frame_2 = QFrame(self)
self.grid.addWidget(self.frame_2, 1, 0)
self.frame_3 = QFrame(self)
self.grid.addWidget(self.frame_3, 2, 0)
# frame 1
self.grid_1 = QGridLayout(self.frame_1)
self.close_button = QPushButton(self.frame_1)
self.close_button.setText('Close window')
self.close_button.clicked.connect(self.close)
self.grid_1.addWidget(self.close_button, 0, 0)
self.accept = QPushButton(self.frame_1)
self.accept.setText('Enter an entry')
self.accept.clicked.connect(self.insert_expense)
self.grid_1.addWidget(self.accept, 0, 1)
self.income = QPushButton(self.frame_1)
self.income.setText('Income')
self.income.clicked.connect(self.change_to_income)
self.grid_1.addWidget(self.income, 1, 0)
self.expense = QPushButton(self.frame_1)
self.expense.setText('Expense')
self.expense.clicked.connect(self.change_to_expense)
self.grid_1.addWidget(self.expense, 1, 1)
# frame 2
self.grid_2 = QGridLayout(self.frame_2)
self.operator = QLabel(self.frame_2)
self.grid_2.addWidget(self.operator, 0, 0)
self.amount = QLabel(self.frame_2)
self.amount.setAlignment(QtCore.Qt.AlignCenter)
self.amount.setText('')
self.grid_2.addWidget(self.amount, 0, 1)
# currency pick function
self.currency = QLabel(self.frame_2)
self.currency.setText('EUR')
self.currency.setAlignment(QtCore.Qt.AlignCenter)
self.grid_2.addWidget(self.currency, 0, 2)
self.account = QPushButton(self.frame_2)
self.account.clicked.connect(self.choose_account)
self.account_text = 'Račun: '
self.grid_2.addWidget(self.account, 1, 0)
self.category = QPushButton(self.frame_2)
self.category.clicked.connect(self.choose_category)
self.category_text = 'Kategorija: '
self.grid_2.addWidget(self.category, 1, 2)
# frame 3
self.grid_3 = QGridLayout(self.frame_3)
self.seven = QPushButton('7')
self.seven.clicked.connect(self.change_amount)
self.grid_3.addWidget(self.seven, 0, 0)
self.eight = QPushButton('8')
self.eight.clicked.connect(self.change_amount)
self.grid_3.addWidget(self.eight, 0, 1)
self.nine = QPushButton('9')
self.nine.clicked.connect(self.change_amount)
self.grid_3.addWidget(self.nine, 0, 2)
self.four = QPushButton('4')
self.four.clicked.connect(self.change_amount)
self.grid_3.addWidget(self.four, 1, 0)
self.five = QPushButton('5')
self.five.clicked.connect(self.change_amount)
self.grid_3.addWidget(self.five, 1, 1)
self.six = QPushButton('6')
self.six.clicked.connect(self.change_amount)
self.grid_3.addWidget(self.six, 1, 2)
self.one = QPushButton('1')
self.one.clicked.connect(self.change_amount)
self.grid_3.addWidget(self.one, 2, 0)
self.two = QPushButton('2')
self.two.clicked.connect(self.change_amount)
self.grid_3.addWidget(self.two, 2, 1)
self.three = QPushButton('3')
self.three.clicked.connect(self.change_amount)
self.grid_3.addWidget(self.three, 2, 2)
self.point = QPushButton('.')
self.grid_3.addWidget(self.point, 3, 0)
self.point.clicked.connect(self.change_amount)
self.zero = QPushButton('0')
self.zero.clicked.connect(self.change_amount)
self.grid_3.addWidget(self.zero, 3, 1)
self.back = QPushButton('<')
self.back.clicked.connect(self.change_amount)
self.grid_3.addWidget(self.back, 3, 2)
self.user = e.account
self.table_category = 'unknown'
self.type = 'unknown'
self.get_inital_values()
def get_inital_values(self):
try:
self.table_category, self.type = e.cursor.execute(
'SELECT category, type FROM expenses').fetchall()[-1]
self.account.setText(self.account_text + self.user)
self.category.setText(self.category_text + self.table_category)
if self.type == 'expense':
self.expense.setStyleSheet('background: #FFFF00;')
else:
self.income.setStyleSheet('background: #FFFF00;')
except IndexError:
self.account.setText('unknown')
self.category.setText('unknown')
def change_to_income(self):
if self.type == 'income':
pass
else:
self.expense.setStyleSheet('background: #FFFFFF;')
self.income.setStyleSheet('background: #FFFF00;')
self.type = 'income'
def change_to_expense(self):
if self.type == 'expense':
pass
else:
self.income.setStyleSheet('background: #FFFFFF')
self.expense.setStyleSheet('background: #FFFF00')
self.type = 'expense'
def insert_expense(self):
try:
new_amount = e.cursor.execute(
f'SELECT amount FROM account WHERE name = "{self.user}"').fetchall()
if new_amount != []:
new_amount = float(new_amount[0][0])
else:
msg = QMessageBox(QMessageBox.Warning,
'User not found', f'No user named {self.user}')
msg.exec_()
return
date = datetime.now().strftime('%Y/%m/%d, %H:%M:%S')
e.cursor.execute(
f'INSERT INTO expenses VALUES ("{self.user}", "{self.table_category}", "{self.amount.text()}", "{e.get_time()}", "{self.type}")')
if self.amount.text() == '':
msg = QMessageBox(
QMessageBox.Warning, 'Invalid number', 'Number field cannot be empty')
msg.exec_()
return
if self.type == 'expense':
new_amount -= float(self.amount.text())
elif self.type == 'income':
new_amount += float(self.amount.text())
else:
msg = QMessageBox(QMessageBox.Warning, 'Type incorrect',
'Type cannot be unknown, please select a valid type')
msg.exec_()
return
e.cursor.execute(
f'UPDATE account SET amount = "{new_amount}" WHERE name = "{self.user}";')
e.db.commit()
except AttributeError:
msg = QMessageBox(QMessageBox.Warning, 'No accounts found',
'Please make an account to enter an expense')
msg.exec_()
return
e.pie.hide()
e.show_graph()
e.get_account_balance(self.user)
def choose_account(self):
self.account_window = AccountPicker(parent=self)
self.account_window.show()
def choose_category(self):
self.category_window = CategoryPicker()
self.category_window.show()
def change_amount(self):
current_amount = self.amount.text()
sender = self.sender().text()
if sender == '<':
if len(current_amount) == 0:
pass
else:
self.amount.setText(current_amount[:-1])
elif sender == '.':
if '.' not in current_amount:
if len(current_amount) == 0:
pass
else:
self.amount.setText(current_amount + '.')
else:
self.amount.setText(current_amount + sender)
class MplCanvasPie(FigureCanvasQTAgg):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
super(MplCanvasPie, self).__init__(fig)
def show_overview(self, amounts, assets, table_name='overview', table_title='overview', time_period='Last 30 days'):
def func(pct, allvals):
absolute = int(np.round(pct/100.*np.sum(allvals)))
return "{:.1f}%\n({:d} €)".format(pct, absolute)
wedges, texts, autotexts = self.axes.pie(amounts, autopct=lambda pct: func(pct, amounts),
textprops=dict(color="w"))
self.axes.legend(wedges, assets,
title='Kategorije troškova',
loc="lower right",
bbox_to_anchor=(0, 0, 0, 0))
plt.setp(autotexts, size=8, weight="bold")
self.axes.set_title(f'{time_period}: {table_title} €')
class AccountPicker(QWidget):
def __init__(self, parent, initial=False):
super().__init__()
self.initial = initial
self.parent = parent
self.setGeometry(0, 0, 400, 400)
self.setWindowTitle('CHOOSE AN ACCOUNT')
self.setStyleSheet('background: #FFFFFF')
self.grid = QGridLayout(self)
self.new_account = QLabel(self)
self.new_account.setText('Add a new account: ')
self.grid.addWidget(self.new_account, 0, 0)
self.new_account_edit = QLineEdit(self)
self.grid.addWidget(self.new_account_edit, 0, 1)
self.add_button = QPushButton(self)
self.add_button.setText('ADD A NEW ACCOUNT')
self.add_button.clicked.connect(self.add_new)
self.grid.addWidget(self.add_button, 0, 2)
self.attempt()
def add_new(self):
account = self.new_account_edit.text()
try:
if account != '':
e.cursor.execute(
f'INSERT INTO account VALUES ("{account}", "0")')
e.db.commit()
self.attempt()
self.new_account_edit.setText('')
else:
msg = QMessageBox(
QMessageBox.Warning, 'Account name blank', 'Account name cannot be empty')
msg.exec_()
except IntegrityError:
msg = QMessageBox(QMessageBox.Warning, 'Account already present',
'Account already present in the database, cannot duplicate usernames')
msg.exec_()
def attempt(self):
items = e.cursor.execute('SELECT name FROM account').fetchall()
style_sheet = "" # napravit stylesheet
if items != []:
items = [item[0] for item in items]
for i in range(len(items)):
new_button = QPushButton(self)
new_button.setText(items[i])
new_button.setStyleSheet(style_sheet)
new_button.clicked.connect(self.get_account)
self.grid.addWidget(new_button, i + 1, 1)
else:
new_label = QLabel(self)
new_label.setText(
'No accounts found, please make an account to proceed')
self.grid.addWidget(new_label, 0, 0)
def get_account(self):
if not self.initial:
e.expense_window.user = self.sender().text()
e.expense_window.account.setText(
e.expense_window.account_text + e.expense_window.user)
if self.initial:
e.account = self.sender().text()
e.get_account_balance(e.account, initial=False)
e.show_graph()
self.close()
class CategoryPicker(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(0, 0, 400, 400)
self.setWindowTitle('CHOOSE A CATEGORY')
self.setStyleSheet('background: #FFFFFF')
self.grid = QGridLayout(self)
self.new_category = QLabel(self)
self.new_category.setText('ADD A NEW CATEGORY: ')
self.grid.addWidget(self.new_category, 0, 0)
self.new_category_edit = QLineEdit(self)
self.grid.addWidget(self.new_category_edit, 0, 1)
self.add_button = QPushButton(self)
self.add_button.setText('ADD A NEW CATEGORY')
self.add_button.clicked.connect(self.add_new)
self.grid.addWidget(self.add_button, 0, 2)
self.attempt()
def add_new(self):
category = self.new_category_edit.text()
try:
if category != '':
e.cursor.execute(
f'INSERT INTO expense_categories VALUES ("{category}")')
e.db.commit()
self.attempt()
self.new_category_edit.setText('')
else:
msg = QMessageBox(
QMessageBox.Warning, 'Category name blank', 'Category name cannot be empty')
msg.exec_()
except IntegrityError:
msg = QMessageBox(QMessageBox.Warning, 'Category already present',
'Category already present in the database, cannot duplicate category names')
msg.exec_()
def attempt(self):
items = e.cursor.execute(
'SELECT category FROM expense_categories').fetchall()
style_sheet = "" # napravit stylesheet
if items != []:
items = [item[0] for item in items]
for i in range(len(items)):
new_button = QPushButton(self)
new_button.setText(items[i])
new_button.setStyleSheet(style_sheet)
new_button.clicked.connect(self.get_account)
self.grid.addWidget(new_button, i + 1, 1)
else:
new_label = QLabel(self)
new_label.setText(
'No categories found, please make a category to proceed')
self.grid.addWidget(new_label, 0, 0)
def get_account(self):
e.expense_window.table_category = self.sender().text()
e.expense_window.category.setText(
e.expense_window.category_text + e.expense_window.table_category)
self.close()
class RecordsWindow(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(0, 0, 900, 900)
self.setWindowTitle('Records window')
self.setStyleSheet('background: #FFFFFF')
self.grid = QGridLayout(self)
self.table = self.show_table()
if type(self.table) == QTableWidget:
self.grid.addWidget(self.table, 0, 0)
else:
self.grid.addWidget(QLabel(self), 0, 0)
self.set_table_width()
try:
max_h = sum([self.table.rowHeight(row)
for row in range(self.table.rowCount())]) + 40
self.table.setMaximumHeight(max_h)
except AttributeError:
pass
def get_column_names(self, table_name):
columns = e.cursor.execute(
f"SELECT sql FROM sqlite_master WHERE name='{table_name}';").fetchall()[0][0]
first_sections = columns.split(f'"{table_name}"')[
1].split('PRIMARY KEY')[0]
upper = string.ascii_uppercase
other = ['', ' ', '(', ')', '\n', '\t', '"']
almost_done = [
item for item in first_sections if item not in upper and item not in other]
return [item for item in ''.join(
almost_done).split(',') if item != '']
def show_table(self, table_name='expenses'):
columns = self.get_column_names(table_name)
try:
content = e.cursor.execute(
f'SELECT * FROM {table_name} WHERE user = "{e.account}"').fetchall()
except OperationalError:
msg = QMessageBox(QMessageBox.Warning,
'Error with columns', f'Columns: {columns}')
msg.exec_()
try:
if len(content) == 0 and len(content[0]) == 0:
msg = QMessageBox(QMessageBox.Warning,
'Empty table', 'Table has no entries')
msg.exec_()
return None
table = QTableWidget(len(content), len(content[0]), self)
for i in range(len(content)):
for j in range(len(content[0])):
if j == 3:
item = QTableWidgetItem(
str(pd.to_datetime(content[i][j])))
else:
item = QTableWidgetItem(content[i][j])
item.setForeground(QBrush(QColor("#000000")))
table.setItem(i, j, item)
table.setHorizontalHeaderLabels(columns)
return table
except IndexError:
msg = QMessageBox(QMessageBox.Warning, 'Table empty',
'Table empty, cannot show data')
msg.exec_()
def set_table_width(self):
try:
width = self.table.verticalHeader().width()
width += self.table.horizontalHeader().length()
if self.table.verticalScrollBar().isVisible():
width += self.table.verticalScrollBar().width()
width += self.table.frameWidth() * 2
self.table.setFixedWidth(width)
except AttributeError:
pass
class BudgetWindow(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(0, 0, 700, 700)
self.setStyleSheet('background: #FFFFFF')
self.grid = QGridLayout(self)
self.main_label = QLabel(self)
self.main_label.setText('Budgets')
self.main_label.setAlignment(QtCore.Qt.AlignCenter)
self.grid.addWidget(self.main_label, 0, 0, 1, 3)
self.weekly = QFrame(self)
self.grid.addWidget(self.weekly, 1, 0)
self.weekly_grid = QGridLayout(self.weekly)
self.weekly_label = QLabel(self)
self.weekly_label.setText('Weekly budgets')
self.weekly_label.setAlignment(QtCore.Qt.AlignCenter)
self.weekly_grid.addWidget(self.weekly_label, 0, 0)
self.monthly = QFrame(self)
self.grid.addWidget(self.monthly, 1, 1)
self.monthly_grid = QGridLayout(self.monthly)
self.monthly_label = QLabel(self)
self.monthly_label.setText('Monthly budgets')
self.monthly_label.setAlignment(QtCore.Qt.AlignCenter)
self.monthly_grid.addWidget(self.monthly_label, 0, 0)
self.yearly = QFrame(self)
self.grid.addWidget(self.yearly, 1, 2)
self.yearly_grid = QGridLayout(self.yearly)
self.yearly_label = QLabel(self)
self.yearly_label.setText('Yearly budgets')
self.yearly_label.setAlignment(QtCore.Qt.AlignCenter)
self.yearly_grid.addWidget(self.yearly_label, 0, 0)
self.new_budget = QFrame(self)
self.grid.addWidget(self.new_budget, 2, 0, 1, 3)
self.new_budget_grid = QGridLayout(self.new_budget)
self.make_budget = QPushButton(self)
self.make_budget.setText('Make a new budget')
self.make_budget.setMaximumWidth(300)
self.make_budget.clicked.connect(self.make_a_new_budget)
self.new_budget_grid.addWidget(self.make_budget, 0, 0)
self.delete_budget = QPushButton(self)
self.delete_budget.setText('Delete a budget')
self.delete_budget.setMaximumWidth(300)
self.delete_budget.clicked.connect(self.delete_a_budget)
self.new_budget_grid.addWidget(self.delete_budget, 0, 1)
self.budgets = []
self.get_budgets()
# dodat funkcionalnost za promijenit iznos budgeta kao i dodat novi te izbrisat
def get_budgets(self):
budgets = e.cursor.execute(
f'SELECT * FROM budgets WHERE account = "{e.account}"').fetchall()
expenses = e.cursor.execute(
f'SELECT category, SUM(amount) FROM expenses WHERE user = "{e.account}" GROUP BY category;').fetchall()
expenses_dict = {}
for expense in expenses:
expenses_dict[expense[0]] = expense[1]
weekly = 1
monthly = 1
yearly = 1
for budget in budgets:
budget_frame = QFrame(self)
grid = QGridLayout(budget_frame)
splitted = budget[1].split(', ')
amount = 0
for item in splitted:
amount += float(expenses_dict[item])
budget_name = Label(budget[0])
grid.addWidget(budget_name, 0, 0)
amount_label = Label(str(amount) + '/' + budget[2])
grid.addWidget(amount_label, 1, 0)
if amount > float(budget[2]):
amount_label.setStyleSheet('color: red;')
elif amount == float(budget[2]):
amount_label.setStyleSheet('color: yellow')
if budget[-1] == 'weekly':
self.weekly_grid.addWidget(budget_frame, weekly, 0)
weekly += 1
elif budget[-1] == 'monthly':
self.monthly_grid.addWidget(budget_frame, monthly, 0)
monthly += 1
else:
self.yearly_grid.addWidget(budget_frame, yearly, 0)
yearly += 1
def make_a_new_budget(self):
self.new_budget_window = NewBudget()
self.new_budget_window.show()
def delete_a_budget(self):
self.delete_a_budget_window = DeleteBudget()
self.delete_a_budget_window.show()
def hide_budgets(self):
[[item.hide() for item in time.children() if type(item) == QFrame]
for time in [self.weekly, self.monthly, self.yearly]]
class BalanceWindow(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(0, 0, 700, 700)
self.setWindowTitle('Balance overview')
self.setStyleSheet('background: #FFFFFF')
self.balances = self.calc_balance()
self.canvas = MplCanvas()
self.canvas.axes.plot(self.balances[0], self.balances[1])
self.grid = QGridLayout(self)
self.label_1 = QLabel(self)
self.label_1.setText('Balance overview')
self.label_1.setAlignment(QtCore.Qt.AlignCenter)
self.grid.addWidget(self.label_1, 0, 0)
self.grid.addWidget(self.canvas, 1, 0)
def calc_balance(self):
expenses = e.cursor.execute(
f'SELECT amount, type, time FROM expenses WHERE user = "{e.account}"').fetchall()
balances = [float(e.cursor.execute(
f'SELECT amount FROM account WHERE name = "{e.account}";').fetchall()[0][0])]
dates = [''.join([item for item in datetime.now().strftime(
'%Y/%m/%d, %H:%M:%S') if item.isalnum()])]
for i in range(1, len(expenses) + 1):
if expenses[-i][1] == 'expense':
balances.insert(0, float(balances[0]) + float(expenses[-i][0]))
elif expenses[-i][1] == 'income':
balances.insert(0, float(balances[0]) - float(expenses[-i][0]))
dates.append(expenses[-i][2])
return dates, balances
class MplCanvas(FigureCanvasQTAgg):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
super(MplCanvas, self).__init__(fig)
class NewBudget(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(0, 0, 700, 700)
self.setStyleSheet('background: #FFFFFF')
self.grid = QGridLayout(self)
self.frame_1 = QFrame(self)
self.frame_1.setMaximumHeight(100)
self.grid_1 = QGridLayout(self.frame_1)
self.grid.addWidget(self.frame_1, 0, 0, 1, 2)
self.close_button = QPushButton(self)
self.close_button.setText('Close window')
self.close_button.clicked.connect(self.close)
self.close_button.setMaximumWidth(200)
self.grid_1.addWidget(self.close_button, 0, 0)
self.save_button = QPushButton(self)
self.save_button.setText('Save budget')
self.save_button.clicked.connect(self.save_budget)
self.save_button.setMaximumWidth(200)
self.grid_1.addWidget(self.save_button, 0, 1)
self.name = Label('Name')
self.name.setFocus()
self.grid.addWidget(self.name, 1, 0)
self.name_entry = LineEdit()
self.grid.addWidget(self.name_entry, 1, 1)
self.amount = Label('Amount')
self.grid.addWidget(self.amount, 2, 0)
self.amount_entry = LineEdit()
self.grid.addWidget(self.amount_entry, 2, 1)
self.period = Label('Time period')
self.grid.addWidget(self.period, 3, 0)
self.period_entry = LineEdit()
self.grid.addWidget(self.period_entry, 3, 1)
self.category = Label('Category (one or more)')
self.grid.addWidget(self.category, 4, 0)
self.category_entry = LineEdit()
self.grid.addWidget(self.category_entry, 4, 1)
self.account = Label('Account')
self.grid.addWidget(self.account, 5, 0)
self.account_entry = LineEdit()
self.account_entry.setText(e.account)
self.grid.addWidget(self.account_entry, 5, 1)
def save_budget(self):
data = [self.name_entry.text(), self.period_entry.text(),
self.category_entry.text(), self.account_entry.text(), self.amount_entry.text()]
budgets = [name[0] for name in e.cursor.execute(f'SELECT name FROM budgets'
).fetchall()]
if data[0] in budgets:
msg = QMessageBox(QMessageBox.Warning, 'Budget already present',
'Budget with this name already exists in the database')
msg.exec_()
return
if '' in data:
msg = QMessageBox(QMessageBox.Warning, 'Empty entries',
'Please fill out all the entries')
msg.exec_()
return
if data[1].lower() not in ['weekly', 'monthly', 'yearly']:
msg = QMessageBox(QMessageBox.Warning, 'Invalid timeframe',
'Please choose either beetwen a weekly, a monthly or a yearly period')
msg.exec_()
return
accounts = [account[0] for account in e.cursor.execute(
'SELECT name FROM account;').fetchall()]
if data[3] not in accounts:
msg = QMessageBox(
QMessageBox.Warning, 'Account unknown', 'Please select a valid account')
msg.exec_()
return
e.cursor.execute(
f'INSERT INTO budgets VALUES ("{data[0]}", "{data[2]}", "{data[4]}", "{data[3]}", "{data[1]}")')
e.db.commit()
e.budget_window.get_budgets()
class DeleteBudget(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(0, 0, 400, 200)
self.setStyleSheet('background: #FFFFFF')
self.grid = QGridLayout(self)
self.label = Label('Budget name: ')
self.grid.addWidget(self.label, 0, 0)
self.edit = LineEdit()
self.grid.addWidget(self.edit, 0, 1)
self.button = QPushButton()
self.button.setText('Delete the budget')
self.button.clicked.connect(self.delete_budget)
self.button.setMaximumWidth(200)
self.grid.addWidget(self.button, 0, 2)
self.frame = QFrame()
self.frame_grid = QGridLayout(self.frame)
self.grid.addWidget(self.frame, 1, 0, 1, 3)
def delete_budget(self):
name = self.edit.text()
e.cursor.execute(f'DELETE FROM budgets WHERE name = "{name}";')
e.db.commit()
label = Label('Budget successfuly deleted')
self.frame_grid.addWidget(label, 0, 0)
e.budget_window.hide_budgets()
e.budget_window.get_budgets()
class Label(QLabel):
def __init__(self, text, width=300):
super().__init__()
self.setText(text)
self.setAlignment(QtCore.Qt.AlignCenter)
self.setMaximumWidth(width)
class LineEdit(QLineEdit):
def __init__(self, width=300):
super().__init__()
self.setMaximumWidth(width)
if __name__ == '__main__':
app = QApplication(sys.argv)
e = ExpenseTracker()
e.show()
app.exec()
| celee1/expense-tracker | expense_tracker.py | expense_tracker.py | py | 39,348 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "matplotlib.use",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "PyQt5.QtWidgets.QMainWindow",
"line_number": 20,
"usage_type": "name"
},
{
"api_name": "sqlite3.connect",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "PyQt5.QtWi... |
26839905654 | # before use run in command shell:
# pip install pipenv
# pipenv install requests
# pipenv install BeautifulSoup
# pipenv install lxml
# pip install BeautifulSoup
# pip install beautifulsoup4
# pip install lxml
import requests
import re
from bs4 import BeautifulSoup
import json
# r = requests.get('http://immunet.cn/hmmcas') # this is optional
# url = "http://immunet.cn/hmmcas/index.html"
testgenome = open('NC_016025.faa', 'r').read()
# print(testgenome)
payload = {'sequence': testgenome,
'submit': 'Run HMMCAS'}
url = "http://immunet.cn/hmmcas/upload2.php"
print("request to "+ url)
headers = {'Host': 'immunet.cn',
'Connection': 'keep-alive',
# 'Content-Length': '400435',
'Cache-Control': 'max-age=0',
'Origin': 'http://immunet.cn',
'Upgrade-Insecure-Requests': '1',
'Content-Type': 'multipart/form-data',
'Save-Data': 'on',
'User-Agent': "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Referer': 'http://immunet.cn/hmmcas/index.html',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.8,ru;q=0.6'
}
r = requests.post(url, data=payload, headers=headers)
# print(r.request.body)
print(r.request.headers)
################# alernate
# files = {'uploadfile': open('NC_016025.faa', 'rb')}
# r = requests.post(url, files=files)
#################
#print(r.text)
text_file = open("Output1.html", "w")
text_file.write(r.text)
text_file.close()
#print(r.status_code)
matches = re.findall("(tables\/ToSlide\d+\.json)", r.text)
if len(matches):
print("found " + matches[0])
url2 = "http://immunet.cn/hmmcas/" + matches[0]+ "?limit=10&offset=0&sort=name&order=desc"
# http://immunet.cn/hmmcas/tables/ToSlide225044.json?limit=10&offset=0&sort=name&order=desc
r = requests.get(url2)
text_file = open("Output1j.html", "w")
text_file.write(r.json())
text_file.close()
# button for:
#url2 = "http://i.uestc.edu.cn/hmmcas/operon.php?qsf=ToSlide175938&tb=Table175938&sp=3"
#url2 = "http://i.uestc.edu.cn/hmmcas/operon.php?qsf=ToSlide031405&tb=Table031405&sp=3"
# Search links on buttons:
matches = re.findall("(http\:\/\/i\.uestc\.edu\.cn\/hmmcas\/operon\.php\?qsf=ToSlide.\d+\&tb=Table\d+\&sp=3)", r.text)
if len(matches):
print("found " + matches[0])
url2 = matches[0]
r = requests.get(url2)
from bs4 import BeautifulSoup
print(r.text)
text_file = open("Output2.html", "w")
text_file.write(r.text)
text_file.close()
soup = BeautifulSoup(r.text, "lxml")
for row in soup.findAll('table')[0].tbody.findAll('tr'):
first_column = row.findAll('th')[0].contents
third_column = row.findAll('td')[2].contents
print (first_column, third_column)
# from lxml import etree
# parser = etree.HTMLParser()
# tree = etree.fromstring(table, parser)
# results = tree.xpath('//tr/td[position()=2]')
# print ('Column 2\n========')
# for r in results:
# print (r.text)
| lightweave/CRISPR-dynamics | crawler/hmmcas.py | hmmcas.py | py | 2,986 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "requests.post",
"line_number": 44,
"usage_type": "call"
},
{
"api_name": "re.findall",
"line_number": 59,
"usage_type": "call"
},
{
"api_name": "requests.get",
"line_number": 64,
"usage_type": "call"
},
{
"api_name": "re.findall",
"line_number":... |
10599399107 | import praw
import pause
posts = []
url_set = set()
message_user = 'VirtualLeak'
reddit = praw.Reddit('user')
subreddit = reddit.subreddit('friends')
# Output post data in markdown table format
def output():
format_title = '|'.join(['title', 'author', 'subreddit', 'url', '# of comments\n'])
format_columns = '|'.join(['-', '-', '-', '-', '-\n'])
for i in range(len(posts)):
posts[i] = '|'.join([posts[i].title, str(posts[i].author), str(posts[i].subreddit),
posts[i].shortlink, str(posts[i].num_comments)])
format_table = '\n'.join(posts)
print(format_title + format_columns + format_table)
reddit.redditor(message_user).message('New Posts', format_title + format_columns + format_table)
posts.clear()
for post in subreddit.stream.submissions(pause_after=0): # Optional parameters: pause_after=0, skip_existing=True
# Avoids posts that link to the same url in multiple subreddits
if post is not None and post.url not in url_set:
url_set.add(post.url)
posts.insert(0, post)
# If there are new posts, send message
if post is None and len(posts) > 0:
output()
# If there aren't any new posts, pause for 24 hours
if len(posts) == 0:
pause.hours(24)
| shaneavila/reddit-alert | reddit_scraper.py | reddit_scraper.py | py | 1,274 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "praw.Reddit",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "pause.hours",
"line_number": 34,
"usage_type": "call"
}
] |
71681471074 | # -*- coding: utf-8 -*-
import logging
import werkzeug
from odoo import SUPERUSER_ID, api, http, _
from odoo import registry as registry_get
from odoo.addons.web.controllers.main import (login_and_redirect, ensure_db, set_cookie_and_redirect)
from odoo.exceptions import AccessDenied
_logger = logging.getLogger(__name__)
class SSOController(http.Controller):
@http.route('/web/sso/signin', type='http', auth='none')
def signin(self, redirect=None, **kwargs):
login = kwargs.get('userid', False)
timestamp = kwargs.get('timestamp', False)
ssoToken = kwargs.get('ssoToken', False)
dbname = kwargs.get('dbname', 'qis')
registry = registry_get(dbname)
with registry.cursor() as cr:
try:
env = api.Environment(cr, SUPERUSER_ID, {})
credentials = env['res.users'].sudo().auth_oauth(login, timestamp, ssoToken)
cr.commit()
resp = login_and_redirect(*credentials, redirect_url='/web')
return resp
except AttributeError:
# auth_signup is not installed
_logger.error("auth_signup not installed on database %s: oauth sign up cancelled." % (dbname,))
url = "/web/login?oauth_error=1"
except AccessDenied:
# oauth credentials not valid, user could be on a temporary session
_logger.info(
'OAuth2: access denied, redirect to main page in case a valid session exists, without setting cookies')
url = "/web/login?oauth_error=3"
redirect = werkzeug.utils.redirect(url, 303)
redirect.autocorrect_location_header = False
return redirect
except Exception as e:
# signup error
_logger.exception("OAuth2: %s" % str(e))
url = "/web/login?oauth_error=2"
return set_cookie_and_redirect(url)
| chenrongxu/login_sso | controllers/controllers.py | controllers.py | py | 1,975 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "logging.getLogger",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "odoo.http.Controller",
"line_number": 12,
"usage_type": "attribute"
},
{
"api_name": "odoo.http",
"line_number": 12,
"usage_type": "name"
},
{
"api_name": "odoo.registry",
... |
14991617651 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
##############################################
# Hardware
# - Windows 11
# - NI USB-6008
# Erst NI-DAQmx 19.5 installiert
# (aktuelle Version 2023 Q2 zeigt die Karte nicht an)
# (Die Unterstützung für Net Framework und C++ nicht installieren wenn kein Compiler auf dem Rechner)
# Dann nidaqmax installieren: "pip install nidaqmx" in Anaconda Prompt
import time as t
import numpy as np
import nidaqmx
from nidaqmx.constants import AcquisitionType
import pprint
fSampling = 10000 #Hz
nSamples = 1000 #samples
pp = pprint.PrettyPrinter(indent=4)
dtMax = 1 #sec
###############################################
# DAQ
data = []
t_insgesamt = 0
# config
with nidaqmx.Task() as task:
t_vorher = t.time()
task.ai_channels.add_ai_voltage_chan("Dev1/ai0")
task.timing.cfg_samp_clk_timing(fSampling, sample_mode=AcquisitionType.CONTINUOUS)
t_nachher = t.time()
while t_insgesamt < dtMax:
value = task.read(number_of_samples_per_channel=nSamples)
#t.sleep(1)
data.extend(value)
t_nachher = t.time()
dt_buffer = t_nachher-t_vorher
t_insgesamt += dt_buffer
t_vorher = t_nachher
#Verzögerungen haben keinen Einfluss auf die Messung! Super, hier der Beweis:
#print(dt_buffer)
#pp.pprint(data)
###############################################
# output to file
# In[2]:
print("Gesamte Messzeit [s]: " + str(t_insgesamt))
print("Anzahl aufgenommener Werte: " + str(len(data)))
print("Abtastfrequenz [Hz]: " + str(len(data) / t_insgesamt))
# In[3]:
import matplotlib.pyplot as plt
plt.rcParams['figure.dpi'] = 300
plt.rcParams['savefig.dpi'] = 300
fig = plt.figure()
plt.plot(data)
plt.tight_layout()
plt.xlabel('Zeit [s]')
plt.ylabel('Spannung [V]')
plt.show()
fig.savefig('..\output_bilder\output_voltage.png', dpi=fig.dpi)
# In[4]:
f = open("..\output_csv\output_voltage.txt", "w")
f.write("t,U")
for i in range(len(data)):
f.write(str(i/len(data)*t_insgesamt) + ',' + str(data[i]) + '\n')
f.close()
# In[ ]:
| alexwohlers/ni_daq | scripts/ni_read_voltage_buffered.py | ni_read_voltage_buffered.py | py | 2,120 | python | de | code | 0 | github-code | 1 | [
{
"api_name": "pprint.PrettyPrinter",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "nidaqmx.Task",
"line_number": 34,
"usage_type": "call"
},
{
"api_name": "time.time",
"line_number": 35,
"usage_type": "call"
},
{
"api_name": "nidaqmx.constants.Acquisi... |
44912301952 | import sys
from rdkit import Chem
from rdkit.Chem import AllChem
import glob
import shutil
import os
import multiprocessing as mp
nprocs = 4
except_dir_path = os.path.abspath(os.path.dirname(__file__)) + "\except_mol"
def optimize(mol_file):
try:
m = Chem.MolFromMolFile(mol_file)
m = Chem.AddHs(m)
AllChem.EmbedMolecule(m)
except:
shutil.move(mol_file, except_dir_path)
return
try:
AllChem.UFFOptimizeMolecule(m)
except ValueError:
print("Bad Conformer Id")
print(mol_file)
shutil.move(mol_file, except_dir_path)
# m = Chem.RemoveHs(m)
w = Chem.SDWriter(mol_file)
w.write(m)
print(str(mol_file))
return
if __name__ == "__main__":
#dir_path = os.path.abspath(os.path.dirname(__file__)) + "\mol_datas"
mol_files = glob.glob("*.sdf")
procs = mp.Pool(nprocs)
procs.map(optimize, mol_files)
| miya-dai/system_design | scripts/rdk.py | rdk.py | py | 829 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "os.path.abspath",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "os.path.dirname",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "rdkit.Chem.MolFromMolFil... |
45888664352 | from starlette.endpoints import HTTPEndpoint
from starlette.responses import UJSONResponse
from api.utils import is_admin
from db.conn import get_conn
from db.replica import Replica
from db.replica_files import ReplicaFiles
class ReplicasHandlers(HTTPEndpoint):
async def post(self, request):
is_admin(request)
data = await request.json()
async with get_conn()as conn:
async with conn.transaction():
replica = Replica(conn)
result = await replica.add(data['type'], data)
master = await replica.master()
if not master:
master_id = result
await replica.set_master(result)
else:
master_id = master['id']
await ReplicaFiles(conn).add_replica(result, master_id)
return UJSONResponse({'id': result})
async def get(self, request):
is_admin(request)
async with get_conn() as conn:
replicas = await Replica(conn).get_all()
return UJSONResponse({'data': replicas})
class ReplicaHandlers(HTTPEndpoint):
async def post(self, request):
is_admin(request)
data = await request.json()
replica_id = int(request.path_params['id'])
async with get_conn() as conn:
if 'master' in data:
await Replica(conn).set_master(replica_id)
if 'delay' in data:
await Replica(conn).update_delay(replica_id, data['delay'])
return UJSONResponse({})
async def delete(self, request):
is_admin(request)
replica_id = int(request.path_params['id'])
async with get_conn() as conn:
await Replica(conn).delete(replica_id)
return UJSONResponse({})
| wooque/openpacs | backend/api/replicas.py | replicas.py | py | 1,811 | python | en | code | 4 | github-code | 1 | [
{
"api_name": "starlette.endpoints.HTTPEndpoint",
"line_number": 10,
"usage_type": "name"
},
{
"api_name": "api.utils.is_admin",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "db.conn.get_conn",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "... |
29599272508 | import argparse
import cv2
import logging as log
import sys
import time
import socket
import paho.mqtt.client as mqtt
import json
import math
import os
from inference import Network
# Set the MQTT server environment variables
HOSTNAME = socket.gethostname()
IPADDRESS = socket.gethostbyname(HOSTNAME)
MQTT_HOST = IPADDRESS
MQTT_PORT = 1884
MQTT_KEEPALIVE_INTERVAL = 60
def connect_mqtt():
client = mqtt.Client()
client.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)
return client
def get_args():
# Create the parser object
parser = argparse.ArgumentParser()
# Create the arguments
# Required
parser.add_argument("-m", "--model", required = True, type = str, help = "The location of model .xml file")
parser.add_argument("-i", "--input", required = True, type = str, help = "The path to input image or video")
# Optional
parser.add_argument("-d", "--device", default = "CPU", type =str, help = "To specify target device used for inference, CPU, GPU, VPU etc.")
parser.add_argument("-l", "--cpu_extension", required = False, type = str, default = None, help = "MKLDNN (CPU)-targeted custom layers. Absolute path to a shared library")
parser.add_argument("-pt", "--prob_threshold", default = 0.5, type = float, help = "Probability threshold for detections filtering")
parser.add_argument("-c", "--color", default = "GREEN", type = str, help = "The color of the bounding boxes to draw; RED, GREEN or BLUE")
parser.add_argument("-at", "--alert_time", default = 15.0, type = float, help = "The duration people stay in the frame")
args = parser.parse_args()
return args
def preprocessing(frame, batch, channel, height, width):
# Resize to model's input w x h
p_frame = cv2.resize(frame, (width, height))
# Transpose the layout from hwc to chw
p_frame = p_frame.transpose((2, 0, 1))
# Reshape to model's shape n x c x h x w
p_frame = p_frame.reshape((batch, channel, height, width))
return p_frame
def infer_on_stream(args, client):
# Set flag for the input
single_image_mode = False
# Instantiate current inference request
cur_request_id = 0
# Initialize the plugin
plugin = Network()
# Load model, and get the input shape
plugin.load_model(args.model, args.device, cur_request_id, args.cpu_extension)
n, c, h, w = plugin.get_input_shape()
### Checking for the feed input file
# CAM
if args.input == 'CAM':
input_stream = 0
# Image
elif args.input.endswith('.jpg') or args.input.endswith('.bmp') :
single_image_mode = True
input_stream = args.input
# Video
else:
input_stream = args.input
assert os.path.isfile(args.input), "Specified input file doesn't exist"
# Create the VideoCapture object, and have it opened
cap = cv2.VideoCapture(input_stream)
if input_stream:
cap.open(args.input)
if not cap.isOpened():
log.error("ERROR! Unable to open video source")
###
# Grab the dimension of width and height
global initial_w, initial_h
initial_w = cap.get(3)
initial_h = cap.get(4)
# Set initial parameters
temp = 0
fp = 0
last_count = 0
total_count = 0
duration = 0
# Iterate the frame until the video ends
while cap.isOpened():
flag, frame = cap.read()
if not flag:
break
key_pressed = cv2.waitKey(60)
# Preprocessing
p_frame = preprocessing(frame, n, c, h, w)
# Perform async_inference
plugin.exec_net(cur_request_id, p_frame)
inf_start = time.time()
# Get the output result
if plugin.wait(cur_request_id) == 0:
result = plugin.extract_output(cur_request_id)
det_time = time.time() - inf_start
# Draw the bounding box
frame, current_count, d, fp = draw_boxes(frame, result, args, temp, fp)
# Print the inference time
inf_time_message = "Inference time: {:.3f}ms".format(det_time * 1000)
cv2.putText(frame, inf_time_message, (15, 15), cv2.FONT_HERSHEY_COMPLEX, 0.5, (200, 10, 10), 1)
### People Counting ###
# When new person enters into the frame
if current_count > last_count: # New entry
start_time = time.time()
total_count = total_count + current_count - last_count
client.publish("person", json.dumps({"total": total_count}))
if current_count < last_count:
duration = int(time.time() - start_time)
client.publish("person/duration", json.dumps({"duration": duration}))
# To check lost frames for false positive cases
lost_info = "Lost frame: %d" %(fp - 1)
cv2.putText(frame, lost_info, (15, 30), cv2.FONT_HERSHEY_COMPLEX, 0.5, (200, 10, 10), 1)
# Warning if people staying time > alert time
if duration >= args.alert_time:
cv2.putText(frame, 'CAUTION! Staying longer than ' + str(args.alert_time) + ' seconds', (15, 45), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 255), 1)
client.publish("person", json.dumps({"count": current_count}))
last_count = current_count
temp = d
###----------------###
# Break if escape key is pressed
if key_pressed == 27:
break
# Send the information to FFmpeg server
sys.stdout.buffer.write(frame)
sys.stdout.flush()
# Image mode
if single_image_mode:
cv2.imwrite('output_image.jpg', frame)
# Release all. Destroy OpenCV windows, and disconnect the MQTT
cap.release()
cv2.destroyAllWindows()
client.disconnect()
def draw_boxes(frame, result, args, x, k):
# Customize the color space of bounding box, if not assign default will be 'GREEN'
colors = {"BLUE": (255, 0, 0), "GREEN": (0, 255, 0), "RED": (0, 0, 255)}
if args.color:
draw_color = colors.get(args.color)
else:
draw_color = colors["GREEN"]
current_count = 0
distance = x
for obj in result[0][0]:
conf = obj[2]
if conf >= args.prob_threshold:
xmin = int(obj[3] * initial_w)
ymin = int(obj[4] * initial_h)
xmax = int(obj[5] * initial_w)
ymax = int(obj[6] * initial_h)
class_id = int(obj[1])
# If the probability threshold is crossed, then count the people, and draw the bounding box
current_count += 1
cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), draw_color, 3)
det_label = str(class_id)
cv2.putText(frame, "label: " + det_label + ' ' + str(round(obj[2] * 100, 1)) + ' %', (xmin, ymin - 7), cv2.FONT_HERSHEY_COMPLEX, 0.6, draw_color, 2)
enter_time = time.time()
# To calculate the distance
c_y = frame.shape[0] / 2
c_x = frame.shape[1] / 2
mid_y = (ymin + ymax) / 2
mid_x = (xmin + xmax) / 2
distance = math.sqrt(math.pow(mid_x - c_x, 2) + math.pow(mid_y - c_y, 2) * 1.0)
k = 0
if current_count < 1:
k += 1
if distance > 0 and k < 15:
current_count = 1
k += 1
if k > 100:
k = 0
return frame, current_count, distance, k
def main():
args = get_args()
client = connect_mqtt()
infer_on_stream(args, client)
if __name__ == "__main__":
main()
| jonathanyeh0723/OpenVINO_People_Counter_App | main.py | main.py | py | 7,735 | python | en | code | 2 | github-code | 1 | [
{
"api_name": "socket.gethostname",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "socket.gethostbyname",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "paho.mqtt.client.Client",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "paho.... |
6899169608 | # %%
# Shi-TOmasi角点检测(一种适应追踪的角点检测方式)
import numpy as np
import cv2
from matplotlib import pyplot as plt
# %%
img = cv2.imread('data/calibresult.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
"""goodFeaturesToTrack函数:
参数: (1)gray:输入灰度图
(2) 25:想要检测的角点数量
(3) 0:角点最低水平 (0到1)
(4) 10:两个角点的最短欧式距离
"""
corners = cv2.goodFeaturesToTrack(gray,25,0.01,10)
# 返回的结果是[[ 311., 250.]] 两层括号的数组。
corners = np.int0(corners)
for corner in corners:
x,y = corner.ravel()
cv2.circle(img,(x,y),3,255,-1) #汇出角点
plt.imshow(img),plt.show()
# %%
| vvgoder/opencv_learning_chinese | opencv学习文件/9.Shi-Tomas角点检测.py | 9.Shi-Tomas角点检测.py | py | 747 | python | zh | code | 2 | github-code | 1 | [
{
"api_name": "cv2.imread",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "cv2.cvtColor",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "cv2.COLOR_BGR2GRAY",
"line_number": 9,
"usage_type": "attribute"
},
{
"api_name": "cv2.goodFeaturesToTrack"... |
44258172133 | import altair as alt
import pandas as pd
import streamlit as st
import aws
import driver
import requests
import json
import os
from textblob import TextBlob
import datetime
import time
credentials_path = "credentials.json"
auth_dict = {
"CONSUMER_KEY": "",
"CONSUMER_SECRET": "",
"ACCESS_TOKEN": "",
"ACCESS_TOKEN_SECRET": "",
"ENVIRONMENT": ""
}
def get_individual_stock_data(ticker, start="", end="", interval="1d", period="ytd"):
"""get individual stock data"""
ip_address = get_current_ip()
if ip_address == None:
st.warning("IP not valid! Please Create an AWS instance or add valid IP")
return
response = requests.get(
f"http://{ip_address}/stocks/stock?ticker={ticker}&start={start}&end={end}&interval={interval}&period={period}"
)
data_dict = response.json()
# print(data_dict)
return data_dict
# Streamlit command: pipenv run streamlit run <path_to_file>.py
def preprocess_stock_data(stock_dict):
stock_df = pd.DataFrame(stock_dict)
# rename index to date
stock_df.index.rename("Date", inplace=True)
stock_df.reset_index(inplace=True)
stock_df = stock_df.rename(columns={"index": "Date"})
# convert string time to datetime object
stock_df["Date"] = pd.to_datetime(
stock_df["Date"], format="%Y-%m-%dT%H:%M:%S")
return stock_df
def barplot(df, y, x, title=""):
"""barplot with input of a data frame"""
bar_plot = (
alt.Chart(df)
.mark_bar()
.encode(
alt.Y(y),
alt.X(x),
opacity=alt.value(0.7),
color=alt.value("blue"),
)
.properties(title=title, width=700, height=300)
).interactive()
return bar_plot
def lineplot(df, y, x):
"""lineplot with input of a data frame"""
lineplot = (
alt.Chart(df)
.mark_line()
.encode(
alt.Y(y),
alt.X(x),
opacity=alt.value(0.7),
color=alt.value("blue"),
)
.properties(width=700, height=300)
).interactive()
return lineplot
def combined_area_plot(df, y, x):
brush = alt.selection(type="interval", encodings=["x"])
base = (
alt.Chart(df)
.mark_area()
.encode(
x=x,
y=y,
opacity=alt.value(0.7),
color=alt.value("blue"),
)
.properties(width=700, height=300)
).interactive()
upper = base.encode(alt.X(x, scale=alt.Scale(domain=brush)))
lower = base.properties(height=100).add_selection(brush)
combined = alt.vconcat(upper, lower)
return combined
def combined_bar_line_plot(df, y, x):
brush = alt.selection(type="interval", encodings=["x"])
base = barplot(df, y, x)
upper = base.encode(alt.X(x, scale=alt.Scale(domain=brush)))
lower = base.mark_line().properties(height=120).add_selection(brush)
combined = alt.vconcat(upper, lower)
return combined
def append_credentials(new_dict):
"""Uses the path to the credentials to add or update dictionary keys"""
with open(credentials_path, "r") as file:
old_dict = json.load(file)
old_dict.update(new_dict)
with open(credentials_path, "w") as file:
json.dump(old_dict, file, indent=4)
def get_twitter_credentials():
"""Get and store twitter credentials"""
st.write("## Please enter your Twitter developer application credentials:")
consumer_key = st.text_input("Please enter your consumer key",
value=auth_dict["CONSUMER_KEY"])
consumer_secret = st.text_input("Please enter your consumer secret key",
value=auth_dict["CONSUMER_SECRET"])
access_token = st.text_input("Please enter your access token",
value=auth_dict["ACCESS_TOKEN"])
secret_access_token = st.text_input(
"Please enter your secret access token",
value=auth_dict["ACCESS_TOKEN_SECRET"])
environment = st.text_input("Please enter your environment name",
value=auth_dict["ENVIRONMENT"])
if st.button("submit", key="Credentials"):
twitter_credentials = {"CONSUMER_KEY": consumer_key,
"CONSUMER_SECRET": consumer_secret,
"ACCESS_TOKEN": access_token,
"ACCESS_TOKEN_SECRET": secret_access_token,
"ENVIRONMENT": environment}
st.success("Twitter Credentials Updated!")
append_credentials({"TWITTER": twitter_credentials})
def get_aws_credentials():
"""Get and store AWS user credentials and create an
EC2 instance"""
st.write("## Please enter your AWS credentials:")
access_key = st.text_input("Please enter your access key")
secret_key = st.text_input("Please enter your secret key")
session_token = st.text_input("Please enter your session token")
if st.button("submit", key="Credentials"):
aws_credentials = {"access_key": access_key,
"secret_key": secret_key, "session_token": session_token}
new_ip = aws.begin_creation(access_key, secret_key, session_token)
st.success(f"Instance created. Instance IP {new_ip}")
append_credentials({"AWS": aws_credentials})
append_credentials({"ip_address": new_ip})
upload_and_execute(new_ip)
st.write("## OR add an accessible IP address:")
input_ip_address = st.text_input("Please enter your instance's IP address")
if st.button("submit", key="IP") and (not len(input_ip_address) == 0):
append_credentials({"ip_address": input_ip_address})
st.success("New IP Added!")
# upload_and_execute(input_ip_address)
def upload_and_execute(ip_address):
"""Connect to the AWS instance, upload files, and run the scripts"""
# NOTE: this assumes that the file is being run from repo root
stdout, stderr = driver.upload(
"ec2-auto", ip_address, upload_dir="./code/upload")
st.warning(stdout)
st.warning(stderr)
driver.ssh_execute("ec2-auto", ip_address)
def get_current_ip():
"""Open the credentials file and return IP address"""
with open(credentials_path, "r") as file:
credentials_dict = json.load(file)
if "ip_address" in credentials_dict.keys():
return credentials_dict["ip_address"]
else:
return None
def get_twitter_dict():
"""Open the credentials file and return Twitter dictionary"""
with open(credentials_path, "r") as file:
credentials_dict = json.load(file)
if "TWITTER" in credentials_dict.keys():
return credentials_dict["TWITTER"]
else:
return None
def main():
st.title("Stock Market and Twitter Sentiment Analysis")
# Retrieve credentials from local Json
# create empty json file if file does not exist
if os.path.exists(credentials_path):
with open(credentials_path, "r") as file:
credentials_dict = json.load(file)
else:
credentials_dict = {}
json.dump(credentials_dict, open(credentials_path, "w"))
# ============= Sidebar handling================
selection = st.sidebar.selectbox(
"Please select an operation",
options=["AWS Authentication", "Twitter Authentication"],
)
# Add a placeholder for textboxes and buttons
placeholder = st.sidebar.empty()
if selection == "AWS Authentication":
with placeholder.beta_container():
get_aws_credentials()
if selection == "Twitter Authentication":
with placeholder.beta_container():
get_twitter_credentials()
# ==============================================
# ============== Stock information input ===========
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
stock_ticker = st.text_input("Please enter a stock ticker")
start_date = st.date_input(
"Enter Start Date", value=yesterday, max_value=yesterday)
end_date = st.date_input(
"Enter End Date", min_value=start_date + datetime.timedelta(days=1), max_value=today)
if (today - start_date).days < 60:
interval = st.selectbox(
'Select a data interval', ("1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h", "1d", "5d", "1wk", "1mo", "3mo"))
else:
interval = st.selectbox(
'Select a data interval', ("1d", "5d", "1wk", "1mo", "3mo"))
if st.button("get info") and not(stock_ticker == ""):
ticker_info = get_company_info(stock_ticker)
stock_df = preprocess_stock_data(
(get_individual_stock_data(stock_ticker, start=start_date.strftime('%Y-%m-%d'), end=end_date.strftime('%Y-%m-%d'), interval=interval)))
col1, col2 = st.beta_columns(2)
company_logo_url = ticker_info["logo_url"]
company_name = ticker_info["shortName"]
company_website = ticker_info["website"]
with col1:
st.write(f"### About [{company_name}]({company_website})")
with col2:
st.markdown(f"")
st.write(ticker_info["longBusinessSummary"])
st.write("### Stock Charts:")
st.write(stock_df)
# st.altair_chart(barplot(stock_df, "Close", "Date"))
st.altair_chart(lineplot(stock_df, "Close", "Date"))
st.altair_chart(combined_area_plot(stock_df, "Close", "Date"))
# st.altair_chart(combined_bar_line_plot(stock_df, "Close", "Date"))
st.write("### Twitter Sentiment Charts:")
# get weekely data if range is less than 7 days
if (today - start_date).days <= 7:
sentiment_df = get_weekly_tweet_sentiment(stock_ticker)
else:
st.warning("Searching twitter data from over a week ago requires Twitter Premium credentials and could result in an error if maximum monthly requests are reached")
sentiment_df = get_range_sentiment(
stock_ticker, start_date, end_date)
st.altair_chart(lineplot(sentiment_df, "Sentiment", "Date"))
st.write(sentiment_df)
def get_company_info(ticker):
"""get individual stock general information"""
ip_address = get_current_ip()
if ip_address == None:
st.warning("IP not valid! Please Create an AWS instance or add valid IP")
return
response = requests.get(
f"http://{ip_address}/stocks/info?ticker={ticker}"
)
data_dict = response.json()
return data_dict
def get_range_sentiment(ticker, start_date, end_date):
"""Get weekly tweets from API and compute sentiment"""
ip_address = get_current_ip()
if ip_address == None:
st.warning("IP not valid! Please Create an AWS instance or add valid IP")
return
auth_dict = get_twitter_dict()
if auth_dict == None:
st.warning("Twitter credentials not found! Please add your credentials")
return
num_per_day = 100
tweets = {}
for day_since_start in range((end_date - start_date).days):
start_string = (start_date +
datetime.timedelta(days=day_since_start)).strftime("%Y%m%d%H%M")
end_string = (start_date +
datetime.timedelta(days=day_since_start + 1)).strftime("%Y%m%d%H%M")
request_string = f"http://{ip_address}/tweets?keyword={ticker}&start={start_string}&end={end_string}&num={num_per_day}"
response = requests.post(
request_string,
data=json.dumps(auth_dict),
)
response_dict = response.json()
tweets.update(response_dict)
time.sleep(5)
st.write(tweets)
polarity_dict = {}
# get average sentiment score of the date
for k, v in tweets.items():
score = 0
for text in v:
score += compute_sentiment_score(text)
polarity_dict[k] = score / len(v)
senti_dict = {"Date": polarity_dict.keys(
), "Sentiment": polarity_dict.values()}
sentiment_df = pd.DataFrame.from_dict(senti_dict)
# st.write(polarity_dict)
return sentiment_df
def compute_sentiment_score(text: str):
"""return the polarity score of a sentence"""
polarity = TextBlob(text).sentiment.polarity
return polarity
def get_weekly_tweet_sentiment(stock_symbol: str):
"""Get weekly tweets from API and compute sentiment"""
ip_address = get_current_ip()
if ip_address == None:
st.warning("IP not valid! Please Create an AWS instance or add valid IP")
return
auth_dict = get_twitter_dict()
if auth_dict == None:
st.warning("Twitter credentials not found! Please add your credentials")
return
response = requests.post(
f"http://{ip_address}/weeklyTweets?keyword={stock_symbol}",
data=json.dumps(auth_dict),
)
tweets = response.json()
polarity_dict = {}
# get average sentiment score of the date
for k, v in tweets.items():
score = 0
for text in v:
score += compute_sentiment_score(text)
polarity_dict[k] = score / len(v)
senti_dict = {"Date": polarity_dict.keys(
), "Sentiment": polarity_dict.values()}
sentiment_df = pd.DataFrame.from_dict(senti_dict)
return sentiment_df
if __name__ == "__main__":
main()
| enpuyou/aws-fastapi-streamlit | src/visualization.py | visualization.py | py | 13,343 | python | en | code | 2 | github-code | 1 | [
{
"api_name": "streamlit.warning",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "requests.get",
"line_number": 31,
"usage_type": "call"
},
{
"api_name": "pandas.DataFrame",
"line_number": 42,
"usage_type": "call"
},
{
"api_name": "pandas.to_datetime",
... |
24765487770 | import matplotlib.pyplot as plt
import cv2
import numpy as np
from os.path import join, basename
from collections import deque
from utils import grayscale, canny, gaussian_blur, hough_lines, get_slope, get_bias, draw_lines, weighted_img
# region of interest
def region_of_interest(image):
height = image.shape[0]
width = image.shape[1]
vertices = np.array( [[
[3*width/4, 3*height/5],
[width/4, 3*height/5],
[40, height],
[width - 40, height]
]], dtype=np.int32 )
#defining a blank mask to start with
mask = np.zeros_like(image)
# #defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(image.shape) > 2:
channel_count = image.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count # (255, 255, 255)
else:
ignore_mask_color = 255
#filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, ignore_mask_color)
#returning the image only where mask pixels are nonzero
masked_image = cv2.bitwise_and(image, mask)
return masked_image
# compute candidate lines
# and return left and right line coordinates
def compute_candidates(canditates_lines, img_shape):
global left_lane, right_line
# separate candidate lines according to their slope
pos_lines = [l for l in canditates_lines if l["slope"] > 0]
neg_lines = [l for l in canditates_lines if l["slope"] < 0]
# interpolate biases and slopes to compute equation of line that approximates left lane
# median is employed to filter outliers
neg_bias = np.median([l["bias"] for l in neg_lines]).astype(int)
neg_slope = np.median([l["slope"] for l in neg_lines])
x1, y1 = 0, neg_bias
x2, y2 = -np.int32(np.round(neg_bias / neg_slope)), 0
left_lane = np.array([x1, y1, x2, y2])
# interpolate biases and slopes to compute equation of line that approximates right lane
# median is employed to filter outliers
pos_bias = np.median([l["bias"] for l in pos_lines]).astype(int)
pos_slope = np.median([l["slope"] for l in pos_lines])
x1, y1 = 0, pos_bias
x2, y2 = np.int32(np.round((img_shape[0] - pos_bias) / pos_slope)), img_shape[0]
right_lane = np.array([x1, y1, x2, y2])
return [left_lane, right_lane]
def get_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
# convert to grayscale
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# perform gaussian blur
blur = gaussian_blur(img_gray, kernel_size=17)
# perform edge detection
canny_edges = canny(blur, low_threshold=50, high_threshold=70)
detected_lines = hough_lines(img=canny_edges,
rho=rho,
theta=theta,
threshold=threshold,
min_line_len=min_line_len,
max_line_gap=max_line_gap)
candidate_lines = []
for line in detected_lines:
for x1, y1, x2, y2 in line:
slope = get_slope(x1, y1, x2, y2)
if 0.5 <= np.abs(slope) <= 2:
candidate_lines.append({"slope": slope,
"bias": get_bias(slope, x1, y1)})
lane_lines = compute_candidates(candidate_lines, img_gray.shape)
return lane_lines
def last_lines_averages(lane_lines):
avg_lt = np.zeros((len(lane_lines), 4))
avg_lr = np.zeros((len(lane_lines), 4))
for i in range(0, len(lane_lines)):
# left line
x1, y1, x2, y2 = lane_lines[i][0]
avg_lt[i] += np.array([x1, y1, x2, y2])
# right line
x1, y1, x2, y2 = lane_lines[i][1]
avg_lr[i] += np.array([x1, y1, x2, y2])
return [np.mean(avg_lt, axis=0), np.mean(avg_lr, axis=0)]
def progress(frames):
detected_lines = []
# last 10 frames
for i in range(0, len(frames)):
# detect lines
left_right_lines = get_lines(img=frames[i],
rho=2,
theta=np.pi/180,
threshold=1,
min_line_len=15,
max_line_gap=5)
detected_lines.append(left_right_lines)
# prepare empty mask on which lines are drawn
line_img = np.zeros((frames[0].shape[0], frames[0].shape[1], 3), dtype=np.uint8)
# last 10 frames line averages
detected_lines = last_lines_averages(detected_lines)
# draw lines
for lane in detected_lines:
draw_lines(line_img, lane)
# region of interest
masked_img = region_of_interest(line_img)
# img_color = frames[-1] if is_videoclip else frames[0]
result = weighted_img(masked_img, frames[-1])
return result | namigaliyev/road-lane-tracking | lane_detection.py | lane_detection.py | py | 4,915 | python | en | code | 4 | github-code | 1 | [
{
"api_name": "numpy.array",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "numpy.int32",
"line_number": 18,
"usage_type": "attribute"
},
{
"api_name": "numpy.zeros_like",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "cv2.fillPoly",
"lin... |
8985294273 | from pycocotools.coco import COCO
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
import cv2 as cv
# =======================================
# =======================================
obj_class = 255
dataDir='E:/00_graduation project/DataSet/COCO/' # 数据集根目录
dataType='val2017' # 选择图像类型
annFile='{}2017_Train_Val_annotations/instances_{}.json'.format(dataDir,dataType) # annotation路径
# 蒙版绘制函数
def showAnns(mask, anns, c):
if len(anns) == 0: # 判断注释类型
return 0
if 'segmentation' in anns[0] or 'keypoints' in anns[0]:
datasetType = 'instances' # 蒙版
else:
raise Exception('datasetType not supported') # 错误
if datasetType == 'instances':
for ann in anns:
# c = (np.random.random((1, 3)) * 0.6 + 0.4).tolist()[0] # 随机生成标记颜色
if 'segmentation' in ann:
if type(ann['segmentation']) == list: # polygon多边形
for seg in ann['segmentation']:
poly = np.array(seg, np.int32).reshape((int(len(seg) / 2), 2)) # 将标记信息转换为坐标数组
poly = poly.reshape((-1, 1, 2)) # 修整顶点坐标数组格式
cv.fillPoly(mask, [poly], color=c) # 填充形状
# plt.imshow(mask)
# plt.show()
return mask
# 将COCO格式转换为VOC格式
# 图片形状[x,y,3], COCO标注信息, voc蒙版颜色
def coco2voc(imgShape, anns, color):
mask = np.zeros(imgShape, np.uint8) # 绘制纯黑底色
mask = showAnns(mask, anns, color) # 绘制mask
# mask = cv.cvtColor(mask, cv.COLOR_BGR2RGB)
# 获取图片ID
imgId = str(anns[0]['image_id']).zfill(12)
imgId_ = imgId + '.png'
src = dataDir + 'voc/'+ dataType + '/' + imgId_ # 组成路径
cv.imwrite(src, mask) # 保存图片
txt.write(imgId + '\n')
# initialize COCO api for instance annotations
coco=COCO(annFile) # 初始化coco类
''' # 输出所有分类名
# display COCO categories and supercategories
cats = coco.loadCats(coco.getCatIds()) # 获取类别列表,列表中元素是存储着类名、id和亚类的字典
nms=[cat['name'] for cat in cats] # 遍历类别列表,取出所有类的name
print('COCO categories: \n{}\n'.format(' '.join(nms))) # 打印类名
nms = set([cat['supercategory'] for cat in cats]) # set无序不重复序列 取出所有亚类
print('COCO supercategories: \n{}'.format(' '.join(nms))) # 打印类名
'''
# get all images containing given categories
catIds = coco.getCatIds(catNms=['person']) # 获取指定类别的id
imgIds = coco.getImgIds(catIds=catIds) # 获取包含指定类别id的图像id
# ==========================================
# 遍历满足条件的图像
# ==========================================
txt = open(dataDir + 'voc/'+ dataType + '.txt', "w") # 创建txt记录转换的图片id
print("transforming...")
count = 0
for i in tqdm(imgIds):
img = coco.loadImgs(i)[0] # 获取第一个图像的json
# load and display image
I = cv.imread('%s/%s/%s' % (dataDir, dataType, img['file_name'])) # 从本地加载图像
# I = cv.cvtColor(I, cv.COLOR_BGR2RGB) # 转换颜色格式
# use url to load image
# I = cv.imread(img['coco_url']) # 通过网络从远程加载图
# ==============================================
# load and display instance annotations
# ==============================================
imgShape = I.shape # 得到图片尺寸
annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None) # 得到指定图像对应类型的annotation id
anns = coco.loadAnns(annIds) # 根据annotation id加载蒙版json
color = [obj_class, obj_class, obj_class] # 蒙版颜色
coco2voc(imgShape, anns, color)
count = count + 1
txt.close()
print(f"transform completely. total:{count}") | Gao-Jinlong/Graduation-Project | U-Net/utils/coco_to_voc.py | coco_to_voc.py | py | 3,911 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "numpy.array",
"line_number": 29,
"usage_type": "call"
},
{
"api_name": "numpy.int32",
"line_number": 29,
"usage_type": "attribute"
},
{
"api_name": "cv2.fillPoly",
"line_number": 31,
"usage_type": "call"
},
{
"api_name": "numpy.zeros",
"line_num... |
23205933467 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
from dgl.base import DGLError
from dgl.ops import edge_softmax
import dgl.function as fn
class Identity(nn.Module):
"""A placeholder identity operator that is argument-insensitive.
(Identity has already been supported by PyTorch 1.2, we will directly
import torch.nn.Identity in the future)
"""
def __init__(self):
super(Identity, self).__init__()
def forward(self, x):
"""Return input"""
return x
class MsgLinkPredictor(nn.Module):
"""Predict Pair wise link from pos subg and neg subg
use message passing.
Use Two layer MLP on edge to predict the link probability
Parameters
----------
embed_dim : int
dimension of each each feature's embedding
Example
----------
>>> linkpred = MsgLinkPredictor(10)
>>> pos_g = dgl.graph(([0,1,2,3,4],[1,2,3,4,0]))
>>> neg_g = dgl.graph(([0,1,2,3,4],[2,1,4,3,0]))
>>> x = torch.ones(5,10)
>>> linkpred(x,pos_g,neg_g)
(tensor([[0.0902],
[0.0902],
[0.0902],
[0.0902],
[0.0902]], grad_fn=<AddmmBackward>),
tensor([[0.0902],
[0.0902],
[0.0902],
[0.0902],
[0.0902]], grad_fn=<AddmmBackward>))
"""
def __init__(self, emb_dim):
super(MsgLinkPredictor, self).__init__()
self.src_fc = nn.Linear(emb_dim, emb_dim)
self.dst_fc = nn.Linear(emb_dim, emb_dim)
self.out_fc = nn.Linear(emb_dim, 1)
def link_pred(self, edges):
src_hid = self.src_fc(edges.src['embedding'])
dst_hid = self.dst_fc(edges.dst['embedding'])
score = F.relu(src_hid+dst_hid)
score = self.out_fc(score)
return {'score': score}
def forward(self, x, pos_g, neg_g):
# Local Scope?
pos_g.ndata['embedding'] = x
neg_g.ndata['embedding'] = x
pos_g.apply_edges(self.link_pred)
neg_g.apply_edges(self.link_pred)
pos_escore = pos_g.edata['score']
neg_escore = neg_g.edata['score']
return pos_escore, neg_escore
class TimeEncode(nn.Module):
"""Use finite fourier series with different phase and frequency to encode
time different between two event
..math::
\Phi(t) = [\cos(\omega_0t+\psi_0),\cos(\omega_1t+\psi_1),...,\cos(\omega_nt+\psi_n)]
Parameter
----------
dimension : int
Length of the fourier series. The longer it is ,
the more timescale information it can capture
Example
----------
>>> tecd = TimeEncode(10)
>>> t = torch.tensor([[1]])
>>> tecd(t)
tensor([[[0.5403, 0.9950, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000]]], dtype=torch.float64, grad_fn=<CosBackward>)
"""
def __init__(self, dimension):
super(TimeEncode, self).__init__()
self.dimension = dimension
self.w = torch.nn.Linear(1, dimension)
self.w.weight = torch.nn.Parameter((torch.from_numpy(1 / 10 ** np.linspace(0, 9, dimension)))
.double().reshape(dimension, -1))
self.w.bias = torch.nn.Parameter(torch.zeros(dimension).double())
def forward(self, t):
t = t.unsqueeze(dim=2)
output = torch.cos(self.w(t))
return output
class MemoryModule(nn.Module):
"""Memory module as well as update interface
The memory module stores both historical representation in last_update_t
Parameters
----------
n_node : int
number of node of the entire graph
hidden_dim : int
dimension of memory of each node
Example
----------
Please refers to examples/pytorch/tgn/tgn.py;
examples/pytorch/tgn/train.py
"""
def __init__(self, n_node, hidden_dim):
super(MemoryModule, self).__init__()
self.n_node = n_node
self.hidden_dim = hidden_dim
self.reset_memory()
def reset_memory(self):
self.last_update_t = nn.Parameter(torch.zeros(
self.n_node).float(), requires_grad=False)
self.memory = nn.Parameter(torch.zeros(
(self.n_node, self.hidden_dim)).float(), requires_grad=False)
def backup_memory(self):
"""
Return a deep copy of memory state and last_update_t
For test new node, since new node need to use memory upto validation set
After validation, memory need to be backed up before run test set without new node
so finally, we can use backup memory to update the new node test set
"""
return self.memory.clone(), self.last_update_t.clone()
def restore_memory(self, memory_backup):
"""Restore the memory from validation set
Parameters
----------
memory_backup : (memory,last_update_t)
restore memory based on input tuple
"""
self.memory = memory_backup[0].clone()
self.last_update_t = memory_backup[1].clone()
# Which is used for attach to subgraph
def get_memory(self, node_idxs):
return self.memory[node_idxs, :]
# When the memory need to be updated
def set_memory(self, node_idxs, values):
self.memory[node_idxs, :] = values
def set_last_update_t(self, node_idxs, values):
self.last_update_t[node_idxs] = values
# For safety check
def get_last_update(self, node_idxs):
return self.last_update_t[node_idxs]
def detach_memory(self):
"""
Disconnect the memory from computation graph to prevent gradient be propagated multiple
times
"""
self.memory.detach_()
class MemoryOperation(nn.Module):
""" Memory update using message passing manner, update memory based on positive
pair graph of each batch with recurrent module GRU or RNN
Message function
..math::
m_i(t) = concat(memory_i(t^-),TimeEncode(t),v_i(t))
v_i is node feature at current time stamp
Aggregation function
..math::
\bar{m}_i(t) = last(m_i(t_1),...,m_i(t_b))
Update function
..math::
memory_i(t) = GRU(\bar{m}_i(t),memory_i(t-1))
Parameters
----------
updater_type : str
indicator string to specify updater
'rnn' : use Vanilla RNN as updater
'gru' : use GRU as updater
memory : MemoryModule
memory content for update
e_feat_dim : int
dimension of edge feature
temporal_dim : int
length of fourier series for time encoding
Example
----------
Please refers to examples/pytorch/tgn/tgn.py
"""
def __init__(self, updater_type, memory, e_feat_dim, temporal_encoder):
super(MemoryOperation, self).__init__()
updater_dict = {'gru': nn.GRUCell, 'rnn': nn.RNNCell}
self.memory = memory
memory_dim = self.memory.hidden_dim
self.temporal_encoder = temporal_encoder
self.message_dim = memory_dim+memory_dim + \
e_feat_dim+self.temporal_encoder.dimension
self.updater = updater_dict[updater_type](input_size=self.message_dim,
hidden_size=memory_dim)
self.memory = memory
# Here assume g is a subgraph from each iteration
def stick_feat_to_graph(self, g):
# How can I ensure order of the node ID
g.ndata['timestamp'] = self.memory.last_update_t[g.ndata[dgl.NID]]
g.ndata['memory'] = self.memory.memory[g.ndata[dgl.NID]]
def msg_fn_cat(self, edges):
src_delta_time = edges.data['timestamp'] - edges.src['timestamp']
time_encode = self.temporal_encoder(src_delta_time.unsqueeze(
dim=1)).view(len(edges.data['timestamp']), -1)
ret = torch.cat([edges.src['memory'], edges.dst['memory'],
edges.data['feats'], time_encode], dim=1)
return {'message': ret, 'timestamp': edges.data['timestamp']}
def agg_last(self, nodes):
timestamp, latest_idx = torch.max(nodes.mailbox['timestamp'], dim=1)
ret = nodes.mailbox['message'].gather(1, latest_idx.repeat(
self.message_dim).view(-1, 1, self.message_dim)).view(-1, self.message_dim)
return {'message_bar': ret.reshape(-1, self.message_dim), 'timestamp': timestamp}
def update_memory(self, nodes):
# It should pass the feature through RNN
ret = self.updater(
nodes.data['message_bar'].float(), nodes.data['memory'].float())
return {'memory': ret}
def forward(self, g):
self.stick_feat_to_graph(g)
g.update_all(self.msg_fn_cat, self.agg_last, self.update_memory)
return g
class EdgeGATConv(nn.Module):
'''Edge Graph attention compute the graph attention from node and edge feature then aggregate both node and
edge feature.
Parameter
==========
node_feats : int
number of node features
edge_feats : int
number of edge features
out_feats : int
number of output features
num_heads : int
number of heads in multihead attention
feat_drop : float, optional
drop out rate on the feature
attn_drop : float, optional
drop out rate on the attention weight
negative_slope : float, optional
LeakyReLU angle of negative slope.
residual : bool, optional
whether use residual connection
allow_zero_in_degree : bool, optional
If there are 0-in-degree nodes in the graph, output for those nodes will be invalid
since no message will be passed to those nodes. This is harmful for some applications
causing silent performance regression. This module will raise a DGLError if it detects
0-in-degree nodes in input graph. By setting ``True``, it will suppress the check
and let the users handle it by themselves. Defaults: ``False``.
'''
def __init__(self,
node_feats,
edge_feats,
out_feats,
num_heads,
feat_drop=0.,
attn_drop=0.,
negative_slope=0.2,
residual=False,
activation=None,
allow_zero_in_degree=False):
super(EdgeGATConv, self).__init__()
self._num_heads = num_heads
self._node_feats = node_feats
self._edge_feats = edge_feats
self._out_feats = out_feats
self._allow_zero_in_degree = allow_zero_in_degree
self.fc_node = nn.Linear(
self._node_feats, self._out_feats*self._num_heads)
self.fc_edge = nn.Linear(
self._edge_feats, self._out_feats*self._num_heads)
self.attn_l = nn.Parameter(torch.FloatTensor(
size=(1, self._num_heads, self._out_feats)))
self.attn_r = nn.Parameter(torch.FloatTensor(
size=(1, self._num_heads, self._out_feats)))
self.attn_e = nn.Parameter(torch.FloatTensor(
size=(1, self._num_heads, self._out_feats)))
self.feat_drop = nn.Dropout(feat_drop)
self.attn_drop = nn.Dropout(attn_drop)
self.leaky_relu = nn.LeakyReLU(negative_slope)
self.residual = residual
if residual:
if self._node_feats != self._out_feats:
self.res_fc = nn.Linear(
self._node_feats, self._out_feats*self._num_heads, bias=False)
else:
self.res_fc = Identity()
self.reset_parameters()
self.activation = activation
def reset_parameters(self):
gain = nn.init.calculate_gain('relu')
nn.init.xavier_normal_(self.fc_node.weight, gain=gain)
nn.init.xavier_normal_(self.fc_edge.weight, gain=gain)
nn.init.xavier_normal_(self.attn_l, gain=gain)
nn.init.xavier_normal_(self.attn_r, gain=gain)
nn.init.xavier_normal_(self.attn_e, gain=gain)
if self.residual and isinstance(self.res_fc, nn.Linear):
nn.init.xavier_normal_(self.res_fc.weight, gain=gain)
def msg_fn(self, edges):
ret = edges.data['a'].view(-1, self._num_heads,
1)*edges.data['el_prime']
return {'m': ret}
def forward(self, graph, nfeat, efeat, get_attention=False):
with graph.local_scope():
if not self._allow_zero_in_degree:
if (graph.in_degrees() == 0).any():
raise DGLError('There are 0-in-degree nodes in the graph, '
'output for those nodes will be invalid. '
'This is harmful for some applications, '
'causing silent performance regression. '
'Adding self-loop on the input graph by '
'calling `g = dgl.add_self_loop(g)` will resolve '
'the issue. Setting ``allow_zero_in_degree`` '
'to be `True` when constructing this module will '
'suppress the check and let the code run.')
nfeat = self.feat_drop(nfeat)
efeat = self.feat_drop(efeat)
node_feat = self.fc_node(
nfeat).view(-1, self._num_heads, self._out_feats)
edge_feat = self.fc_edge(
efeat).view(-1, self._num_heads, self._out_feats)
el = (node_feat*self.attn_l).sum(dim=-1).unsqueeze(-1)
er = (node_feat*self.attn_r).sum(dim=-1).unsqueeze(-1)
ee = (edge_feat*self.attn_e).sum(dim=-1).unsqueeze(-1)
graph.ndata['ft'] = node_feat
graph.ndata['el'] = el
graph.ndata['er'] = er
graph.edata['ee'] = ee
graph.apply_edges(fn.u_add_e('el', 'ee', 'el_prime'))
graph.apply_edges(fn.e_add_v('el_prime', 'er', 'e'))
e = self.leaky_relu(graph.edata['e'])
graph.edata['a'] = self.attn_drop(edge_softmax(graph, e))
graph.edata['efeat'] = edge_feat
graph.update_all(self.msg_fn, fn.sum('m', 'ft'))
rst = graph.ndata['ft']
if self.residual:
resval = self.res_fc(nfeat).view(
nfeat.shape[0], -1, self._out_feats)
rst = rst + resval
if self.activation:
rst = self.activation(rst)
if get_attention:
return rst, graph.edata['a']
else:
return rst
class TemporalEdgePreprocess(nn.Module):
'''Preprocess layer, which finish time encoding and concatenate
the time encoding to edge feature.
Parameter
==========
edge_feats : int
number of orginal edge feature
temporal_encoder : torch.nn.Module
time encoder model
'''
def __init__(self, edge_feats, temporal_encoder):
super(TemporalEdgePreprocess, self).__init__()
self.edge_feats = edge_feats
self.temporal_encoder = temporal_encoder
def edge_fn(self, edges):
t0 = torch.zeros_like(edges.dst['timestamp'])
time_diff = edges.data['timestamp'] - edges.src['timestamp']
time_encode = self.temporal_encoder(
time_diff.unsqueeze(dim=1)).view(t0.shape[0], -1)
edge_feat = torch.cat([edges.data['feats'], time_encode], dim=1)
return {'efeat': edge_feat}
def forward(self, graph):
graph.apply_edges(self.edge_fn)
efeat = graph.edata['efeat']
return efeat
class TemporalTransformerConv(nn.Module):
def __init__(self,
edge_feats,
memory_feats,
temporal_encoder,
out_feats,
num_heads,
allow_zero_in_degree=False,
layers=1):
'''Temporal Transformer model for TGN and TGAT
Parameter
==========
edge_feats : int
number of edge features
memory_feats : int
dimension of memory vector
temporal_encoder : torch.nn.Module
compute fourier time encoding
out_feats : int
number of out features
num_heads : int
number of attention head
allow_zero_in_degree : bool, optional
If there are 0-in-degree nodes in the graph, output for those nodes will be invalid
since no message will be passed to those nodes. This is harmful for some applications
causing silent performance regression. This module will raise a DGLError if it detects
0-in-degree nodes in input graph. By setting ``True``, it will suppress the check
and let the users handle it by themselves. Defaults: ``False``.
'''
super(TemporalTransformerConv, self).__init__()
self._edge_feats = edge_feats
self._memory_feats = memory_feats
self.temporal_encoder = temporal_encoder
self._out_feats = out_feats
self._allow_zero_in_degree = allow_zero_in_degree
self._num_heads = num_heads
self.layers = layers
self.preprocessor = TemporalEdgePreprocess(
self._edge_feats, self.temporal_encoder)
self.layer_list = nn.ModuleList()
self.layer_list.append(EdgeGATConv(node_feats=self._memory_feats,
edge_feats=self._edge_feats+self.temporal_encoder.dimension,
out_feats=self._out_feats,
num_heads=self._num_heads,
feat_drop=0.6,
attn_drop=0.6,
residual=True,
allow_zero_in_degree=allow_zero_in_degree))
for i in range(self.layers-1):
self.layer_list.append(EdgeGATConv(node_feats=self._out_feats*self._num_heads,
edge_feats=self._edge_feats+self.temporal_encoder.dimension,
out_feats=self._out_feats,
num_heads=self._num_heads,
feat_drop=0.6,
attn_drop=0.6,
residual=True,
allow_zero_in_degree=allow_zero_in_degree))
def forward(self, graph, memory, ts):
graph = graph.local_var()
graph.ndata['timestamp'] = ts
efeat = self.preprocessor(graph).float()
rst = memory
for i in range(self.layers-1):
rst = self.layer_list[i](graph, rst, efeat).flatten(1)
rst = self.layer_list[-1](graph, rst, efeat).mean(1)
return rst
| taotianli/gin_model.py | examples/pytorch/tgn/modules.py | modules.py | py | 18,905 | python | en | code | 5 | github-code | 1 | [
{
"api_name": "torch.nn.Module",
"line_number": 12,
"usage_type": "attribute"
},
{
"api_name": "torch.nn",
"line_number": 12,
"usage_type": "name"
},
{
"api_name": "torch.nn.Module",
"line_number": 26,
"usage_type": "attribute"
},
{
"api_name": "torch.nn",
"li... |
69890553314 | import agent.potil_lstm as agent
from expert_dataloader import ExpertLoader, ExpertLoader_each_step
import agent.utils as utils
import sys
sys.path.append('/catkin_workspace/src/ros_kortex/kortex_examples/src/move_it')
import torch
torch.backends.cudnn.benchmark = True
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
import queue
potil_agent = agent.POTILAgent(obs_shape=[4, 1], action_shape=[4, 1], device='cuda', lr=1e-3, feature_dim=512,
hidden_dim=128, critic_target_tau=0.01, num_expl_steps=0,
update_every_steps=2, stddev_schedule='linear(0.2,0.04,500000)', stddev_clip=0.1, use_tb=True, augment=True,
rewards='sinkhorn_cosine', sinkhorn_rew_scale=200, update_target_every=10000,
auto_rew_scale=True, auto_rew_scale_factor=10, obs_type='env', bc_weight_type='linear',
bc_weight_schedule='linear(0.15,0.03,20000)')
nstep = 32
# expert_loader = ExpertLoader(nstep, 50)
# expert_iter = iter(expert_loader)
# test_data = expert_loader.read_data(0,1)
# state, action = test_data
# seq_queue = queue.Queue(nstep)
# test_data_storage = []
# for i in range(nstep):
# seq_queue.put(state[0])
# for i in range(state.shape[0]):
# seq_queue.get()
# seq_queue.put(state[i])
# test_data_storage.append((np.stack(seq_queue.queue), action[i]))
# with step
expert_loader = ExpertLoader_each_step(nstep, 50)
expert_iter = iter(expert_loader)
test_data = expert_loader.read_data(0,1)
state, action = test_data
seq_queue = queue.Queue(nstep)
test_data_storage = []
for i in range(nstep):
seq_queue.put(state[0])
for i in range(state.shape[0]):
seq_queue.get()
seq_queue.put(state[i])
test_data_storage.append((np.stack(seq_queue.queue), action[i]))
cnt = 1
# def test():
# obs = utils.to_torch(test_data, 'cuda')[0]
# replay = []
# for i in range(80):
# with torch.no_grad():
# action = potil_agent.act(obs, 0, True)
# action[0] = (action[0] + 1.3) * 0.2 + 0.2
# action[1] = (action[1] + 1) * 1.1 * -0.1
# action[2] = (action[2] + 0.75) * 0.125 + 0.05
# action[3] = (action[3] + 1) * 0.2
# obs[:4] = torch.from_numpy(action).cuda()
# replay.append(obs)
# fig = plt.figure()
# #创建3d绘图区域
# ax = plt.axes(projection='3d')
# #从三个维度构建
# z = test_data[0][:,2]
# x = test_data[0][:,0]
# y = test_data[0][:,1]
# #调用 ax.plot3D创建三维线图
# ax.scatter3D(x, y, z,'gray', s=1)
# replay = np.stack(replay)
# z = replay[:,2]
# x = replay[:,0]
# y = replay[:,1]
# #调用 ax.plot3D创建三维线图
# ax.scatter3D(x, y, z,'gray', s=1)
# plt.savefig(f'./figs/{cnt}.png')
# cnt += 1
def scale(action_):
action = action_.copy()
action[0] = (action[0] + 1.31) * 0.2 + 0.2
action[1] = (action[1] + 0.84) * 1.1 * -0.11
action[2] = (action[2] + 0.83) * 0.15 + 0.05
action[3] = (action[3] + 1) * 0.25
return action
def test():
loss = 0
for data in test_data_storage:
data = utils.to_torch(data, 'cuda')
with torch.no_grad():
action = potil_agent.act(data[0][:, :4], 0, True)
loss += np.linalg.norm(scale(action) - scale(data[1].cpu().numpy()), ord=1)
loss /= state.shape[0]
print(loss)
# for i in range(100000):
# batch = next(expert_iter)
# obs_bc, action_bc = utils.to_torch(batch, 'cuda')
# metrics = potil_agent.train_bc_norm(obs_bc, action_bc)
# # if i % 10 == 1:
# # print(metrics['bc_loss'])
# if i % 20 == 0:
# test()
# if i % 100 == 0:
# torch.save(potil_agent.actor, 'BC_actor_norm.pkl')
# for i in range(100000):
# batch = next(expert_iter)
# obs_bc, action_bc = utils.to_torch(batch, 'cuda')
# metrics = potil_agent.train_bc_dist(obs_bc, action_bc)
# # if i % 10 == 1:
# # print(metrics['bc_loss'])
# if i % 100 == 0:
# test()
# if i % 100 == 0:
# torch.save(potil_agent.actor, 'BC_actor_dist.pkl')
# potil_agent.actor = torch.load('/catkin_workspace/src/ros_kortex/kortex_examples/src/move_it/BC_actor_dist.pkl').cuda()
potil_agent.actor.train()
potil_agent.actor_opt = torch.optim.Adam(potil_agent.actor.parameters(), lr=potil_agent.lr)
for i in range(100000):
batch = next(expert_iter)
obs_bc, action_bc = utils.to_torch(batch, 'cuda')
metrics = potil_agent.train_bc_norm_step(obs_bc[:,:,:4], action_bc)
# if i % 10 == 1:
# print(metrics['bc_loss'])
if i % 100 == 0:
test()
if i % 100 == 0:
torch.save(potil_agent.actor, 'BC_actor_dist.pkl')
| ZDDWLIG/KinovaArm_PegInsert_DRL | BC_train.py | BC_train.py | py | 4,776 | python | en | code | 3 | github-code | 1 | [
{
"api_name": "sys.path.append",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "sys.path",
"line_number": 5,
"usage_type": "attribute"
},
{
"api_name": "torch.backends",
"line_number": 7,
"usage_type": "attribute"
},
{
"api_name": "agent.potil_lstm.POTIL... |
12316864652 | import matplotlib.pyplot as plt
x_list = []
y_list = []
def process(line):
### transformation matix 로 궤적 얻기 ##############################################################
pose = line.strip().split()
x_list.append(float(pose[3])) # position
y_list.append(float(pose[11]))
##################################################################################################
file_path = '/media/doyu_now/Linux Workspace/ICSL_Project/Visual SLAM/KITTI_data_odometry_color/data_odometry_poses/dataset/poses/10.txt'
with open(file_path, 'r') as f:
while True:
line = f.readline()
if not line:
print("End Of File")
break
process(line)
plt.plot(x_list, y_list, 'ob')
plt.title('kitti odom - scenario 10')
plt.show() | owl-d/Visual_Odometry_Basic | 05_trajectory_visualization/kitti_odom_visual.py | kitti_odom_visual.py | py | 823 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "matplotlib.pyplot.plot",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot",
"line_number": 28,
"usage_type": "name"
},
{
"api_name": "matplotlib.pyplot.title",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "matp... |
71276797475 | # Python standard libraries
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import json
import sqlite3
# Third-party libraries
from flask import Flask, redirect, request, url_for, render_template
from flask_login import (
LoginManager,
current_user,
login_required,
login_user,
logout_user,
UserMixin,
)
from oauthlib.oauth2 import WebApplicationClient
import requests
# Internal imports
from etl.gcp_utils import init_connection_engine, access_secret
from data_viz import journal_calendar
# Configuration
PROJECT_ID = os.getenv("PROJECT_ID")
try:
GOOGLE_CLIENT_ID = access_secret(project_id=PROJECT_ID,secret_id="CLIENT_ID")
GOOGLE_CLIENT_SECRET = access_secret(project_id=PROJECT_ID,secret_id="CLIENT_SECRET")
EMAIL = access_secret(project_id=PROJECT_ID,secret_id="EMAIL")
except: # google.api_core.exceptions.PermissionDenied
GOOGLE_CLIENT_ID = os.getenv("CLIENT_ID")
GOOGLE_CLIENT_SECRET = os.getenv("CLIENT_SECRET")
LOCAL_DB = os.getenv("LOCAL_DB")
EMAIL = os.getenv("EMAIL")
finally:
GOOGLE_DISCOVERY_URL = 'https://accounts.google.com/.well-known/openid-configuration'
DB_URL = os.getenv('DB_URL')
# TODO: Resolve testing with this initial database declaration.
db = None
db= sqlite3
app = Flask(__name__)
app.secret_key = os.getenv("SECRET_KEY") or os.urandom(24)
# User session management setup
# https://flask-login.readthedocs.io/en/latest
login_manager = LoginManager()
login_manager.init_app(app)
# OAuth 2 client setup
client = WebApplicationClient(GOOGLE_CLIENT_ID)
# User class for flask-login
class User(UserMixin):
def __init__(self, email):
self.id = email
@staticmethod
def get(user_id):
user = User(email=user_id)
return user
# Flask-Login helper to retrieve a user from our db
@login_manager.user_loader
def load_user(user_id):
return User.get(user_id)
# TODO: Add error handling
def get_google_provider_cfg():
return requests.get(GOOGLE_DISCOVERY_URL).json()
@app.route("/")
def login():
# Find out what URL to hit for Google login.
google_provider_cfg = get_google_provider_cfg()
authorization_endpoint = google_provider_cfg["authorization_endpoint"]
# Construct Google login request and retrieve user profile.
request_uri = client.prepare_request_uri(
authorization_endpoint,
redirect_uri=request.base_url + "login/callback",
scope=["openid", "email", "profile"],
)
return redirect(request_uri)
@app.route("/login/callback")
def callback():
# Get authorization code from Google.
code = request.args.get("code")
# Get User token URL.
google_provider_cfg = get_google_provider_cfg()
token_endpoint = google_provider_cfg["token_endpoint"]
# Prepare and send a request to get tokens.
token_url, headers, body = client.prepare_token_request(
token_endpoint,
authorization_response=request.url,
redirect_url=request.base_url,
code=code
)
token_response = requests.post(
token_url,
headers=headers,
data=body,
auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
)
# Parse tokens.
client.parse_request_body_response(json.dumps(token_response.json()))
# Get Google account information,
userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
uri, headers, body = client.add_token(userinfo_endpoint)
userinfo_response = requests.get(uri, headers=headers, data=body)
# Verify email address for Google account.
if userinfo_response.json()["email"] != EMAIL:
return "User email not available or not verified by Google.", 400
user = User(email=EMAIL)
# Begin user session by logging the user in
login_user(user)
# Send user to homepage if Google account is verified.
return redirect(url_for("codex_vitae"))
@login_required
@app.route('/logout')
def logout():
if current_user.is_authenticated:
logout_user()
return redirect(url_for("login"))
@login_required
@app.route('/codex-vitae')
def codex_vitae():
if current_user.is_authenticated:
# Connect to DB and plot journal entries.
global db
db = db or init_connection_engine()
with db.connect(LOCAL_DB) as conn:
journal_tuples = conn.execute(
"select * from journal_view order by date"
).fetchall()
journal = journal_calendar(journal_tuples)
return render_template('index.html', plot=journal)
return "Please Log In."
if __name__ == '__main__':
app.run(ssl_context="adhoc",debug=True)
| ColtAllen/codex_vitae_app | codex_vitae/app.py | app.py | py | 4,766 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "os.getenv",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "etl.gcp_utils.access_secret",
"line_number": 33,
"usage_type": "call"
},
{
"api_name": "etl.gcp_utils.access_secret",
"line_number": 34,
"usage_type": "call"
},
{
"api_name": "etl... |
8533855613 | import getopt
import sys
from prisma.calibrate import main_loop
# parse arguments
try:
opts, args = getopt.getopt(sys.argv[1:], "d:", ["days_to_sync="])
except getopt.GetoptError:
print("Please provide proper arguments.")
print("Usage: $python3 sync_fripon.py --d=<days>")
sys.exit(2)
for opt, arg in opts:
if opt in ("-d", "--days_to_sync"):
last_n_days = int(arg)
if __name__ == "__main__":
main_loop()
| Matteo04052017/PRISMA_automation | src/run_calibration.py | run_calibration.py | py | 441 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "getopt.getopt",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "sys.argv",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "getopt.GetoptError",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "sys.exit",
"lin... |
4752869794 | #!/usr/bin/env python
""" This module has api-key-specific methods """
import argparse
from api_request.request import *
class UNIQUE_ID():
def __init__(self, director_url):
self.base_url = director_url + "/v3" + "/settings/websocketproxy.unique.identity"
requestobj = Data('', '')
self.request = requestobj
def getId(self, jwt):
url = self.base_url
cookie = {'token': jwt,'authProvider': 'localAuthConfig'}
response = self.request.getByCookie(url, cookie)
id = response['value']
print(id)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--url",
help="director onprem url")
parser.add_argument("--token",
help="token")
args = parser.parse_args()
director_url = args.url
token = args.token
api_key_obj = UNIQUE_ID(director_url)
api_key_obj.getId(token)
if __name__ == '__main__':
main() | mayadata-io/oep-e2e | api_testing/unique-id/unique-id.py | unique-id.py | py | 964 | python | en | code | 6 | github-code | 1 | [
{
"api_name": "argparse.ArgumentParser",
"line_number": 22,
"usage_type": "call"
}
] |
16516618905 | from __future__ import absolute_import, division, print_function,\
with_statement
import collections
import errno
import socket
import logging
import ssl
import sys
from tornado import ioloop
from tornado.log import gen_log
from tornado.netutil import ssl_wrap_socket, ssl_match_hostname, \
SSLCertificateError
from tornado import stack_context
from datetime import timedelta
try:
from tornado.platform.posix import _set_nonblocking
except ImportError:
_set_nonblocking = None
# These errnos indicate that a non-blocking operation must be retried
# at a later time. On most platforms they're the same value, but on
# some they differ.
_ERRNO_WOULDBLOCK = (errno.EWOULDBLOCK, errno.EAGAIN)
# These errnos indicate that a connection has been abruptly terminated.
# They should be caught and handled less noisily than other errors.
_ERRNO_CONNRESET = (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE)
# Nice constant for enabling debug output
import sys
_SHOULD_LOG_DEBUG_OUTPUT = gen_log.isEnabledFor(logging.DEBUG)
class StreamClosedError(IOError):
"""Exception raised by `IOStream` methods when the stream is closed.
Note that the close callback is scheduled to run *after* other
callbacks on the stream (to allow for buffered data to be processed),
so you may see this error before you see the close callback.
"""
pass
class WriteQueue(object):
def __init__(self):
self._last_send_idx = 0
self._write_queue = collections.deque()
def has_next(self):
return len(self._write_queue) > 0
def next(self):
if self.has_next():
return (self._write_queue[0], self._last_send_idx)
return None
def clear(self):
self._write_queue.clear()
def append(self, src):
self._write_queue.append(src)
def advance(self, bytes_to_advance):
next_src = self._write_queue[0]
if bytes_to_advance + self._last_send_idx >= len(next_src):
self._write_queue.popleft()
self._last_send_idx = 0
else:
self._last_send_idx += bytes_to_advance
class IOHandler(object):
def __init__(self, io_loop=None):
# Bind to the eventloop
self._io_loop = io_loop or ioloop.IOLoop.current()
# Error tracking
self.error = 0
# Callbacks
self._connect_cb = None
self._close_cb = None
self._read_cb = None
self._write_cb = None
# TODO:Review - Is this a good idea?
self._error_cb = None
def reading(self):
raise NotImplementedError()
def writing(self):
raise NotImplementedError()
def closed(self):
raise NotImplementedError()
def read(self, callback):
raise NotImplementedError()
def write(self, src, callback=None):
raise NotImplementedError()
def connect(self, address, callback=None):
raise NotImplementedError()
def close(self):
raise NotImplementedError()
class FileDescriptorHandle(object):
def __init__(self, fd, io_loop):
assert fd is not None
assert io_loop is not None
self.fd = fd
self._io_loop = io_loop
self._event_interest = None
def is_reading(self):
return self._event_interest & self._io_loop.READ
def is_writing(self):
return self._event_interest & self._io_loop.WRITE
def set_handler(self, event_handler):
"""initialize the ioloop event handler"""
assert event_handler is not None and callable(event_handler)
self._event_interest = self._io_loop.ERROR
with stack_context.NullContext():
self._io_loop.add_handler(
self.fd,
event_handler,
self._event_interest)
def remove_handler(self):
self._io_loop.remove_handler(self.fd)
def disable_reading(self):
"""
Alias for removing the read interest from the event handler.
"""
if _SHOULD_LOG_DEBUG_OUTPUT:
gen_log.debug('Halting read events for stream(fd:{})'.format(
self.fd))
self._drop_event_interest(self._io_loop.READ)
def disable_writing(self):
"""
Alias for removing the send interest from the event handler.
"""
if _SHOULD_LOG_DEBUG_OUTPUT:
gen_log.debug('Halting write events for stream(fd:{})'.format(
self.fd))
self._drop_event_interest(self._io_loop.WRITE)
def resume_reading(self):
"""
Alias for adding the read interest to the event handler.
"""
if _SHOULD_LOG_DEBUG_OUTPUT:
gen_log.debug('Resuming recv events for stream(fd:{})'.format(
self.fd))
self._add_event_interest(self._io_loop.READ)
def resume_writing(self):
"""
Alias for adding the send interest to the event handler.
"""
if _SHOULD_LOG_DEBUG_OUTPUT:
gen_log.debug('Resuming send events for stream(fd:{})'.format(
self.fd))
self._add_event_interest(self._io_loop.WRITE)
def _add_event_interest(self, event_interest):
"""Add io_state to poller."""
if not self._event_interest & event_interest:
self._event_interest = self._event_interest | event_interest
self._io_loop.update_handler(self.fd, self._event_interest)
def _drop_event_interest(self, event_interest):
"""Stop poller from watching an io_state."""
if self._event_interest & event_interest:
self._event_interest = self._event_interest & (~event_interest)
self._io_loop.update_handler(self.fd, self._event_interest)
class SocketIOHandler(IOHandler):
def __init__(self, sock, io_loop=None, recv_chunk_size=4096):
super(SocketIOHandler, self).__init__(io_loop)
# Socket init
self._socket = sock
# Set socket options
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._socket.setblocking(0)
# Initialize our handling of the FD events
self.handle = FileDescriptorHandle(self._socket.fileno(), self._io_loop)
self.handle.set_handler(self._handle_events)
# Flow control vars
self._connecting = False
self._closing = False
# Writing and reading management
self._write_queue = WriteQueue()
self._recv_chunk_size = recv_chunk_size
self._recv_buffer = bytearray(self._recv_chunk_size)
def on_done_writing(self, callback=None):
"""
Sets a callback for completed send events and then sets the send
interest on the event handler.
"""
if not self._closing:
assert callback is None or callable(callback)
self._write_cb = stack_context.wrap(callback)
def on_close(self, callback):
"""
Sets a callback to be called after this stream closes.
"""
if not self._closing:
assert callback is None or callable(callback)
self._close_cb = stack_context.wrap(callback)
def on_error(self, callback):
"""
Sets a callback to be called after this stream closes.
"""
if not self._closing:
assert callback is None or callable(callback)
self._error_cb = stack_context.wrap(callback)
def reading(self):
"""Returns True if we are currently receiving from the stream."""
return not self.closed() and self.handle.is_reading()
def writing(self):
"""Returns True if we are currently writing to the stream."""
return not self.closed() and self._write_queue.has_next()
def closed(self):
return self._closing or self._socket is None
def read(self, callback):
"""
Sets a callback for read events and then sets the read interest on
the event handler.
"""
self._assert_not_closed()
assert callback is None or callable(callback)
self._read_cb = stack_context.wrap(callback)
self.handle.resume_reading()
def write(self, msg, callback=None):
self._assert_not_closed()
if not isinstance(msg, basestring) and not isinstance(msg, bytearray):
raise TypeError("bytes/bytearray/unicode/str objects only")
# Append the data for writing - this should not copy the data
self._write_queue.append(msg)
# Enable writing on the FD
self.handle.resume_writing()
# Set our callback - writing None to the method below is okay
self.on_done_writing(callback)
def connect(self, address, callback=None):
self._connecting = True
try:
self._socket.connect(address)
except socket.error as e:
if (e.args[0] != errno.EINPROGRESS and e.args[0] not in _ERRNO_WOULDBLOCK):
gen_log.warning("Connect error on fd %d: %s", self.handle.fd, e)
self.close()
return
self._on_connect_cb = stack_context.wrap(callback)
self.handle.resume_writing()
def close(self):
if not self._closing:
if self._write_queue.has_next():
self.on_done_writing(self._close)
else:
self._close()
self._closing = True
def _close(self):
"""Close this stream."""
if self._socket is not None:
gen_log.debug('Closing stream(fd: {})'.format(self.handle.fd))
self.handle.remove_handler()
self._socket.close()
self._socket = None
if self._close_cb:
self._run_callback(self._close_cb)
def _assert_not_closed(self):
if self.closed():
raise StreamClosedError('Stream closing or closed.')
def _do_read(self, recv_buffer):
return self._socket.recv_into(recv_buffer, self._recv_chunk_size)
def _do_write(self, send_buffer):
return self._socket.send(send_buffer)
def _handle_events(self, fd, events):
#gen_log.debug('Handle event for stream(fd: {})'.format(self.handle.fd))
if self._socket is None:
gen_log.warning("Got events for closed stream %d", fd)
return
try:
if self._socket is not None and events & self._io_loop.READ:
self.handle_read()
if self._socket is not None and events & self._io_loop.WRITE:
if self._connecting:
self.handle_connect()
else:
self.handle_write()
if not self.closed() and events & self._io_loop.ERROR:
self.handle_error(
self._socket.getsockopt(
socket.SOL_SOCKET, socket.SO_ERROR))
except Exception:
self.close()
raise
def handle_error(self, error):
try:
if self._error_cb is not None:
callback = self._error_cb
self._error_cb = None
self._run_callback(callback, error)
if error not in _ERRNO_CONNRESET:
gen_log.warning("Error on stream(fd:%d) caught: %s",
self.handle.fd, errno.errorcode[error])
finally:
# On error, close the FD
self.close()
def handle_read(self):
try:
read = self._do_read(self._recv_buffer)
if read is not None:
if read > 0 and self._read_cb:
self._run_callback(self._read_cb, self._recv_buffer[:read])
elif read == 0:
self.close()
except (socket.error, IOError, OSError) as ex:
if ex.args[0] not in _ERRNO_WOULDBLOCK:
self.handle_error(ex.args[0])
def handle_write(self):
if self._write_queue.has_next():
try:
msg = None
while self._write_queue.has_next():
msg, offset = self._write_queue.next()
sent = self._do_write(msg[offset:])
self._write_queue.advance(sent)
except (socket.error, IOError, OSError) as ex:
if ex.args[0] in _ERRNO_WOULDBLOCK:
self._write_queue.appendleft(msg)
else:
self._write_queue.clear()
self.handle_error(ex.args[0])
else:
self.handle.disable_writing()
if self._write_cb:
callback = self._write_cb
self._write_cb = None
self._run_callback(callback)
def handle_connect(self):
if self._on_connect_cb is not None:
callback = self._on_connect_cb
self._on_connect_cb = None
self._run_callback(callback)
self._connecting = False
def _run_callback(self, callback, *args, **kwargs):
"""Wrap running callbacks in try/except to allow us to
close our socket."""
try:
# Use a NullContext to ensure that all StackContexts are run
# inside our blanket exception handler rather than outside.
with stack_context.NullContext():
callback(*args, **kwargs)
except Exception as ex:
gen_log.error("Uncaught exception: %s", ex)
# Close the socket on an uncaught exception from a user callback
# (It would eventually get closed when the socket object is
# gc'd, but we don't want to rely on gc happening before we
# run out of file descriptors)
self.close()
# Re-raise the exception so that IOLoop.handle_callback_exception
# can see it and log the error
raise
class SSLSocketIOHandler(SocketIOHandler):
"""A utility class to write to and read from a non-blocking SSL socket.
If the socket passed to the constructor is already connected,
it should be wrapped with::
ssl.wrap_socket(sock, do_handshake_on_connect=False, **kwargs)
before constructing the `SSLSocketIOHandler`. Unconnected sockets will be
wrapped when `SSLSocketIOHandler.connect` is finished.
"""
def __init__(self, *args, **kwargs):
"""The ``ssl_options`` keyword argument may either be a dictionary
of keywords arguments for `ssl.wrap_socket`, or an `ssl.SSLContext`
object.
"""
self._ssl_options = kwargs.pop('ssl_options', {})
super(SSLSocketIOHandler, self).__init__(*args, **kwargs)
self._ssl_accepting = True
self._handshake_reading = False
self._handshake_writing = False
self._ssl_on_connect_cb = None
self._server_hostname = None
# If the socket is already connected, attempt to start the handshake.
try:
self._socket.getpeername()
except socket.error:
pass
else:
# Indirectly start the handshake, which will run on the next
# IOLoop iteration and then the real IO event_interest will be set in
# _handle_events.
self.handle.resume_writing()
def reading(self):
return self._handshake_reading or super(SSLSocketIOHandler, self).reading()
def writing(self):
return self._handshake_writing or super(SSLSocketIOHandler, self).writing()
def _do_ssl_handshake(self):
# Based on code from test_ssl.py in the python stdlib
try:
self._handshake_reading = False
self._handshake_writing = False
self._socket.do_handshake()
except ssl.SSLError as err:
if err.args[0] == ssl.SSL_ERROR_WANT_READ:
self._handshake_reading = True
return
elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
self._handshake_writing = True
return
elif err.args[0] in (ssl.SSL_ERROR_EOF,
ssl.SSL_ERROR_ZERO_RETURN):
self.close()
return
elif err.args[0] == ssl.SSL_ERROR_SSL:
try:
peer = self._socket.getpeername()
except Exception:
peer = '(not connected)'
gen_log.warning("SSL Error on %d %s: %s",
self.handle.fd, peer, err)
self.close()
return
raise
except socket.error as err:
if err.args[0] in _ERRNO_CONNRESET:
self.close()
return
except AttributeError:
# On Linux, if the connection was reset before the call to
# wrap_socket, do_handshake will fail with an
# AttributeError.
self.close()
return
else:
self._ssl_accepting = False
if not self._verify_cert(self._socket.getpeercert()):
self.close()
return
if self._ssl_on_connect_cb is not None:
callback = self._ssl_on_connect_cb
self._ssl_on_connect_cb = None
self._run_callback(callback)
def _verify_cert(self, peercert):
"""Returns True if peercert is valid according to the configured
validation mode and hostname.
The ssl handshake already tested the certificate for a valid
CA signature; the only thing that remains is to check
the hostname.
"""
if isinstance(self._ssl_options, dict):
verify_mode = self._ssl_options.get('cert_reqs', ssl.CERT_NONE)
elif isinstance(self._ssl_options, ssl.SSLContext):
verify_mode = self._ssl_options.verify_mode
assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL)
if verify_mode == ssl.CERT_NONE or self._server_hostname is None:
return True
cert = self._socket.getpeercert()
if cert is None and verify_mode == ssl.CERT_REQUIRED:
gen_log.warning("No SSL certificate given")
return False
try:
ssl_match_hostname(peercert, self._server_hostname)
except SSLCertificateError:
gen_log.warning("Invalid SSL certificate", )
return False
else:
return True
def handle_read(self):
if self._ssl_accepting:
self._do_ssl_handshake()
else:
super(SSLSocketIOHandler, self).handle_read()
def handle_write(self):
if self._ssl_accepting:
self._do_ssl_handshake()
else:
super(SSLSocketIOHandler, self).handle_write()
def connect(self, address, callback=None, server_hostname=None):
# Save the user's callback and run it after the ssl handshake
# has completed.
self._ssl_on_connect_cb = stack_context.wrap(callback)
self._server_hostname = server_hostname
super(SSLSocketIOHandler, self).connect(address, callback=None)
def handle_connect(self):
# When the connection is complete, wrap the socket for SSL
# traffic. Note that we do this by overriding handle_connect
# instead of by passing a callback to super().connect because
# user callbacks are enqueued asynchronously on the IOLoop,
# but since _handle_events calls handle_connect immediately
# followed by handle_write we need this to be synchronous.
self._socket = ssl_wrap_socket(self._socket, self._ssl_options,
server_hostname=self._server_hostname,
do_handshake_on_connect=False)
super(SSLSocketIOHandler, self).handle_connect()
def _do_read(self, recv_buffer):
if self._ssl_accepting:
# If the handshake hasn't finished yet, there can't be anything
# to read (attempting to read may or may not raise an exception
# depending on the SSL version)
return -1
try:
bytes = self._socket.read(self._recv_chunk_size)
read = len(bytes)
recv_buffer[:read] = bytes
return read
except ssl.SSLError as e:
# SSLError is a subclass of socket.error, so this except
# block must come first.
if e.args[0] == ssl.SSL_ERROR_WANT_READ:
return -1
else:
raise
def _do_write(self, send_buffer):
return self._socket.send(send_buffer)
| zinic/pyrox | pyrox/tstream/iostream.py | iostream.py | py | 20,656 | python | en | code | 37 | github-code | 1 | [
{
"api_name": "tornado.platform.posix._set_nonblocking",
"line_number": 22,
"usage_type": "name"
},
{
"api_name": "errno.EWOULDBLOCK",
"line_number": 27,
"usage_type": "attribute"
},
{
"api_name": "errno.EAGAIN",
"line_number": 27,
"usage_type": "attribute"
},
{
"... |
42327230 | # important: process ids are global, i. e. are preserved (same pid for each instance) ==> <> os-managed pid
import itertools
import json
from datetime import timedelta, datetime
from typing import Sequence, Tuple, Dict
import os
import locale
import sys
import argparse
root, filename = os.path.split(__file__)
proj_root = os.path.realpath(os.path.join(root, "..", ".."))
locale.setlocale(locale.LC_ALL, "de_AT.UTF-8") # "" for auto, e. g. german: de_AT.UTF-8
sys.path.append(proj_root)
from instances.large.process_log import ProcessLog, FileMode
from instances.large.persistence_helper import persist_summary, save_summary_plot, persist_conflict_report, save_plot
def parse_args():
parser = argparse.ArgumentParser(description="Reads process traces from json files and analyzes them with respect "
"to possible sources of resource conflicts. A plot describing the"
" number of traces per PID and one showing the number of resource "
"accesses (read, write) as well as possible conflicts are saved. "
"The underlying data for the plots will be persisted as csv and JSON.")
parser.add_argument("pid", metavar="pid", type=int, help="ID of the process to analyze")
parser.add_argument("freqs", metavar="freqs", type=str, help="path frequency plot should be persisted to")
parser.add_argument("summary_csv", metavar="summary_csv", type=str,
help="path resource summary (csv) should be persisted to")
parser.add_argument("summary_plot", metavar="summary_plot", type=str,
help="path resource summary (plot) should be persisted to")
parser.add_argument("conflicts", metavar="conflicts", type=str, help="path conflict report should be persisted to")
parser.add_argument("traces", metavar="traces", nargs="+", type=str, help="process trace logs (JSON) to analyze")
return parser.parse_args()
def load_data(paths: Sequence[str]) -> Sequence[ProcessLog]:
return_value = []
for path in paths:
with open(path) as file:
data_lst = json.load(file)
return_value.extend(map(ProcessLog.deserialize, data_lst))
return return_value
# count of entries, unique pids, all pids (for histogram)
def get_pids(data: Sequence[ProcessLog]) -> (int, Sequence[int], Sequence[int]):
seen = set()
count = 0
pids = []
for obj in data:
count += 1
pids.append(obj.pid)
if obj.pid not in seen:
seen.add(obj.pid)
return count, seen, pids
def get_logs_by_id(logs: Sequence[ProcessLog], pid: int) -> Sequence[ProcessLog]:
return [log for log in logs if log.pid == pid]
def get_runtime(logs: Sequence[ProcessLog]) -> timedelta:
runtime = timedelta(0)
for log in logs:
runtime += log.end - log.start
return runtime
def get_overlaps(logs: Sequence[ProcessLog]) -> Tuple[Sequence[Tuple[ProcessLog, ProcessLog]], int]:
combinations = itertools.combinations(logs, 2)
overlaps = []
resource_accesses = 0
for x, y in combinations:
resource_accesses += len(x.resources) + len(y.resources)
if dates_overlap(x.start, x.end, y.start, y.end):
overlaps.append((x, y))
return overlaps, resource_accesses
def dates_overlap(start1: datetime, end1: datetime, start2: datetime, end2: datetime):
return start1 <= end2 and end1 >= start2
def get_conflicts(overlaps: Sequence[Tuple[ProcessLog, ProcessLog]]) -> \
Sequence[Tuple[ProcessLog, ProcessLog, Sequence[str]]]:
conflicting_tuples = []
for x, y, in overlaps:
intersection = list(set(x.resources).intersection(y.resources))
# intersection not empty and mode conflict
if intersection and x.mode == FileMode.WRITE and y.mode == FileMode.WRITE:
conflicting_tuples.append((x, y, intersection))
return conflicting_tuples
# returns dict with resource name as key and (read-accesses, write-accesses)-tuple as value
def get_concurrent_accesses_per_resource(concurrent_execs: Sequence[Tuple[ProcessLog, ProcessLog]]) -> \
Dict[str, Tuple[int, int]]:
# unique list of executions (equals flattened list of concurrent ProcessLogs without duplicates)
execs = set([item for t in concurrent_execs for item in t])
ret_dict = {}
for execution in execs:
for res in execution.resources:
if res not in ret_dict:
ret_dict[res] = (0, 0)
current_r, current_w = ret_dict[res]
if execution.mode == FileMode.READ:
ret_dict[res] = (current_r + 1, current_w)
elif execution.mode == FileMode.WRITE:
ret_dict[res] = (current_r, current_w + 1)
return ret_dict
# returns dict with resource name as key and number of conflicts as value
def get_conflicts_per_resource(conflicts: Sequence[Tuple[ProcessLog, ProcessLog, Sequence[str]]]) -> Dict[str, int]:
ret_dict = {}
for x, y, resources in conflicts:
for res in resources:
if res not in ret_dict:
ret_dict[res] = 0
ret_dict[res] += 1
return ret_dict
def get_resource_summary(accesses: Dict[str, Tuple[int, int]], conflicts: Dict[str, int]) -> \
Dict[str, Tuple[int, int, int]]:
# dict comprehension: take values of access and add a third component to the tuple by adding (conflicts[k], )
# (= access int in conflicts dict with key k) -> if key does not exist, take 0 (= no conflicts for this resource)
return {k: (v + (conflicts.get(k, 0),)) for k, v in accesses.items()}
"""
@begin inst_l.main
@param pid @desc ID of process to analyze
@param freqs @desc persistence path for frequency plot
@param summary_csv @desc persistence path for csv summary
@param summary_plot @desc persistence path for plot summary
@param conflicts @desc persistence path for conflict report
@in traces @desc paths of process trace logs to analyze
@out frequency_plot @uri file:{freqs}
@out conflict_report @uri file:{conflicts}
@out res_summary_csv @uri file:{summary_csv}
@out res_summary_plot @uri file:{summary_plot}
"""
def main():
args = parse_args()
"""
@begin load_data @desc read process trace logs
@in traces
@out data
"""
print("Loading data...")
data = load_data(args.traces)
print("Done.\n")
"""
@end load_data
"""
"""
@begin get_pids @desc determine PIDs stored\nin trace logs
@in data
@out count
@out distinct_pids
@out all_pids
"""
print("Initial analysis...")
count, distinct_pids, all_pids = get_pids(data)
"""
@end get_pids
"""
"""
@begin provide_data_info @desc print count and names of\nprocesses; save frequency plot
@in count
@in distinct_pids
@in all_pids
@in freqs
@out frequency_plot @uri file:{freqs}
"""
print("Done. Read {0:n} process log entries from {1} files.\n".format(count, len(args.traces)))
print("The following {0} processes were captured in the log:".format(len(distinct_pids)))
print(sorted(distinct_pids))
save_plot(all_pids, args.freqs)
print("(See plot {0} for frequency distribution.)".format(os.path.basename(args.freqs)))
"""
@end provide_data_info
"""
print("\u2500" * 75) # unicode character "box drawings light horizontal"
print("Start gathering information about process with ID {0}...".format(args.pid))
if args.pid not in distinct_pids:
print("\nError! PID must be part of the list above (process must be captured in input traces). Abort.")
exit(1)
"""
@begin get_logs @desc retrieve trace logs\nof specified process
@in data
@in pid
@out pid_logs
"""
pid_logs = get_logs_by_id(data, args.pid) # there are len(pid_logs) instances recorded of that process
"""
@end get_logs
"""
"""
@begin get_process_runtime @desc compute total and average runtime
@in pid_logs
@out total_runtime
@out avg_runtime
"""
total_runtime = get_runtime(pid_logs)
avg_runtime = total_runtime // len(pid_logs)
"""
@end get_process_runtime
"""
"""
@begin get_overlaps @desc determine overlapping\nPID trace logs
@in pid_logs
@out concurrent_executions
@out overall_resource_accesses
"""
concurrent_executions, overall_resource_accesses = get_overlaps(pid_logs)
"""
@end get_overlaps
"""
"""
@begin get_conflicts @desc determine write-write conflicts
@in concurrent_executions
@out res_conflicts
"""
conflicts = get_conflicts(concurrent_executions)
"""
@end get_conflicts
"""
"""
@begin get_resource_info @desc determine usage and\nresource conflict infos
@in concurrent_executions
@in conflicts
@out concurrent_accesses_per_resource
@out conflicts_per_resource
"""
concurrent_accesses_per_resource = get_concurrent_accesses_per_resource(concurrent_executions)
conflicts_per_resource = get_conflicts_per_resource(conflicts)
"""
@end get_resource_info
"""
"""
@begin get_resource_summary @desc get dict representation\nof resource summary
@in concurrent_accesses_per_resource
@in conflicts_per_resource
@out resource_summary
"""
resource_summary = get_resource_summary(concurrent_accesses_per_resource, conflicts_per_resource)
print("Done.\n")
"""
@end get_resource_summary
"""
print("Persisting plot and summaries...")
"""
@begin persist_res_summary @desc save resource summary\nas CSV file and plot
@in resource_summary
@in summary_csv
@in summary_plot
@in pid
@out res_summary_csv @uri file:{summary_csv}
@out res_summary_plot @uri file:{summary_plot}
"""
persist_summary(resource_summary, args.summary_csv.replace(".csv", "_{0}.csv".format(args.pid)))
save_summary_plot(resource_summary, args.summary_plot.replace(".jpg", "_{0}.jpg".format(args.pid)), args.pid)
"""
@end persist_resource_summary
"""
"""
@begin persist_conflict_report @desc save conflict report\nas JSON file
@in res_conflicts
@in total_runtime
@in avg_runtime
@in pid
@in conflicts
@out conflict_report @uri file:{conflicts}
"""
persist_conflict_report(conflicts, total_runtime, avg_runtime, args.pid,
args.conflicts.replace(".json", "_{0}.json".format(args.pid)))
print("Done.")
"""
@end persist_conflict_report
"""
"""
@end inst_l.main
"""
if __name__ == "__main__":
main()
| raffaelfoidl/ProvCaptPyEnvs | instances/large/inst_l.py | inst_l.py | py | 10,789 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "os.path.split",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "os.path.realpath",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_numbe... |
19046607125 | from iqoptionapi.stable_api import IQ_Option
import iqoptionapi.country_id as Pais
import time, logging, json, configparser
from datetime import datetime, date, timedelta
from dateutil import tz
import sys
#CODIGO PARA DESATIVAR DEBUG OU logging.ERROR
#logging.disable(level=(logging.DEBUG))
# Credenciais
API = IQ_Option('seu_email', 'password')
# Logar
def Login():
API.connect()
while True:
if API.check_connect() == False:
print('Erro ao se conectar')
API.connect()
else:
print('Conectado com sucesso')
break
time.sleep(1)
# carrega sua banca na api
def getBalance():
# Define a conta de utilização
conta = 'PRACTICE'#input('\nDigite com qual conta quer entrar "REAL" ou "PRACTICE": ')
API.change_balance(conta) # PRACTICE / REAL
return API.get_balance()
#CONVERT TIMESTAMP PARA HORA HUMANA
def timestamp_converter(x): # Função para converter timestamp
hora = datetime.strptime(datetime.utcfromtimestamp(x).strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')
hora = hora.replace(tzinfo=tz.gettz('GMT'))
return str(hora)[:-6]
#PEGA O PERFIL
def perfil():
return json.loads(json.dumps(API.get_profile_ansyc()))
#PEGA A BANCA
def banca():
return json.loads(json.dumps(getBalance()))
#PEGA TOP 10 TRADERS DO MUNDO
def topTrades():
pais='Worldwide'#"BR"
da_posicao=1
para_posicao=30
traders_perto=0
return json.loads(json.dumps(API.get_leader_board(pais, da_posicao, para_posicao, traders_perto)))
#PEGA PARIDADES ABERTAS
def payout(par, tipo, timeframe = 1):
if tipo == 'turbo':
a = API.get_all_profit()
return int(100 * a[par]['turbo'])
elif tipo == 'digital':
API.subscribe_strike_list(par, timeframe)
while True:
d = API.get_digital_current_profit(par, timeframe)
if d != False:
d = int(d)
break
time.sleep(1)
API.unsubscribe_strike_list(par, timeframe)
return d
def getCandles(par):
API.start_candles_stream(par, 60, 1)
time.sleep(1)
vela = API.get_realtime_candles(par, 60)
while True:
for velas in vela:
print(vela[velas]['close'])
time.sleep(1)
API.stop_candles_stream(par, 60)
def configuracao():
arquivo = configparser.RawConfigParser()
arquivo.read('config.txt')
return { 'paridade': arquivo.get('GERAL', 'paridade'), 'valor_entrada': arquivo.get('GERAL', 'entrada'), 'timeframe': arquivo.get('GERAL', 'timeframe')}
def sinais():
file = open('sinais.txt', encoding='UTF-8')
lista = file.read()
file.close
lista = lista.split('\n')
for index,a in enumerate(lista):
if a == '':
del lista[index]
return lista
Login()
print('\n - Inicializando o bot - \n')
# loop infinito para pegar acompanhar velas
# print('\n - Acompanhar velas - \n')
# par = 'EURUSD'
# getCandles(par)
# print meu perfil
data = perfil()
print('\n - Meu perfil - \n')
print(' Apelido: ',data['nickname'])
print(' Email: ',data['email'])
print(' Nome : ',data['name'])
print(' Banca : ', banca())
print(' Criado : ',timestamp_converter(data['created']))
print('\n - Pegando Top Traders - \n')
traders = topTrades()
for colocacao in traders['result']['positional']:
nome_ranking = traders['result']['positional'][colocacao]['user_name']
segunda_busca = API.get_user_profile_client(traders['result']['positional'][colocacao]['user_id'])
print(' Nome:',nome_ranking)
print(' User ID:',traders['result']['positional'][colocacao]['user_id'])
print(' Se registrou em:',timestamp_converter(segunda_busca['registration_time']))
print(' Pais: '+traders['result']['positional'][colocacao]['flag'])
print(' Faturamento esta semana:',round(traders['result']['positional'][colocacao]['score'], 2))
print('\n')
print(' - Trader(s) Online - \n')
for index in traders['result']['positional']:
# Pega o user_id do top 10 traders
id = traders['result']['positional'][index]['user_id']
# Quarda o perfil de cada trader
perfil_trader = API.get_user_profile_client(id)
# Verifica quem está online
if perfil_trader['status'] == 'online':
trade = API.get_users_availability(id)
try:
tipo = trade['statuses'][0]['selected_instrument_type']
par = API.get_name_by_activeId(trade['statuses'][0]['selected_asset_id']).replace('/', '')
print('\n [',index,'] ',perfil_trader['user_name'])
print(' Opção: ',tipo)
print(' Pariedade: ',par)
except:
pass
# print('\n - Pegando pariedades abertas - \n')
# par = API.get_all_open_time()
# for paridade in par['turbo']:
# if par['turbo'][paridade]['open'] == True:
# print('[ TURBO ]: '+paridade+' | Payout: '+str(payout(paridade, 'turbo')))
# print('\n')
# for paridade in par['digital']:
# if par['digital'][paridade]['open'] == True:
# print('[ DIGITAL ]: '+paridade+' | Payout: '+str( payout(paridade, 'digital') ))
# #PEGA OS SINAIS
# print('\n')
# print(json.dumps(sinais(), indent=1))
# lista_sinais = sinais()
# print('\n Quantidade de sinais: ',len(lista_sinais))
# for index, sinal in enumerate(lista_sinais):
# dados = sinal.split(';')
# while index <= len(lista_sinais):
# HORA_ATUAL = time.strftime('%Y-%m-%d %H:%M', time.localtime())
# if HORA_ATUAL == dados[0]:
# print('\n - Abrir ordem opções digitais - \n')
# pareMoeda = dados[2]
# entradas = 100.00
# direcoes = dados[3]#call pra cima put pra baixo
# timesframe = 1#1minuto;5minutos;15minutos
# status,id = API.buy_digital_spot(pareMoeda, entradas, direcoes, timesframe)
# if status:
# print(' Ordem aberta com sucesso')
# break
# else:
# print(' Não executou a ordem!')
# break
#PEGA AS CONFIGURAÇÕES
# print('\n\n')
# conf = configuracao()
# print(conf['paridade'])
print('\n - Seguir traders - \n')
# # name:
# # "live-deal-binary-option-placed"
# # "live-deal-digital-option"
while_run_time=10
name="live-deal-digital-option"
active="EURAUD"
_type="PT1M" #"PT1M"/"PT5M"/"PT15M"
buffersize=10
print("_____________subscribe_live_deal_______________")
API.subscribe_live_deal(name,active,_type,buffersize)
start_t=time.time()
while True:
trades = API.get_live_deal(name,active,_type)
print("__For_digital_option__ data size:"+str(len(trades)))
print(trades)
print("\n\n")
time.sleep(1)
# if time.time()-start_t>while_run_time:
# break
if len(trades) > 0:
print(json.dumps(trades[0], indent=1))
print("_____________unscribe_live_deal_______________")
API.unscribe_live_deal(name,active,_type)
# Abrir ordem iq option opções digitais
# print('\n - Abrir ordem opções digitais - \n')
# pareMoeda = 'EURCAD'
# entradas = 100.00
# direcoes = 'call'#call pra cima put pra baixo
# timesframe = 1#1minuto;5minutos;15minutos
# status,id = API.buy_digital_spot(pareMoeda, entradas, direcoes, timesframe)
# if status:
# print(' Ordem aberta com sucesso')
# print(' Aguarde a ordem ser concluida')
# else:
# print(' Não executou a ordem!')
# sys.exit()
# if isinstance(id, int):
#while True:
# resultado,lucro = API.check_win_digital_v2(id)
# if resultado:
# if lucro > 0:
# print(' RESULTADO: WIN / LUCRO: '+str(round(lucro,2)))
# else:
# print(' RESULTADO: LOSS / PERDA: '+str(entradas))
# break
#força a saida
#sys.exit()
# Abrir ordem iq option opções binarias
# print('\n - Abrir ordem opções binarias - \n')
# parMoeda = 'AUDCAD-OTC'
# entrada = 100.00
# direcao = 'call'#call pra cima put pra baixo
# timeframe = 1
# status,id = API.buy(entrada, parMoeda, direcao, timeframe)
# if status:
# resultado,lucro = API.check_win_v3(id)
# print('RESULTADO: '+resultado+' / LUCRO: '+str(round(lucro, 2)))
# #Exemplo para pegar resultado
# # print(API.check_win_v3(id))
# # print('\n')
# # print(API.check_win_v4(id))
print('\n - Fim das operações - \n')
| Cleoir-Dev/iqoptionapi | tests/bot_CopyTrade.py | bot_CopyTrade.py | py | 8,285 | python | pt | code | 0 | github-code | 1 | [
{
"api_name": "iqoptionapi.stable_api.IQ_Option",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "time.sleep",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "datetime.datetime.strptime",
"line_number": 37,
"usage_type": "call"
},
{
"api_name":... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.