index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
19,802
|
Mr-big-c/github
|
refs/heads/master
|
/练习代码/Flask/flask_web/__init__.py
|
# -*- coding: utf-8 -*-
# @File : __init__.py
# @Author: 一稚杨
# @Date : 2018/6/8/008
# @Desc : 创建一个方法创建app,并且执行响应的初始化
from flask import Flask
from flask_web.models.man import db
def create_app():
app = Flask(__name__)
# 导入普通配置文件
app.config.from_object("settings.setting")
# 导入机密数据配置文件
app.config.from_object("settings.secret")
# 调用蓝图注册函数,将蓝图与app相关联
register_blueprint(app)
# 关联app与db
db.init_app(app)
db.create_all(app=app)
return app
def register_blueprint(app):
from flask_web.blueprint1.views import blueprint
from flask_web.blueprint2.views.views import blueprint2
# 注册蓝图对象, 从而就将app与蓝图关联起来了
app.register_blueprint(blueprint)
app.register_blueprint(blueprint2)
|
{"/Blog Relevant/files_system/basics/views.py": ["/Blog Relevant/files_system/basics/file_op.py"], "/Blog Relevant/blog7-17/myapp/admin.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/Blog Relevant/blog8-31/myapp/views.py": ["/Blog Relevant/blog8-31/myapp/forms.py"], "/Blog Relevant/blog7-21/myapp/views.py": ["/Blog Relevant/blog7-21/myapp/models.py"], "/Blog Relevant/blog7-17/myapp/views.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/views1.py": ["/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/__init__.py"]}
|
19,803
|
Mr-big-c/github
|
refs/heads/master
|
/Flask/Flask_win/m68/model.py
|
# -*- coding: utf-8 -*-
# @File : model.py
# @Author: 一稚杨
# @Date : 2018/6/8/008
# @Desc : 使用模型类
from flask import Flask
from m68.models.books import db
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+cymysql://一稚杨:muyuyu123@localhost:3306/flask'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# 关联app与db对象
db.init_app(app)
db.create_all(app=app)
@app.route("/index")
def index():
return "model"
if __name__ == "__main__":
app.run(debug=True)
|
{"/Blog Relevant/files_system/basics/views.py": ["/Blog Relevant/files_system/basics/file_op.py"], "/Blog Relevant/blog7-17/myapp/admin.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/Blog Relevant/blog8-31/myapp/views.py": ["/Blog Relevant/blog8-31/myapp/forms.py"], "/Blog Relevant/blog7-21/myapp/views.py": ["/Blog Relevant/blog7-21/myapp/models.py"], "/Blog Relevant/blog7-17/myapp/views.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/views1.py": ["/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/__init__.py"]}
|
19,804
|
Mr-big-c/github
|
refs/heads/master
|
/Blog Relevant/blog8-19/Run/admin.py
|
from django.contrib import admin
from .models import Run
# Register your models here.
class RunAdmin(admin.ModelAdmin):
list_display = ('pk', 'time')
admin.site.register(Run, RunAdmin)
|
{"/Blog Relevant/files_system/basics/views.py": ["/Blog Relevant/files_system/basics/file_op.py"], "/Blog Relevant/blog7-17/myapp/admin.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/Blog Relevant/blog8-31/myapp/views.py": ["/Blog Relevant/blog8-31/myapp/forms.py"], "/Blog Relevant/blog7-21/myapp/views.py": ["/Blog Relevant/blog7-21/myapp/models.py"], "/Blog Relevant/blog7-17/myapp/views.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/views1.py": ["/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/__init__.py"]}
|
19,805
|
Mr-big-c/github
|
refs/heads/master
|
/练习代码/spider5.15/妹子图.py
|
import urllib.request
import re
import os
def spider(url):
# 创建请求头,模拟浏览器请求
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:59.0) Gecko/20100101 Firefox/59.0"
}
# 利用请求头来创建请求体
req = urllib.request.Request(url, headers=headers)
# 发起请求
response = urllib.request.urlopen(req)
# 获得放回的数据并指定解码格式
data = response.read().decode('UTF-8')
return data
url = r"http://www.tgirl.cc/gctt/kimoe"
result = spider(url)
# 正则字符串
re_str1 = r'<span class="read-more"><a href="([\s\S]*?)">阅读全文»</a></span>'
re_str2 = r'<div id="post_content">([\s\S]*?)<div class="xydown_down_link">'
re_str3 = r'<img src="([\s\S]*?)" alt="'
img_url_list1 = re.findall(re_str1, result)
num = 1
# 图片存储的路径
path = r"C:\Users\Administrator\Desktop\img"
# 打开对应的总览的链接
for img_url_l in img_url_list1:
# 打开总览后返回的数据
download_html = spider(img_url_l)
download_url = re.findall(re_str2, download_html)
img_url_list2 = re.findall(re_str3, download_url[0])
# print(download_url)
# 下载图片到本地
for img in img_url_list2:
filename = os.path.join(path, str(num) + ".jpg")
urllib.request.urlretrieve(img, filename=filename)
print(img)
num += 1
|
{"/Blog Relevant/files_system/basics/views.py": ["/Blog Relevant/files_system/basics/file_op.py"], "/Blog Relevant/blog7-17/myapp/admin.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/Blog Relevant/blog8-31/myapp/views.py": ["/Blog Relevant/blog8-31/myapp/forms.py"], "/Blog Relevant/blog7-21/myapp/views.py": ["/Blog Relevant/blog7-21/myapp/models.py"], "/Blog Relevant/blog7-17/myapp/views.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/views1.py": ["/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/__init__.py"]}
|
19,806
|
Mr-big-c/github
|
refs/heads/master
|
/代码中转站/blog/myapp/admin.py
|
from django.contrib import admin
from myapp.models import books
# Register your models here.
admin.site.register(books)
|
{"/Blog Relevant/files_system/basics/views.py": ["/Blog Relevant/files_system/basics/file_op.py"], "/Blog Relevant/blog7-17/myapp/admin.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/Blog Relevant/blog8-31/myapp/views.py": ["/Blog Relevant/blog8-31/myapp/forms.py"], "/Blog Relevant/blog7-21/myapp/views.py": ["/Blog Relevant/blog7-21/myapp/models.py"], "/Blog Relevant/blog7-17/myapp/views.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/views1.py": ["/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/__init__.py"]}
|
19,807
|
Mr-big-c/github
|
refs/heads/master
|
/tkinter/listbox.py
|
'''
listbox 控件
'''
import tkinter
win = tkinter.Tk()
win.title("hwy")
win.geometry("400x400")
# 绑定参数
lbv = tkinter.StringVar()
listbox = tkinter.Listbox(win, selectmode=tkinter.MULTIPLE, listvariable=lbv,)
str = ["python", "java", "php", "C++", "C#"]
# 增加参数
for text in str:
listbox.insert(tkinter.END, text)
listbox.insert(tkinter.ACTIVE, "HTML")
# 删除参数, 有两个参数,第一个参数指定开始的索引,第二个参数指定
# 结束的索引,如果只有一个参数则只删除一个
# listbox.delete(1)
# # 选中,参数同delete
listbox.select_set(1, 3)
# # 清除选中,参数同delete
# listbox.select_clear(2)
# # 获取元素的个数
# print(listbox.size())
# # 获得指定下标的值
# print(listbox.get(1, 3))
# 返回当前选中项的标号
# print(listbox.curselection())
# 判断一个元素是否被选中
# print(listbox.select_includes(1))
# 修改元素的内容
# lbv.set(('1', '2', '3'))
# 绑定事件
# def showinfo(event):
# print(listbox.get(listbox.curselection()))
# listbox.bind('<Double-Button-1>', showinfo)
# print(lbv.get())
listbox.pack()
win.mainloop()
|
{"/Blog Relevant/files_system/basics/views.py": ["/Blog Relevant/files_system/basics/file_op.py"], "/Blog Relevant/blog7-17/myapp/admin.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/Blog Relevant/blog8-31/myapp/views.py": ["/Blog Relevant/blog8-31/myapp/forms.py"], "/Blog Relevant/blog7-21/myapp/views.py": ["/Blog Relevant/blog7-21/myapp/models.py"], "/Blog Relevant/blog7-17/myapp/views.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/views1.py": ["/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/__init__.py"]}
|
19,808
|
Mr-big-c/github
|
refs/heads/master
|
/练习代码/spider5.15/5.15.py
|
import urllib.request
# 通过urlopen这个方法向指定的url发送请求,并放回服务器响应的数据
response = urllib.request.urlopen("https://www.douban.com/")
# 通过read读取返回的全部数据,并通过decode指定编码方式,赋值给一个字符变量
# data = response.read().decode("utf-8")
# 每次读取一行内容,可以通过循环来读取数据
data1 = response.readline().decode("utf-8")
# 读取全部数据,但是赋值给一个列表变量,每一行为一个元素
data2 = response.readlines()
print(data2[100].decode("utf-8"))
# 放回当前环境的相关信息
print(response.info())
# 返回状态码 200 成功访问, 304 存在缓存
print(response.getcode())
# 返回当前请求的网址
print(response.geturl())
url = "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&tn=\
monline_3_dg&wd=%E7%99%BE%E5%BA%A6&oq=charles%25E4%25B8%258B%2\
5E8%25BD%25BD&rsv_pq=e61190b5000004db&rsv_t=a6c11nbP3rDI9y0Mz%\
2FODHo%2FT6%2F9jLULDmr6tH5cVepSLYjyv0V0ewhGEzBUwlZoNRhfw&rqlan\
g=cn&rsv_enter=1&rsv_sug3=6&rsv_sug1=6&rsv_sug7=100&rsv_sug2=0\
&inputT=896&rsv_sug4=13910"
# 转义网址中的中文编码
newurl = urllib.request.unquote(url)
# print(newurl)
url1 = "黄文杨"
# 与unquote过程相反
newurl = urllib.request.quote(url1)
print(newurl)
|
{"/Blog Relevant/files_system/basics/views.py": ["/Blog Relevant/files_system/basics/file_op.py"], "/Blog Relevant/blog7-17/myapp/admin.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/Blog Relevant/blog8-31/myapp/views.py": ["/Blog Relevant/blog8-31/myapp/forms.py"], "/Blog Relevant/blog7-21/myapp/views.py": ["/Blog Relevant/blog7-21/myapp/models.py"], "/Blog Relevant/blog7-17/myapp/views.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/views1.py": ["/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/__init__.py"]}
|
19,809
|
Mr-big-c/github
|
refs/heads/master
|
/练习代码/Flask/6.2/2.py
|
# -*- coding: utf-8 -*-
# @File : 2.py
# @Author: 一稚杨
# @Date : 2018/6/2/002
# @Desc : 利用url传递参数
from flask import Flask
# 创建一个flask应用
app = Flask(__name__)
# 指定路由并对应一个视图函数,通过<data>来传递数据
@app.route("/index/<username>")
def index_page(username):
# 要提取出url中的参数,只需要用对应的参数名即可,但是需要在对应的视图函数中传入该变量名
username = username
return "hell ipad, i am windows %s" % username
# 启动应用
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=80)
|
{"/Blog Relevant/files_system/basics/views.py": ["/Blog Relevant/files_system/basics/file_op.py"], "/Blog Relevant/blog7-17/myapp/admin.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/Blog Relevant/blog8-31/myapp/views.py": ["/Blog Relevant/blog8-31/myapp/forms.py"], "/Blog Relevant/blog7-21/myapp/views.py": ["/Blog Relevant/blog7-21/myapp/models.py"], "/Blog Relevant/blog7-17/myapp/views.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/views1.py": ["/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/__init__.py"]}
|
19,810
|
Mr-big-c/github
|
refs/heads/master
|
/Blog Relevant/blog8-3/Recent_Read/views.py
|
from django.shortcuts import render
from .models import Recent_Read
# Create your views here.
# 用户信息
def user_info(request):
user = request.user
if not user.is_anonymous:
articles = Recent_Read.objects.filter(user=user, is_delete=False)[0:40]
context = {}
context['articles'] = articles
return render(request, 'user_info.html', context)
else:
return render(request, 'error.html')
|
{"/Blog Relevant/files_system/basics/views.py": ["/Blog Relevant/files_system/basics/file_op.py"], "/Blog Relevant/blog7-17/myapp/admin.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/Blog Relevant/blog8-31/myapp/views.py": ["/Blog Relevant/blog8-31/myapp/forms.py"], "/Blog Relevant/blog7-21/myapp/views.py": ["/Blog Relevant/blog7-21/myapp/models.py"], "/Blog Relevant/blog7-17/myapp/views.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/views1.py": ["/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/__init__.py"]}
|
19,811
|
Mr-big-c/github
|
refs/heads/master
|
/Blog Relevant/blog8-22/Comment/Form/comment_text_form.py
|
# -*- coding: utf-8 -*-
# @File : comment_text_form.py
# @Author: 一稚杨
# @Date : 2018/8/17/017
# @Desc :
from django import forms
from ckeditor.widgets import CKEditorWidget
class CommentText(forms.Form):
comment_text = forms.CharField(label='', widget=CKEditorWidget(config_name='comment_ckeditor'))
|
{"/Blog Relevant/files_system/basics/views.py": ["/Blog Relevant/files_system/basics/file_op.py"], "/Blog Relevant/blog7-17/myapp/admin.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/Blog Relevant/blog8-31/myapp/views.py": ["/Blog Relevant/blog8-31/myapp/forms.py"], "/Blog Relevant/blog7-21/myapp/views.py": ["/Blog Relevant/blog7-21/myapp/models.py"], "/Blog Relevant/blog7-17/myapp/views.py": ["/Blog Relevant/blog7-17/myapp/models.py"], "/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/views1.py": ["/\u7ec3\u4e60\u4ee3\u7801/Flask/flask_web/blueprint1/views/__init__.py"]}
|
19,812
|
mortonjt/microLearner
|
refs/heads/master
|
/microLearner/cmd.py
|
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2014--, microLearner development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
from __future__ import print_function
from microLearner.util.misc import AliasedGroup
from sklearn import preprocessing
import click
import pandas as pd
import numpy as np
CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())
@click.group(cls=AliasedGroup, context_settings=CONTEXT_SETTINGS)
@click.option('-v', '--verbose', count=True)
@click.version_option() # add --version option
@click.pass_context
def microLearner(ctx, verbose):
pass
@microLearner.command()
@click.argument('method', nargs=1, default='StandardScaler',
required=True,
# specify legal choices for the methods; anything not
# listed here will be not allowed.
type=click.Choice(['StandardScaler',
'MinMaxScaler']))
@click.option('-i', '--input_table', type=click.File('r'),
# required=True,
help='Input feature table.')
@click.option('-o', '--output_table', type=click.File('w'),
# required=True,
help='Output feature table.')
@click.option('--feature_range', nargs=2, type=float)
@click.pass_context
def preprocess(ctx, method, input_table, output_table, **kwargs):
if ctx.parent.params['verbose'] > 0:
click.echo("Running...")
click.echo(kwargs)
if True:
scaler = getattr(preprocessing, method)(**kwargs)
i = pd.read_table(input_table)
print(i)
o = pd.DataFrame(scaler.fit_transform(np.array(i)), columns=i.columns)
print(o)
o.to_csv(output_table, sep='\t')
# output_table.write(out)
else:
print(ctx.parent.params)
pass
|
{"/microLearner/cmd.py": ["/microLearner/util/misc.py"], "/microLearner/tests/test_instances.py": ["/microLearner/instances.py"]}
|
19,813
|
mortonjt/microLearner
|
refs/heads/master
|
/microLearner/instances.py
|
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2014--, microLearner development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
from __future__ import print_function
from pandas import DataFrame
class Instances(DataFrame):
'''
'''
def __init__(self, features, outcome):
self.features = features
self.outcome = outcome
|
{"/microLearner/cmd.py": ["/microLearner/util/misc.py"], "/microLearner/tests/test_instances.py": ["/microLearner/instances.py"]}
|
19,814
|
mortonjt/microLearner
|
refs/heads/master
|
/setup.py
|
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2014--, microLearner development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
# The PACKAGE is the top-level folder containing the __init__.py module
# that should be in the same directory as your setup.py file
PACKAGE = "microLearner"
# The NAME is what people will refer to your software as,
# the name under which your software is listed in PyPI and
# under which users will install it (for example, pip install NAME)
NAME = "microLearner"
DESCRIPTION = "Python package for ncRNA annotation"
AUTHOR = "microLearner development team"
AUTHOR_EMAIL = "zhenjiang.xu@gmail.com"
URL = "https://github.com/RNAer/microLearner"
VERSION = __import__(PACKAGE).__version__
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# Get the long description from the relevant file
with open('README.md') as f:
long_description = f.read()
setup(
name=NAME,
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# http://packaging.python.org/en/latest/tutorial.html#version
version=VERSION,
# What does your project relate to?
keywords=['Microbiome', 'Machine Learning', 'Bioinformatics'],
description=DESCRIPTION,
long_description=long_description,
# The project's main homepage.
url=URL,
# Author details
author=AUTHOR,
author_email=AUTHOR_EMAIL,
# Choose your license
license='BSD',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 2 - Pre-Alpha',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Intended Audience :: Bioinformatician',
'Topic :: Software Development :: Libraries',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Bio-Informatics',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: BSD License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/technical.html#install-requires-vs-requirements-files
install_requires=['numpy >= 1.7',
'scipy >= 0.13.0',
'matplotlib >= 1.1.0',
'scikit-learn',
'click',
# 'biom',
'pandas',
'future'],
extras_require={'test': ["nose >= 0.10.1", "pep8", "flake8"],
'doc': ["Sphinx >= 1.2.2", "sphinx-bootstrap-theme"]},
# Include additional files into the package
include_package_data=True,
# If there are data files included in your packages that need to be
# installed, specify them here. If using Python 2.6 or less, then these
# have to be included in MANIFEST.in as well.
package_data={
'microLearner': ['data/*'],
},
# To provide executable scripts, use entry points in preference to the
# "scripts" keyword. Entry points provide cross-platform support and allow
# pip to create the appropriate form of executable for the target platform.
entry_points={
'console_scripts': [
'microLearner=microLearner.cmd:microLearner',
],
},
test_suite='nose.collector'
)
|
{"/microLearner/cmd.py": ["/microLearner/util/misc.py"], "/microLearner/tests/test_instances.py": ["/microLearner/instances.py"]}
|
19,815
|
mortonjt/microLearner
|
refs/heads/master
|
/microLearner/tests/test_instances.py
|
#!/usr/bin/env python
from microLearner.instances import Instances
from unittest import TestCase, main
class InstancesTests(TestCase):
def setUp(self):
self.a1 = Instances('a', 'b')
if __name__ == "__main__":
main()
|
{"/microLearner/cmd.py": ["/microLearner/util/misc.py"], "/microLearner/tests/test_instances.py": ["/microLearner/instances.py"]}
|
19,816
|
mortonjt/microLearner
|
refs/heads/master
|
/microLearner/util/misc.py
|
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2014--, microLearner development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
import click
class AliasedGroup(click.Group):
''' Alias for commands.
This implements a subclass of click.Group that accepts a prefix
for a command. If there were a (sub)command called "push", it would
accept "pus" as an alias (so long as it was unique).
'''
def get_command(self, ctx, cmd_name):
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
matches = [x for x in self.list_commands(ctx)
if x.startswith(cmd_name)]
if not matches:
return None
elif len(matches) == 1:
return click.Group.get_command(self, ctx, matches[0])
ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))
class MultiParamType(click.ParamType):
def __init__(self, name=None, func=None):
if name is not None:
self.name = ' '.join('Multiple', func.__name__)
else:
self.name = name
self.func = func
def convert(self, value, param, ctx):
try:
values = [i for i in value.split(',') if i]
if self.func is None:
return values
else:
return [self.func(i) for i in values]
except ValueError:
self.fail('%s is not a valid' % value, param, ctx)
multi_int = MultiParamType(func=int)
|
{"/microLearner/cmd.py": ["/microLearner/util/misc.py"], "/microLearner/tests/test_instances.py": ["/microLearner/instances.py"]}
|
19,817
|
mortonjt/microLearner
|
refs/heads/master
|
/microLearner/__init__.py
|
#!/usr/bin/env python
from __future__ import print_function
# ----------------------------------------------------------------------------
# Copyright (c) 2014--, microLearner development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
__credits__ = "microLearner development team"
__version__ = "1.0.0-dev"
from numpy.testing import Tester
test = Tester().test,
|
{"/microLearner/cmd.py": ["/microLearner/util/misc.py"], "/microLearner/tests/test_instances.py": ["/microLearner/instances.py"]}
|
19,825
|
Hosseinberg/pyqentangle_Hosseinberg
|
refs/heads/master
|
/pyqentangle/schmidt.py
|
import numpy as np
from .bipartite_reddenmat_nocheck import bipartitepurestate_reduceddensitymatrix_nocheck
from .bipartite_denmat import bipartitepurestate_densitymatrix_cython
# total density matrix
def bipartitepurestate_densitymatrix(bipartitepurestate_tensor):
"""Calculate the whole density matrix of the bipartitite system
Given a discrete normalized quantum system, given in terms of 2-D numpy array ``bipartitepurestate_tensor``,
each element of ``bipartitepurestate_tensor[i, j]`` is the coefficient of the ket :math:`|ij\\rangle`,
calculate the whole density matrix.
:param bipartitepurestate_tensor: tensor describing the bi-partitite states, with each elements the coefficients for :math:`|ij\\rangle`
:return: density matrix
:type bipartitepurestate_tensor: numpy.ndarray
:rtype: numpy.ndarray
"""
return bipartitepurestate_densitymatrix_cython(bipartitepurestate_tensor)
def bipartitepurestate_reduceddensitymatrix(bipartitepurestate_tensor, kept):
"""Calculate the reduced density matrix for the specified subsystem
Given a discrete normalized quantum system, given in terms of 2-D numpy array ``bipartitepurestate_tensor``,
each element of ``bipartitepurestate_tensor[i, j]`` is the coefficient of the ket :math:`|ij\\rangle`,
calculate the reduced density matrix of the specified subsystem.
:param bipartitepurestate_tensor: tensor describing the bi-partitite states, with each elements the coefficients for :math:`|ij\\rangle`
:param kept: subsystem, 0 indicating the first subsystem; 1 the second
:return: reduced density matrix of the specified subsystem
:type bipartitepurestate_tensor: numpy.ndarray
:type kept: int
:rtype: numpy.ndarray
"""
if not (kept in [0, 1]):
raise ValueError('kept can only be 0 or 1!')
return bipartitepurestate_reduceddensitymatrix_nocheck(bipartitepurestate_tensor, kept)
def schmidt_decomposition(bipartitepurestate_tensor):
"""Calculate the Schmidt decomposition of the given discrete bipartite quantum system
Given a discrete normalized quantum system, given in terms of 2-D numpy array ``bipartitepurestate_tensor``,
each element of ``bipartitepurestate_tensor[i, j]`` is the coefficient of the ket :math:`|ij\\rangle`,
calculate its Schmidt decomposition, returned as a list of tuples, where each tuple contains
the Schmidt coefficient, the vector of eigenmode of first subsystem, and the vector of the eigenmode of
second subsystem.
:param bipartitepurestate_tensor: tensor describing the bi-partitite states, with each elements the coefficients for :math:`|ij\\rangle`
:return: list of tuples containing the Schmidt coefficient, eigenmode for first subsystem, and eigenmode for second subsystem
:type bipartitepurestate_tensor: numpy.ndarray
:rtype: list
"""
state_dims = bipartitepurestate_tensor.shape
mindim = np.min(state_dims)
vecs1, diags, vecs2_h = np.linalg.svd(bipartitepurestate_tensor)
vecs2 = vecs2_h.transpose()
#decomposition = [(diags[k]*diags[k], vecs1[:, k], transposevecs2[:, k])
# for k in range(mindim)]
decomposition = [(diags[k], vecs1[:, k], vecs2[:, k])
for k in range(mindim)]
decomposition = sorted(decomposition, key=lambda dec: dec[0], reverse=True)
return decomposition
|
{"/pyqentangle/continuous.py": ["/pyqentangle/__init__.py"], "/pyqentangle/__init__.py": ["/pyqentangle/schmidt.py", "/pyqentangle/continuous.py", "/pyqentangle/metrics.py"]}
|
19,826
|
Hosseinberg/pyqentangle_Hosseinberg
|
refs/heads/master
|
/pyqentangle/continuous.py
|
from itertools import product
import numpy as np
from .interpolate_nocheck import numerical_continuous_interpolation_nocheck_cython
from . import schmidt_decomposition
disentangled_gaussian = lambda x1, x2: np.exp(-0.5 * (x1 * x1 + x2 * x2)) / np.sqrt(np.pi)
class OutOfRangeException(Exception):
def __init__(self, value):
self.msg = "Out of range: " + str(value)
def __str__(self):
return repr(self.msg)
class UnequalLengthException(Exception):
def __init__(self, array1, array2):
self.msg = "Unequal length: " + str(len(array1)) + " vs. " + str(len(array2))
def __str__(self):
return repr(self.msg)
def numerical_continuous_interpolation(xarray, yarray, x):
"""Evaluate the value of a function given a variable x using interpolation
With a function approximated by given arrays of independent variable (`xarray`)
and of dependent variable (`yarray`), the value of this function given `x` is
calculated by interpolation.
If `x` is outside the range of `xarray`, an `OutOfRangeException`
is raised; if the lengths of `xarray` and `yarray` are not equal, an
`UnequalLengthException` is raised.
:param xarray: an array of independent variable values
:param yarray: an array of dependent variable values
:param x: the input value at where the function is computed at
:return: the value of function with the given `x`
:type xarray: numpy.ndarray
:type yarray: numpy.ndarray
:rtype: float
:raises: OutOfRangeException, UnequalLengthException
"""
if len(xarray) != len(yarray):
raise UnequalLengthException(xarray, yarray)
minx = np.min(xarray)
maxx = np.max(xarray)
if x == maxx:
return yarray[-1]
if not (x >= minx and x < maxx):
raise OutOfRangeException(x)
return numerical_continuous_interpolation_nocheck_cython(xarray, yarray, x)
def numerical_continuous_function(xarray, yarray):
"""Return a function with the given arrays of independent and dependent variables
With a function approximated by given arrays of independent variable (`xarray`)
and of dependent variable (`yarray`), it returns a lambda function that takes
a `numpy.ndarray` as an input and calculates the values at all these elements
using interpolation.
If `x` is outside the range of `xarray`, an `OutOfRangeException`
is raised.
:param xarray: an array of independent variable values
:param yarray: an array of dependent variable values
:return: a lambda function that takes a `numpy.ndarray` as the input parameter and calculate the values
:type xarray: numpy.ndarray
:type yarray: numpy.ndarray
:rtype: function
:raises: OutOfRangeException
"""
return lambda xs: np.array(list(map(lambda x: numerical_continuous_interpolation(xarray, yarray, x), xs)))
def discretize_continuous_bipartitesys(fcn, x1_lo, x1_hi, x2_lo, x2_hi, nb_x1=100, nb_x2=100):
"""Find the discretized representation of the continuous bipartite system
Given a function `fcn` (a function with two input variables),
find the discretized representation of the bipartite system, with
the first system ranges from `x1_lo` to `x1_hi`, and second from `x2_lo` to `x2_hi`.
:param fcn: function with two input variables
:param x1_lo: lower bound of :math:`x_1`
:param x1_hi: upper bound of :math:`x_1`
:param x2_lo: lower bound of :math:`x_2`
:param x2_hi: upper bound of :math:`x_2`
:param nb_x1: number of :math:`x_1` (default: 100)
:param nb_x2: number of :math:`x_2` (default: 100)
:return: discretized tensor representation of the continuous bipartite system
:type fcn: function
:type x1_lo: float
:type x1_hi: float
:type x2_lo: float
:type x2_hi: float
:type nb_x1: int
:type nb_x2: int
:rtype: numpy.ndarray
"""
x1 = np.linspace(x1_lo, x1_hi, nb_x1)
x2 = np.linspace(x2_lo, x2_hi, nb_x2)
tensor = np.zeros((len(x1), len(x2)))
for i, j in product(*map(range, tensor.shape)):
tensor[i, j] = fcn(x1[i], x2[j])
return tensor
def continuous_schmidt_decomposition(fcn, x1_lo, x1_hi, x2_lo, x2_hi, nb_x1=100, nb_x2=100, keep=None):
"""Compute the Schmidt decomposition of a continuous bipartite quantum systems
Given a function `fcn` (a function with two input variables), perform the Schmidt
decomposition, returning a list of tuples, where each contains a Schmidt decomposition,
the lambda function of the eigenmode in the first subsystem, and the lambda function
of the eigenmode of the second subsystem.
:param fcn: function with two input variables
:param x1_lo: lower bound of :math:`x_1`
:param x1_hi: upper bound of :math:`x_1`
:param x2_lo: lower bound of :math:`x_2`
:param x2_hi: upper bound of :math:`x_2`
:param nb_x1: number of :math:`x_1` (default: 100)
:param nb_x2: number of :math:`x_2` (default: 100)
:param keep: the number of Schmidt modes with the largest coefficients to return; the smaller of `nb_x1` and `nb_x2` will be returned if `None` is given. (default: `None`)
:return: list of tuples, where each contains a Schmidt coefficient, the lambda function of the eigenmode of the first subsystem, and the lambda function of the eigenmode of the second subsystem
:type fcn: function
:type x1_lo: float
:type x1_hi: float
:type x2_lo: float
:type x2_hi: float
:type nb_x1: int
:type nb_x2: int
:type keep: int
:rtype: list
"""
tensor = discretize_continuous_bipartitesys(fcn, x1_lo, x1_hi, x2_lo, x2_hi, nb_x1=nb_x1, nb_x2=nb_x2)
decomposition = schmidt_decomposition(tensor)
if keep == None or keep > len(decomposition):
keep = len(decomposition)
x1array = np.linspace(x1_lo, x1_hi, nb_x1)
x2array = np.linspace(x2_lo, x2_hi, nb_x2)
dx1 = (x1_hi - x1_lo) / (nb_x1 - 1.)
dx2 = (x2_hi - x2_lo) / (nb_x2 - 1.)
renormalized_decomposition = []
#s = list(map(lambda item: item[0], decomposition))
sumeigvals = np.sum(list(map(lambda dec: dec[0], decomposition)))
#sumeigvals = np.sum(list(map(lambda i: s[i]**2, range(keep))))
for i in range(keep):
schmidt_weight, unnorm_modeA, unnorm_modeB = decomposition[i]
normA = np.linalg.norm(unnorm_modeA) * np.sqrt(dx1)
normB = np.linalg.norm(unnorm_modeB) * np.sqrt(dx2)
renormalized_decomposition.append(
( (schmidt_weight / sumeigvals),
numerical_continuous_function(x1array, unnorm_modeA / normA),
numerical_continuous_function(x2array, unnorm_modeB / normB)
)
)
return renormalized_decomposition
|
{"/pyqentangle/continuous.py": ["/pyqentangle/__init__.py"], "/pyqentangle/__init__.py": ["/pyqentangle/schmidt.py", "/pyqentangle/continuous.py", "/pyqentangle/metrics.py"]}
|
19,827
|
Hosseinberg/pyqentangle_Hosseinberg
|
refs/heads/master
|
/pyqentangle/metrics.py
|
import numpy as np
from .negativity_utils import bipartitepurestate_partialtranspose_subsys0_densitymatrix_cython
from .negativity_utils import bipartitepurestate_partialtranspose_subsys1_densitymatrix_cython
from .bipartite_denmat import flatten_bipartite_densitymatrix_cython
def schmidt_coefficients(schmidt_modes):
""" Retrieving Schmidt coefficients from Schmidt modes.
:param schmidt_modes: Schmidt modes
:return: Schmidt coefficients
:type schmidt_modes: list
:rtype: numpy.array
"""
return np.array([mode[0] for mode in schmidt_modes])
def entanglement_entropy(schmidt_modes):
"""Calculate the entanglement entropy
Given the calculated Schmidt modes, compute the entanglement entropy
with the formula :math:`H=-\\sum_i p_i \log p_i`.
:param schmidt_modes: Schmidt modes
:return: the entanglement entropy
:type schmidt_modes: list
:rtype: numpy.float
"""
eigenvalues = np.real(schmidt_coefficients(schmidt_modes))
eigenvalues = np.extract(eigenvalues > 0, eigenvalues)
entropy = np.sum(- eigenvalues * np.log(eigenvalues))
return entropy
# participation ratio
def participation_ratio(schmidt_modes):
"""Calculate the participation ratio
Given the calculated Schmidt modes, compute the participation ratio
with the formula :math:`K=\\frac{1}{\\sum_i p_i^2}`.
:param schmidt_modes: Schmidt modes
:return: participation ratio
:type schmidt_modes: list
:rtype: numpy.float
"""
eigenvalues = np.real(np.real(schmidt_coefficients(schmidt_modes)))
K = 1. / np.sum(eigenvalues * eigenvalues)
return K
# negativity
def negativity(bipartite_tensor):
"""Calculate the negativity
Given a normalized bipartite discrete state, compute the negativity
with the formula :math:`N = \\frac{||\\rho^{\Gamma_A}||_1-1}{2}`
:param bipartitepurestate_tensor: tensor describing the bi-partitite states, with each elements the coefficients for :math:`|ij\\rangle`
:return: negativity
:type bipartitepurestate_tensor: numpy.ndarray
:rtype: numpy.float
"""
dim0, dim1 = bipartite_tensor.shape
flatten_fullden_pt = flatten_bipartite_densitymatrix_cython(bipartitepurestate_partialtranspose_subsys0_densitymatrix_cython(bipartite_tensor)
if dim0 < dim1
else bipartitepurestate_partialtranspose_subsys1_densitymatrix_cython(bipartite_tensor))
eigenvalues = np.linalg.eigvals(flatten_fullden_pt)
return 0.5 * (np.sum(np.abs(eigenvalues)) - 1)
|
{"/pyqentangle/continuous.py": ["/pyqentangle/__init__.py"], "/pyqentangle/__init__.py": ["/pyqentangle/schmidt.py", "/pyqentangle/continuous.py", "/pyqentangle/metrics.py"]}
|
19,828
|
Hosseinberg/pyqentangle_Hosseinberg
|
refs/heads/master
|
/setup.py
|
from setuptools import setup, Extension
import numpy as np
# reference: https://stackoverflow.com/questions/46784964/create-package-with-cython-so-users-can-install-it-without-having-cython-already
try:
from Cython.Build import cythonize
ext_modules = cythonize(['pyqentangle/interpolate_nocheck.pyx',
'pyqentangle/bipartite_reddenmat_nocheck.pyx',
'pyqentangle/bipartite_denmat.pyx',
'pyqentangle/negativity_utils.pyx'])
except ImportError:
ext_modules = [Extension('pyqentangle.interpolate_nocheck',
sources=['pyqentangle/interpolate_nocheck.c']),
Extension('pyqentangle.bipartite_reddenmat_nocheck',
sources=['pyqentangle/bipartite_reddenmat_nocheck.c']),
Extension('pyqentangle.bipartite_denmat',
sources=['pyqentangle/bipartite_denmat.c']),
Extension('pyqentangle.negativity_utils',
sources=['pyqentangle/negativity_utils.c'])]
def readme():
with open('README.md') as f:
return f.read()
setup(name='pyqentangle',
version="2.0.0",
description="Quantum Entanglement for Python",
long_description="Schmidt decomposition for discrete and continuous bi-partite quantum systems",
classifiers=[
"Topic :: Scientific/Engineering :: Physics",
"Topic :: Scientific/Engineering :: Mathematics",
"Topic :: Scientific/Engineering :: Chemistry",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Cython",
"Programming Language :: C",
"Intended Audience :: Science/Research",
"Intended Audience :: Developers",
"Intended Audience :: Education"
],
keywords="quantum physics Schmidt decompostion entanglement",
url="https://github.com/stephenhky/pyqentangle",
author="Kwan-Yuet Ho",
author_email="stephenhky@yahoo.com.hk",
license='MIT',
packages=['pyqentangle'],
include_dirs=[np.get_include()],
setup_requires=['Cython', 'numpy', ],
install_requires=['numpy',],
tests_require=['unittest2', 'numpy', 'scipy',],
ext_modules=ext_modules,
test_suite="test",
include_package_data=True,
zip_safe=False)
|
{"/pyqentangle/continuous.py": ["/pyqentangle/__init__.py"], "/pyqentangle/__init__.py": ["/pyqentangle/schmidt.py", "/pyqentangle/continuous.py", "/pyqentangle/metrics.py"]}
|
19,829
|
Hosseinberg/pyqentangle_Hosseinberg
|
refs/heads/master
|
/pyqentangle/__init__.py
|
from .schmidt import schmidt_decomposition
from .continuous import continuous_schmidt_decomposition, OutOfRangeException, UnequalLengthException
from .metrics import entanglement_entropy, participation_ratio, negativity
|
{"/pyqentangle/continuous.py": ["/pyqentangle/__init__.py"], "/pyqentangle/__init__.py": ["/pyqentangle/schmidt.py", "/pyqentangle/continuous.py", "/pyqentangle/metrics.py"]}
|
19,834
|
alexandreday/kSAT_sample
|
refs/heads/master
|
/script_run/main_kSAT.py
|
import sys, os
############################ READ COMMAND LINE ##########################
argv = sys.argv
assert len(argv) == 4 # need to specify number of clauses, alpha and number of samples
argv = argv[1:]
param_type={
'M':int,
'N':int,
'n_sample':int
}
param = {}
for a in argv:
k, v = a.split('=')
v = int(float(v))
param[k] = v
print(param)
alpha = param['M']/param['N']
new_dir = 'alpha=%.3f'%alpha
cmd = 'mkdir %s'%new_dir
cmd_rm = 'rm -rf %s'%new_dir
os.system(cmd_rm) # create new directory
os.system(cmd) # create new directory
os.system('cp merge sp verify walksat kSAT.py check_sol.py %s/'%new_dir)
os.chdir(new_dir)
new_cmd = '~/.conda/envs/py35/bin/python kSAT.py n=%i alpha=%.3f n_sample=%i'%(param['N'], alpha, param['n_sample'])
#print(new_cmd)
os.system(new_cmd)
|
{"/check_sol.py": ["/kSAT.py"]}
|
19,835
|
alexandreday/kSAT_sample
|
refs/heads/master
|
/kSAT.py
|
import numpy as np
import pickle, os, sys
import time
def main():
"""
Use in the following way (example):
python kSAT.py n=1000 alpha=3.5 n_sample=10000
What the code below does:
-> Generates a random K-SAT (pure K-SAT) formula, which is save in "formula.tmp_N=%_M=%i_alpha=%.2f_K=%i.cnf" file
-> Tries to find solutions to that formula. the number of desired solution is specified by the n_sample parameter
-> Solutions are written in (example) files with names of the form sol_N1000=_M=3900_alpha=3.90_K=3.txt.
"""
argv = sys.argv[1:]
type_arg = {'n':int,'alpha':float,'n_sample':int}
tmp = {a.split('=')[0]:a.split('=')[1] for a in argv}
for k,v in tmp.items():
tmp[k] = type_arg[k](float(v))
assert len(tmp) == 3, "need to specify the 3 parameters, example : n=1000 alpha=3.5 n_sample=10000"
model = KSAT(N_ = tmp['n'], alpha_ = tmp['alpha'], K_ = 3, random_state=0) # kSAT class
N, M, alpha, K = model.get_param()
formula_file = "formula.tmp_N=%i_M=%i_alpha=%.2f_K=%i.cnf"%(N, M, alpha, K)
model.generate_formula(savefile=formula_file) # generate random formula (optional)
model.solve_formula(read_file=formula_file, n_sample=tmp['n_sample']) # read formula written in read_file and runs sp code
################################
################################
################################
def save(obj, file):
f = open(file,'wb')
pickle.dump(obj,f)
f.close()
def load(file):
f = open(file,'rb')
return pickle.load(f)
class KSAT:
def __init__(self, N_ = 1000, alpha_ = 3.8, K_=3, random_state = 0):
np.random.seed(random_state) # by default u always get the same thing for the same parameters !
self.N = N_
self.alpha = alpha_
self.K = K_
self.M = round(self.N * self.alpha)
def get_param(self):
return self.N, self.M, self.alpha, self.K
def generate_formula(self, savefile = None):
""" Generates a random formula based on N,M,alpha,K parameters specified in the constructor
Parameters
-------------
savefile: str, optional
file in which the CNF formula is to be saved. This is done via np.savetxt()
Returns
-------
self
"""
N, M, alpha, K = self.get_param()
all_idx = np.arange(1, N+1,dtype=int)
signs = np.array([-1,1],dtype=int)
clause_set = set([])
while len(clause_set) < M:
literals = np.random.choice(all_idx, size=K, replace=False)
clause = literals*np.random.choice(signs, size=K)
clause_set.add(tuple(clause))
zeros = np.zeros(M,dtype=int).reshape(-1,1)
self.formula = np.array(list(clause_set))
if savefile is not None:
np.savetxt(savefile, np.hstack((self.formula, zeros)), fmt='%i', delimiter=" ", header = 'p cnf %i %i'%(N,M), comments='')
return self
def solve_formula(self, read_file = None, n_sample = 1):
N, M, alpha, K = self.get_param()
seed = np.random.randint(0, sys.maxsize)
solutions = []
zeros = np.zeros(M,dtype=int).reshape(-1,1)
restart_count = 0
n_restart = 50
## reading formula file or generating new random formula
if read_file is None:
formula_file = "formula.tmp_N=%i_M=%i_alpha=%.2f_K=%i.cnf"%(N, M, alpha, K) # meaningful file name !
self.generate_formula(savefile=formula_file)
formula = self.formula
else:
formula_file = read_file
formula = np.loadtxt(formula_file, dtype=int, skiprows=1, delimiter=' ')[:,:3]
if n_sample == 1:
os.system("./sp -l %s -s%i"%(formula_file,seed))
else:
nn =0
while nn < n_sample:
os.system("rm noconvergence.tmp.cnf")
if restart_count > n_restart :
"X permutations, still not working !"
print("Stopping, no solutions found !")
break
print("----------------> sample # \t", nn)
#print(restart_count)
#For generating SAT solutions sampled uniformly at random !
idx_ori = np.arange(1, N+1, dtype=int)
idx_new = np.arange(1, N+1, dtype=int)
np.random.shuffle(idx_new)
rand_permutation_map = dict(zip(idx_ori,idx_new))
inv_rand_permutation_map = dict(zip(idx_new,idx_ori))
isometry_formula = np.array([np.sign(x)*rand_permutation_map[abs(x)] for x in formula.flatten()], dtype=int)
isometry_formula=isometry_formula.reshape(-1, K)
file_tmp = '.tmp.cnf.formula.permutation'
np.savetxt('.tmp.cnf.formula.permutation', np.hstack((isometry_formula, zeros)), fmt='%i', delimiter=" ", header = 'p cnf %i %i'%(N,M), comments='')
seed = np.random.randint(0,2**32-1)
os.system("./sp -l %s -s%i > out.txt"%(file_tmp, seed)) # solves the permuted formula (equivalent !)
if os.path.exists("noconvergence.tmp.cnf"):
"Solution not find, try a different permutation"
restart_count +=1
else:
nn+=1
restart_count = 0
if self.check_solution(solution_file='solution.tmp.lst', formula_file='.tmp.cnf.formula.permutation'):
sol_tmp = np.loadtxt('solution.tmp.lst', dtype=int)
sol_tmp_2 = np.array([np.sign(v)*inv_rand_permutation_map[abs(v)] for v in sol_tmp], dtype=int)
sol_tmp_2 = sol_tmp_2[np.argsort(np.abs(sol_tmp_2))]
is_solution = self.check_solution(solution_array=sol_tmp_2)
if is_solution:
solutions.append(sol_tmp_2)
if nn % (n_sample // 10) == 0 and n_sample > 10 and len(solutions) > 0:
print(nn, " saving")
solution_stack = np.sign(np.vstack(solutions))
solution_stack[solution_stack < 0] = 0
save(np.packbits(solution_stack),'sol_N=%i_M=%i_alpha=%.2f_K=%i.pkl'%(N,M,alpha,K))
#np.savetxt('sol_N=%i_M=%i_alpha=%.2f_K=%i.txt'%(N,M,alpha,K), np.packbits(solution_stack, axis=1), fmt="%i")
if len(solutions) > 0:
solution_stack = np.sign(np.vstack(solutions))
solution_stack[solution_stack < 0] = 0
save(np.packbits(solution_stack), 'sol_N=%i_M=%i_alpha=%.2f_K=%i.pkl'%(N,M,alpha,K))
#np.savetxt('sol_N=%i_M=%i_alpha=%.2f_K=%i.txt'%(N,M,alpha,K), np.packbits(solution_stack, axis=1), fmt="%i")
#np.savetxt('sol_N=%i_M=%i_alpha=%.2f_K=%i.txt'%(N,M,alpha,K), solution_stack,fmt="%i")
#print(np.vstack(solutions)[:,:10])
def check_all_solution(self, N, solution_file, formula_file, hist=True):
formula = np.loadtxt(formula_file, dtype=int, skiprows=1, delimiter=' ')[:,:3]
self.formula = formula
tmp = np.unpackbits(load(solution_file),axis=1)[:,N]
all_solution = tmp.astype(int)
N_sol = all_solution.shape[0]
sol_result=[]
idx_var = np.arange(1,N+1,dtype=int)
count_true = 0
print("Checking %i solutions"%N_sol)
for i in range(N_sol):
sol = all_solution[i]*idx_var
res = self.check_solution(solution_array=sol)
if res is True:
count_true +=1
else:
print("Found wrong solution !?")
print("%i out of the %i solutions are correct"%(count_true,N_sol))
n_unique = len(np.unique(all_solution, axis=0))
print("number of unique solutions :\t %i"%(n_unique))
if hist is True:
from matplotlib import pyplot as plt
import seaborn as sns
mag = np.mean(all_solution,axis=0)
nbin = max([N_sol/10,20])
N, M, alpha, K = self.infer_parameters(solution_file)
sns.distplot(mag,bins=nbin,kde=False)
plt.xlabel('magnetization')
plt.title('nsample = %i, N=%i, M=%i, alpha=%.2f, K=%i'%(N_sol, N, M, alpha, K))
plt.show()
def infer_parameters(self, solution_file):
sol_s = solution_file.strip(".txt").split('_')
for p in sol_s:
if '=' in p:
ps = p.split('=')
if ps[0] == 'N':
N = int(float(ps[1]))
elif ps[0] == 'M':
M = int(float(ps[1]))
elif ps[0] == 'alpha':
alpha = float(ps[1])
elif ps[0] == 'K':
K = int(float(ps[1]))
return N, M, alpha, K
def check_solution(self, solution_file=None, solution_array=None, formula_file = None):
K = self.K
if formula_file is None:
formula = self.formula
else:
formula = np.loadtxt(formula_file, dtype=int, skiprows=1, delimiter=' ')[:,:3]
if solution_array is not None:
solution = solution_array
else:
solution = np.loadtxt(solution_file, dtype=int)
variable_label = np.abs(solution)
var_max = np.max(variable_label)
solution_map = np.zeros(var_max+1,dtype=int)
solution_map[variable_label] = np.sign(solution)
abs_formula = np.abs(formula)
sign_formula = np.sign(formula)
res = solution_map[abs_formula]*sign_formula
return np.count_nonzero(np.sum(res, axis=1) == -K) == 0 # check that all clauses are SAT
if __name__ == "__main__":
main()
|
{"/check_sol.py": ["/kSAT.py"]}
|
19,836
|
alexandreday/kSAT_sample
|
refs/heads/master
|
/XOR/runme.py
|
from xor import XOR_SOLVE
import sys, os
import time
import pickle
import numpy as np
param = {}
### default parameters
param['N'] = 1000
param['alpha'] = 0.8
param['n_sample'] = 100
param['K'] = 3
### command line specified parameters
if len(sys.argv) > 1: # > > > read the parameters from the command line // overwrites default parameters
for a in sys.argv[1:]:
name, value = a.split('=')
param[name] = float(value) # more stable across platforms to cast str to float
param['M'] = param['alpha']*param['N']
print('[xor.py] Running with the following parameters ...')
print(param)
start_time = time.time()
xor = XOR_SOLVE(int(param['N']), int(param['M']), int(param['K']), save_formula=False)
A_original = np.copy(xor.A)
X = xor.sample_solution(int(param['n_sample']), verbose=True)
print('Elapsed time:', time.time() - start_time)
# saving the solution and the formula (save the seed used to generate the formula ?) --> or not !
# want to save the solution a data file, but is dependent on the formula used ...
N=int(param['N'])
alpha=param['alpha']
K=int(param['K'])
root = 'data/'
file_formula = root+'formula/formula_idx=%i_N=%i_a=%.3f_K=%i.pkl'
file_solution = root+'sol/xor_sol_idx=%i_N=%i_a=%.3f_K=%i.pkl'
idx = 0
while os.path.isfile(file_formula%(idx, N, alpha, K)):
idx+=1
file_formula=file_formula%(idx, N, alpha, K)
file_solution=file_solution%(idx, N, alpha, K)
print('[xor.py] data saved to :')
print(file_formula)
print(file_solution)
pickle.dump([xor.f, xor.y_original], open(file_formula,'wb'))
pickle.dump(np.packbits(X), open(file_solution,'wb'))
|
{"/check_sol.py": ["/kSAT.py"]}
|
19,837
|
alexandreday/kSAT_sample
|
refs/heads/master
|
/check_sol.py
|
from kSAT import KSAT
# -----------> just check solutions --->
model = KSAT()
M=4050
a = 4.05
sfile = 'sol_N=1000_M=%i_alpha=%.2f_K=3.txt'%(M,a)
ffile = 'formula.tmp_N=1000_M=%i_alpha=%a_K=3.cnf'%(M,a)
model.check_all_solution(sfile,ffile)
|
{"/check_sol.py": ["/kSAT.py"]}
|
19,838
|
alexandreday/kSAT_sample
|
refs/heads/master
|
/XOR/analysis/plot_TSNE.py
|
from matplotlib import pyplot as plt
import numpy as np
import pickle
from fdc import FDC, plotting
from sklearn.preprocessing import StandardScaler as SS
# CONCLUSION => TSNE is a big
# => be careful next time
N=500
K=3
alpha_range = np.arange(0.5,1.001,0.01)
root= '/Users/alexandreday/GitProject/kSAT_sample/XOR/data/TSNE5/'
root_hist= '/Users/alexandreday/GitProject/kSAT_sample/XOR/data/distance/'
root_out= '/Users/alexandreday/GitProject/kSAT_sample/XOR/analysis/plots/'
for a in alpha_range:
#print(a)
f = 'tSNE_N=%i_a=%.3f_K=%i.pkl'%(N,a,K)
X,l = pickle.load(open(root+f,'rb'))
print(a,'\t',l)
#print(a, lX, pca_r,sep='\t')
plt.scatter(X[:,0], X[:,1],s=0.5)
plt.show()
""" f_hist = 'dist_N=%i_a=%.3f_K=%i.pkl'%(N,a,K)
x,y = pickle.load(open(root_hist+f_hist,'rb'))
#print(len(y[1:]),len(x))
#plt.scatter(np.diff(y)+0.005,x)
#print(len(x),len(y))
plt.plot(y[1:],np.log(x))
plt.show() """
#X = SS().fit_transform(X)
#modelfdc=FDC(eta = 0.0)
#modelfdc.fit(X)
#plotting.cluster_w_label(X, modelfdc.cluster_label)
""" plt.scatter(X[:,0], X[:,1], s=3, alpha=0.5)
plt.title('$N=%i,\\alpha=%.3f, K=%i$'%(N,a,K))
plt.xticks([])
plt.yticks([])
fout = f.strip('.pkl')+'.pdf'
plt.tight_layout()
plt.savefig(root_out+fout)
plt.clf() """
#plt.show()
|
{"/check_sol.py": ["/kSAT.py"]}
|
19,839
|
alexandreday/kSAT_sample
|
refs/heads/master
|
/XOR/analysis/distance.py
|
from tsne_visual import TSNE
import numpy as np
import sys, os
import pickle
from sklearn.decomposition import PCA
from scipy.spatial.distance import squareform,cdist,pdist
i_param = int(float(sys.argv[1].split('=')[1])) # specified through the command line !
root_in= '/projectnb/fheating/SAT_GLASS/XORSAT/data/sol/' # root absolute path insert here ...
root_out = '/projectnb/fheating/SAT_GLASS/XORSAT/analysis/distance/'
file_list = '/projectnb/fheating/SAT_GLASS/XORSAT/data/sol/file_name.txt' # absolute path insert here ..
i_count = 0
fname_out = None
for f in open(file_list,'r'):
if i_count == i_param:
fname_in = root_in+f.strip('\n')
sp = f.strip('\n').split('_')
param = sp[3:]
fname_out = root_out+'dist_'+'_'.join(sp[3:])
break
i_count+=1
print('Reading from %s'%fname_in)
print('Saving in %s'%fname_out)
# ---------> RUNNING TSNE
if fname_out is not None:
X = np.unpackbits(pickle.load(open(fname_in,'rb'))).astype(int).reshape(10000, -1)
nonsquare = pdist(X, metric='hamming')
D = squareform(nonsquare)
y, x = np.histogram(nonsquare, bins=np.linspace(0.0025,1,100))
pickle.dump([y, x], open(fname_out,'wb'))
|
{"/check_sol.py": ["/kSAT.py"]}
|
19,840
|
alexandreday/kSAT_sample
|
refs/heads/master
|
/XOR/xor.py
|
import numpy as np
import time
import pickle
from collections import Counter
def main():
alpha = np.arange(0.5, 1.001, 0.01)
N=100
K=3
time_vs_alpha = []
entropy_vs_alpha= []
for a in alpha:
print('alpha = %.3f'%a)
M = int(a*N)
xor = XOR_SOLVE(N, M, K, save_formula = True)
t_start= time.time()
X = xor.sample_solution(10000, verbose=True)
time_vs_alpha.append(time.time() - t_start)
entropy_vs_alpha.append(xor.entropy())
for x in X:
assert xor.check_solution(x)
save_solution_file = 'sol/solution_N=%i_M=%i_K=%i.pkl'%(N,M,K)
if len(X) > 0:
pickle.dump(np.packbits(X), open(save_solution_file,'wb'))
pickle.dump(entropy_vs_alpha, open('entropy/entropy_N=%i_M=%i_K=%i.pkl'%(N,M,K),'wb'))
pickle.dump(time_vs_alpha, open('time/time_N=%i_M=%i_K=%i.pkl'%(N,M,K),'wb'))
def sample_tuple(N, K): # sample tuple uniformly at random
trace = []
tup = []
for i in range(K):
pos = np.random.randint(0, N-i)
value = pos
for t in reversed(trace): # iterate from last element
if value > t-1:
value +=1
tup.append(value)
trace.append(pos)#print(trace)
tup.sort()
return tup
def generate_XOR_formula(N=10, M=10, K=3):
""" generates a XORSAT formula
"""
formula = set([])
while len(formula) < M:
tup = tuple(sample_tuple(N, K))
formula.add(tup)
return list(formula) # better to work with lists => order is always preserved !
def generate_sparse(N=10, M=10, K=3, formula=None):
# Can specify formula, but still have to specify N,M,K
if formula is not None:
formula = formula
else:
formula = generate_XOR_formula(N,M,K)
A = np.zeros((M,N),dtype=int)
for i, clause in enumerate(formula):
for literal in clause:
A[i, literal]=1
return A, formula
def verify_solution(A, y, sol):
nclause = A.shape[0]
for i in range(nclause):
if np.dot(A[i, :], sol) % 2 != y[i]:
return False
return True
def swap_rows(A, ri, rj):
tmp = np.copy(A[ri, :]) # careful when slicing, will return a view
A[ri, :] = A[rj, :]
A[rj, :] = tmp
def swap(y, i, j):
tmp = y[i]
y[i] = y[j]
y[j] = tmp
def add_to_row(A, ri, rj): # A[ri, :] <- A[ri, :] + A[rj, :]
A[ri, :] = A[ri, :] + A[rj, :]
def make_diagonal(A_, y_, copy=False):
""" This reduction is unique """
if copy:
A=np.copy(A_)
y=np.copy(y_)
else:
A = A_
y = y_
#1 clean up zero columns ? (no !)
M, N = A.shape
pos_pivot = 0
pivot_list = []
j = 0
for i in range(M): # go over lines, for each line find pivot !
for j in range(i, N):
pos_one = np.where(A[:,j] == 1)[0]
if len(pos_one) > 0:
pos_one = pos_one[pos_one > (i - 1)]
if len(pos_one) > 0:
if A[i, j] == 0:
swap_rows(A, i, pos_one[0])
swap(y, i, pos_one[0])
pos_one = np.where(A[:,j] == 1)[0]
for k in pos_one:
if k > i :
A[k] += A[i] # mod 2
A[k] = np.remainder(A[k], 2)
y[k] = (y[k] + y[i])%2 # mod 2
pivot_list.append([i, j])
break
for pivot in reversed(pivot_list):
i, j = pivot
pos_one = np.where(A[:,j] == 1)[0]
pos_one = pos_one[pos_one < i]
for k in pos_one:
A[k] += A[i] # mod 2
A[k] = np.remainder(A[k], 2)
y[k] = (y[k] + y[i])%2 # mod 2
if copy is True:
return A, y, np.array(pivot_list,dtype=int)
else:
return np.array(pivot_list,dtype=int)
def find_pivot(A_UT):
return np.where(np.diagonal(A_UT) == 1)[0]
def solve_ES(A, y):
""" Solver using exhaustive search of all configurations """
nvar = A.shape[1]
nsol = 2**nvar
b2_array = lambda n10 : np.array(list(np.binary_repr(n10, width=nvar)), dtype=np.int)
sol_list = []
for i in range(nsol):
sol = b2_array(i)
if check_solution(A, y, sol):
sol_list.append(sol)
return sol_list
def marginals(solution_set): # unique variable marginals
if len(solution_set) > 0:
return np.mean(solution_set, axis=0)
else:
[]
def enumerate_solution_GE(A, y):
""" A has to be in a reduced form """
M, N = A.shape
pivots = np.where(np.diagonal(A) == 1)[0] # pivots are identified
none_pivots = np.setdiff1d(np.arange(N), pivots)
none_pivots_2 = np.setdiff1d(np.arange(M), pivots)
rank = len(pivots) # matrix rank
xsol = -1*np.ones(N, dtype=int) # unconstrained variables are marked by a -2
N_free = N - rank # upper bound on number of log of number of solutions (but may be fewer !)
b2_array = lambda n10 : np.array(list(np.binary_repr(n10, width=N_free)), dtype=np.int)
all_sol = []
pivot_set = set(list(pivots))
for i in range(2**N_free): # HERE REPLACE BY SAMPLING, THIS THE SPACE WE WISH TO SAMPLE !
is_sol = False
xsol = -1*np.ones(N, dtype=int) # unconstrained variables are marked by a -2
xsol[none_pivots] = b2_array(i)
y_res = np.remainder(np.dot(A[:,none_pivots], xsol[none_pivots].T) + y, 2)
if np.count_nonzero(y_res[none_pivots_2] == 1) == 0:
xsol[pivots] = y_res[pivots]
is_sol = True
if is_sol:
all_sol.append(xsol)
return all_sol
def is_SAT(A, y):
tmp = np.sum(A, axis=1)
return np.count_nonzero(y[tmp == 0] == 1) == 0
def sample_solution_GE(A, y, pivot_ls):
""" A is in row-echelon form with pivot position provided in pivot_ls
"""
M, N = A.shape
t_init = time.time()
n_pivot = len(pivot_ls)
n_free = N - n_pivot
pos_pivot = pivot_ls[:,1]
none_pivot_pos = np.setdiff1d(np.arange(N), pos_pivot)
xsol = np.ones(N,dtype=int)
xsol[none_pivot_pos] = np.random.randint(0, 2, n_free)
for p in reversed(pivot_ls):
i, j = p
xsol[j]^= (y[i] + np.dot(A[i, :], xsol)) % 2
assert verify_solution(A, y, xsol)
return xsol
class XOR_SOLVE:
def __init__(self, N=100, M=80, K=3, f=None, y=None, save_formula=True):
self.N = N
self.M = M
self.K = K
self.A, self.f = generate_sparse(N, M, K, formula = f) # A is not reduced at this point
if save_formula:
file_name = 'formula/formula_N=%i_M=%i_K=%i.pkl'%(N,M,K)
pickle.dump(self.f, open(file_name,'wb'))
if y is not None:
self.y_original = np.copy(y)
else:
self.y_original= np.random.randint(0, 2, M) # random constraints
self.y = np.copy(self.y_original)
self.is_reduced = False
def reduce_system(self):
self.pivots = make_diagonal(self.A, self.y)
self.is_reduced = True
def entropy(self):
if self.SAT():
return (self.N - len(self.pivots))/self.N
else:
return 0
def SAT(self):
if not self.is_reduced:
self.reduce_system()
return is_SAT(self.A, self.y)
def sample_solution(self, n_sample = 10, verbose = 0):
if not self.is_reduced:
self.reduce_system()
if self.SAT() is False:
print("No SOLUTION")
return []
x_sample_solution = []
for i in range(n_sample):
if verbose != 0:
if i % 500 == 0:
print(i)
x_sample_solution.append(sample_solution_GE(self.A, self.y, self.pivots))
return x_sample_solution
def check_solution(self, x):
return verify_solution(self.A, self.y, x)
def check_solution_formula(self, x):
for i, clause in enumerate(self.f):
np.sum(x[np.array(list(clause))]) % 2 != self.y_original[i]:
return False
return True
if __name__ == "__main__":
main()
|
{"/check_sol.py": ["/kSAT.py"]}
|
19,841
|
alexandreday/kSAT_sample
|
refs/heads/master
|
/XOR/analysis/analysis.py
|
import numpy as np
import pickle
from matplotlib import pyplot as plt
import sys
sys.path.append('..')
from xor import XOR_SOLVE
def main():
root_sol = '../data/sol/'
root_formula = '../data/formula/'
N=1000
formula, y = pickle.load(open(root_formula + 'formula_idx=0_N=1000_a=0.800_K=3.pkl','rb'))
X = np.unpackbits(pickle.load(open(root_sol + 'xor_sol_idx=0_N=1000_a=0.800_K=3.pkl','rb'))).astype(int).reshape(-1, N)
xor = XOR_SOLVE(N=1000, M=800, K=3, f=formula, y=y, save_formula=False)
if __name__ == "__main__":
main()
|
{"/check_sol.py": ["/kSAT.py"]}
|
19,842
|
alexandreday/kSAT_sample
|
refs/heads/master
|
/XOR/analysis/tSNE.py
|
from tsne_visual import TSNE
import numpy as np
import sys, os
import pickle
from sklearn.decomposition import PCA
i_param = int(float(sys.argv[1].split('=')[1])) # specified through the command line !
root_in= '/projectnb/fheating/SAT_GLASS/XORSAT/data/sol/' # root absolute path insert here ...
root_out = '/projectnb/fheating/SAT_GLASS/XORSAT/analysis/TSNE2/'
file_list = '/projectnb/fheating/SAT_GLASS/XORSAT/data/sol/file_name.txt' # absolute path insert here ..
i_count = 0
fname_out = None
for f in open(file_list,'r'):
if i_count == i_param:
fname_in = root_in+f.strip('\n')
sp = f.strip('\n').split('_')
param = sp[3:]
fname_out = root_out+'tSNE_'+'_'.join(sp[3:])
break
i_count+=1
print('Reading from %s'%fname_in)
print('Saving in %s'%fname_out)
# ---------> RUNNING TSNE
if fname_out is not None:
X = np.unpackbits(pickle.load(open(fname_in,'rb'))).astype(int).reshape(10000,-1)
X = np.unique(X, axis=0)
model = TSNE(n_components=2, n_iter=2000, perplexity=50)
pca = PCA(n_components=100)
Xpca = pca.fit_transform(X)
Xtsne = model.fit_transform(Xpca)
pickle.dump([Xtsne, np.sum(pca.explained_variance_ratio_),len(X)], open(fname_out,'wb'))
|
{"/check_sol.py": ["/kSAT.py"]}
|
19,843
|
sjkingo/vilicus
|
refs/heads/master
|
/manager/api/resources.py
|
from tastypie import fields
from tastypie.api import Api
from tastypie.authorization import Authorization
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from tastypie.serializers import Serializer
from manager.models import *
v1_api = Api(api_name='v1')
class AgentResource(ModelResource):
class Meta:
queryset = Agent.objects.all()
filtering = {
'id': ALL,
}
allowed_methods = ['get', 'put']
authorization = Authorization()
serializer = Serializer()
v1_api.register(AgentResource())
class WindowsServiceResource(ModelResource):
agent = fields.ForeignKey(AgentResource, 'agent')
class Meta:
queryset = WindowsService.objects.all()
filtering = {
'agent': ALL_WITH_RELATIONS,
}
allowed_methods = ['get']
authorization = Authorization()
serializer = Serializer()
v1_api.register(WindowsServiceResource())
class WindowsServiceLogResource(ModelResource):
service = fields.ForeignKey(WindowsServiceResource, 'service')
class Meta:
queryset = WindowsServiceLog.objects.all()
filtering = {
'service': ALL_WITH_RELATIONS,
}
allowed_methods = ['get', 'post']
authorization = Authorization()
serializer = Serializer()
v1_api.register(WindowsServiceLogResource())
class PerformanceLogEntryResource(ModelResource):
agent = fields.ForeignKey(AgentResource, 'agent')
class Meta:
queryset = PerformanceLogEntry.objects.all()
filtering = {
'agent': ALL_WITH_RELATIONS,
}
allowed_methods = ['post']
authorization = Authorization()
serializer = Serializer()
v1_api.register(PerformanceLogEntryResource())
|
{"/manager/api/resources.py": ["/manager/models.py"], "/manager/signals.py": ["/manager/models.py"], "/notify_pushover/signals.py": ["/manager/models.py"], "/vilicus/urls.py": ["/manager/api/resources.py"], "/dashboard/views.py": ["/manager/models.py"], "/notify_pushover/send.py": ["/notify_pushover/__init__.py"], "/manager/admin.py": ["/manager/models.py"]}
|
19,844
|
sjkingo/vilicus
|
refs/heads/master
|
/manager/signals.py
|
import datetime
from django.db.models.signals import post_save
from django.dispatch import receiver
from manager.models import WindowsServiceLog
@receiver(post_save, sender=WindowsServiceLog)
def update_last_checkin(sender, **kwargs):
kwargs['instance'].service.agent.last_checkin = datetime.datetime.now()
kwargs['instance'].service.agent.save()
|
{"/manager/api/resources.py": ["/manager/models.py"], "/manager/signals.py": ["/manager/models.py"], "/notify_pushover/signals.py": ["/manager/models.py"], "/vilicus/urls.py": ["/manager/api/resources.py"], "/dashboard/views.py": ["/manager/models.py"], "/notify_pushover/send.py": ["/notify_pushover/__init__.py"], "/manager/admin.py": ["/manager/models.py"]}
|
19,845
|
sjkingo/vilicus
|
refs/heads/master
|
/notify_pushover/models.py
|
from django.db import models
class PushoverUserTokens(models.Model):
email = models.EmailField(max_length=254)
token = models.CharField(max_length=30)
description = models.TextField(blank=True)
class Meta:
verbose_name = 'Pushover user token'
verbose_name_plural = verbose_name + 's'
def __unicode__(self):
return self.email + ': ' + self.token
|
{"/manager/api/resources.py": ["/manager/models.py"], "/manager/signals.py": ["/manager/models.py"], "/notify_pushover/signals.py": ["/manager/models.py"], "/vilicus/urls.py": ["/manager/api/resources.py"], "/dashboard/views.py": ["/manager/models.py"], "/notify_pushover/send.py": ["/notify_pushover/__init__.py"], "/manager/admin.py": ["/manager/models.py"]}
|
19,846
|
sjkingo/vilicus
|
refs/heads/master
|
/notify_pushover/__init__.py
|
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
_token_key = 'NOTIFY_PUSHOVER_API_TOKEN'
if not hasattr(settings, _token_key):
raise ImproperlyConfigured(_token_key + ' is missing but is required for the notify_pushover app')
TOKEN_KEY = getattr(settings, _token_key)
import signals
|
{"/manager/api/resources.py": ["/manager/models.py"], "/manager/signals.py": ["/manager/models.py"], "/notify_pushover/signals.py": ["/manager/models.py"], "/vilicus/urls.py": ["/manager/api/resources.py"], "/dashboard/views.py": ["/manager/models.py"], "/notify_pushover/send.py": ["/notify_pushover/__init__.py"], "/manager/admin.py": ["/manager/models.py"]}
|
19,847
|
sjkingo/vilicus
|
refs/heads/master
|
/notify_pushover/signals.py
|
from django.db.models.signals import post_save
from django.dispatch import receiver
from manager.models import WindowsServiceLog
from send import *
class LastStatusDummy(object):
actual_status = '(None)'
@receiver(post_save, sender=WindowsServiceLog)
def log_post_save(sender, **kwargs):
inst = kwargs['instance']
if inst.service.changed_since_last:
status_now = inst.service.latest_log_entries[0]
try:
last_status = inst.service.latest_log_entries[1]
except IndexError:
last_status = LastStatusDummy()
title = '{name} is now {now}'.format(name=inst.service, now=status_now.actual_status)
msg = 'The service {name} running on {agent} has just changed status from {last} -> {now} at {dt}'.format(
name=inst.service, agent=inst.service.agent.hostname,
last=last_status.actual_status, now=status_now.actual_status,
dt=status_now.timestamp)
send_push_notification(title, msg, priority=PRIORITY['HIGH'])
|
{"/manager/api/resources.py": ["/manager/models.py"], "/manager/signals.py": ["/manager/models.py"], "/notify_pushover/signals.py": ["/manager/models.py"], "/vilicus/urls.py": ["/manager/api/resources.py"], "/dashboard/views.py": ["/manager/models.py"], "/notify_pushover/send.py": ["/notify_pushover/__init__.py"], "/manager/admin.py": ["/manager/models.py"]}
|
19,848
|
sjkingo/vilicus
|
refs/heads/master
|
/vilicus/urls.py
|
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from manager.api.resources import v1_api
urlpatterns = patterns('',
(r'^grappelli/', include('grappelli.urls')),
(r'^admin/', include(admin.site.urls)),
(r'^api/', include(v1_api.urls)),
(r'^', include('dashboard.urls')),
)
|
{"/manager/api/resources.py": ["/manager/models.py"], "/manager/signals.py": ["/manager/models.py"], "/notify_pushover/signals.py": ["/manager/models.py"], "/vilicus/urls.py": ["/manager/api/resources.py"], "/dashboard/views.py": ["/manager/models.py"], "/notify_pushover/send.py": ["/notify_pushover/__init__.py"], "/manager/admin.py": ["/manager/models.py"]}
|
19,849
|
sjkingo/vilicus
|
refs/heads/master
|
/dashboard/views.py
|
from django.shortcuts import render
from manager.models import *
def dashboard(request, template='dashboard.html'):
agents = Agent.objects.all()
context = {'agents': agents}
return render(request, template, context)
|
{"/manager/api/resources.py": ["/manager/models.py"], "/manager/signals.py": ["/manager/models.py"], "/notify_pushover/signals.py": ["/manager/models.py"], "/vilicus/urls.py": ["/manager/api/resources.py"], "/dashboard/views.py": ["/manager/models.py"], "/notify_pushover/send.py": ["/notify_pushover/__init__.py"], "/manager/admin.py": ["/manager/models.py"]}
|
19,850
|
sjkingo/vilicus
|
refs/heads/master
|
/chartjs/templatetags/chartjs.py
|
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
def jsify_list(python_list):
assert type(python_list) == list
r = '['
for i, entry in enumerate(python_list):
if type(entry) == int:
e = str(entry)
else:
e = '"' + entry + '"'
if i+1 != len(python_list):
e += ', '
r += e
r += ']'
return mark_safe(r)
@register.inclusion_tag('chartjs/line_chart.html')
def line_chart(canvas_id, chart_config=None, width='400', height='400'):
if chart_config is None:
raise template.TemplateSyntaxError('chart_config argument must be provided and not None')
return {
'canvas_id': canvas_id,
'canvas_width': width,
'canvas_height': height,
'labels': jsify_list(chart_config['xaxis']),
'dataset': jsify_list(chart_config['dataset']),
}
|
{"/manager/api/resources.py": ["/manager/models.py"], "/manager/signals.py": ["/manager/models.py"], "/notify_pushover/signals.py": ["/manager/models.py"], "/vilicus/urls.py": ["/manager/api/resources.py"], "/dashboard/views.py": ["/manager/models.py"], "/notify_pushover/send.py": ["/notify_pushover/__init__.py"], "/manager/admin.py": ["/manager/models.py"]}
|
19,851
|
sjkingo/vilicus
|
refs/heads/master
|
/vilicus/local_settings.py
|
# Django local site-specific settings for vilicus project.
DEBUG = True
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': '', # leave blank
'PORT': '', # leave blank
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
# If DEBUG is True, localhost will automatically be added to this list.
ALLOWED_HOSTS = []
# Make this unique, and don't share it with anybody.
SECRET_KEY = '6x78*0ze892of8f+=mo8ce8cg9!e#r5_v45oz2=6$j_v)=0i0d'
|
{"/manager/api/resources.py": ["/manager/models.py"], "/manager/signals.py": ["/manager/models.py"], "/notify_pushover/signals.py": ["/manager/models.py"], "/vilicus/urls.py": ["/manager/api/resources.py"], "/dashboard/views.py": ["/manager/models.py"], "/notify_pushover/send.py": ["/notify_pushover/__init__.py"], "/manager/admin.py": ["/manager/models.py"]}
|
19,852
|
sjkingo/vilicus
|
refs/heads/master
|
/notify_pushover/send.py
|
import pushover
from . import TOKEN_KEY
pushover.init(TOKEN_KEY)
from models import PushoverUserTokens
# from https://pushover.net/api#priority
PRIORITY = {
'LOWEST': -2,
'LOW': -1,
'NORMAL': 0,
'HIGH': 1,
'EMERGENCY': 2,
}
def send_push_notification(title, msg, priority=PRIORITY['NORMAL']):
for t in PushoverUserTokens.objects.all():
client = pushover.Client(t.token)
client.send_message(msg, title='Vilicus alert: ' + title, priority=priority)
|
{"/manager/api/resources.py": ["/manager/models.py"], "/manager/signals.py": ["/manager/models.py"], "/notify_pushover/signals.py": ["/manager/models.py"], "/vilicus/urls.py": ["/manager/api/resources.py"], "/dashboard/views.py": ["/manager/models.py"], "/notify_pushover/send.py": ["/notify_pushover/__init__.py"], "/manager/admin.py": ["/manager/models.py"]}
|
19,853
|
sjkingo/vilicus
|
refs/heads/master
|
/manager/models.py
|
import datetime
from django.db import models
class Agent(models.Model):
hostname = models.CharField(max_length=100)
check_interval_ms = models.IntegerField(verbose_name='Check interval (ms)')
last_checkin = models.DateTimeField(blank=True, null=True)
version = models.CharField(max_length=5, blank=True, null=True)
guid = models.CharField(max_length=40, blank=True, null=True)
class Meta:
verbose_name = 'Agent'
verbose_name_plural = verbose_name + 's'
ordering = ('hostname',)
def __unicode__(self):
return self.hostname
@property
def windows_services_shown(self):
return self.windows_services.filter(hidden=False)
@property
def perflog_last_24hrs(self):
then = datetime.datetime.now() - datetime.timedelta(days=1)
return self.perflogs.filter(timestamp__gte=then)
@property
def perflog_id(self):
return 'perflog_%d' % self.id
@property
def perflog_dataset(self):
dataset = sorted([(entry.timestamp.strftime('%H:%M:%S'), entry.cpu_usage)
for entry in self.perflog_last_24hrs], key=lambda x: x[0])
labels = []
keys = [v[0] for v in dataset]
interval = int(len(keys) / PerformanceLogEntry.MAJOR_TICK_INTERVAL)
if interval == 0:
# not enough data
return None
for i, k in enumerate(keys):
if i % interval == 0:
labels.append(dataset[i][0][:-3])
else:
labels.append('')
return {
'xaxis': labels,
'dataset': [x[1] for x in dataset]
}
# From http://msdn.microsoft.com/en-us/library/windows/desktop/ee126211(v=vs.85).aspx
SERVICE_STATUS_STATES = (
('START_PENDING', 'Start pending'),
('RUNNING', 'Running'),
('STOP_PENDING', 'Stop pending'),
('STOPPED', 'Stopped'),
('PAUSE_PENDING', 'Pause pending'),
('PAUSED', 'Paused'),
('CONTINUE_PENDING', 'Continue pending'),
('NOT_INSTALLED', 'Not installed'),
('UNKNOWN', 'Unknown'),
)
SERVICE_STATUS_DICT = dict(SERVICE_STATUS_STATES)
class WindowsService(models.Model):
agent = models.ForeignKey('Agent', related_name='windows_services')
description = models.CharField(max_length=100)
service_name = models.CharField(max_length=100)
expected_status = models.CharField(max_length=16,
choices=SERVICE_STATUS_STATES, default='RUNNING')
hidden = models.BooleanField(default=False)
class Meta:
verbose_name = 'Windows Service'
verbose_name_plural = verbose_name + 's'
ordering = ('agent', 'description', 'service_name')
def __unicode__(self):
if self.description == self.service_name:
return self.description
else:
return '{self.description} ({self.service_name})'.format(self=self)
@property
def latest_log_entries(self):
return self.log.all()[:10]
@property
def latest_log(self):
try:
return self.latest_log_entries[0]
except IndexError:
return None
@property
def changed_since_last(self):
try:
if self.latest_log_entries[0].actual_status != \
self.latest_log_entries[1].actual_status:
return True
except IndexError:
return True
return False
class WindowsServiceLog(models.Model):
service = models.ForeignKey('WindowsService', related_name='log')
timestamp = models.DateTimeField()
expected_status = models.CharField(max_length=16)
actual_status = models.CharField(max_length=16)
action_taken = models.CharField(max_length=50)
comments = models.TextField(blank=True, null=True)
class Meta:
verbose_name = 'Windows Service log'
verbose_name_plural = verbose_name + 's'
ordering = ('service', '-timestamp')
def __unicode__(self):
return '{service} at {timestamp}'.format(service=str(self.service),
timestamp=self.timestamp)
@property
def status_pass(self):
return self.actual_status == self.expected_status
@property
def expected_status_h(self):
return SERVICE_STATUS_DICT[self.expected_status]
@property
def actual_status_h(self):
return SERVICE_STATUS_DICT[self.actual_status]
class PerformanceLogEntry(models.Model):
agent = models.ForeignKey('Agent', related_name='perflogs')
timestamp = models.DateTimeField()
cpu_usage = models.IntegerField()
# Interval for x-axis in charts. Note there must be this many entries before the graph will appear.
MAJOR_TICK_INTERVAL = 6
class Meta:
verbose_name = 'Performance log entry'
verbose_name_plural = 'Performance log entries'
ordering = ('agent', '-timestamp')
def __unicode__(self):
return '{agent} at {timestamp}'.format(agent=str(self.agent), timestamp=self.timestamp)
@property
def hourmins(self):
return self.timestamp.strftime('H:M')
|
{"/manager/api/resources.py": ["/manager/models.py"], "/manager/signals.py": ["/manager/models.py"], "/notify_pushover/signals.py": ["/manager/models.py"], "/vilicus/urls.py": ["/manager/api/resources.py"], "/dashboard/views.py": ["/manager/models.py"], "/notify_pushover/send.py": ["/notify_pushover/__init__.py"], "/manager/admin.py": ["/manager/models.py"]}
|
19,854
|
sjkingo/vilicus
|
refs/heads/master
|
/manager/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Agent',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('hostname', models.CharField(max_length=100)),
('check_interval_ms', models.IntegerField(verbose_name=b'Check interval (ms)')),
('last_checkin', models.DateTimeField(null=True, blank=True)),
('version', models.CharField(max_length=5, null=True, blank=True)),
('guid', models.CharField(max_length=40, null=True, blank=True)),
],
options={
'ordering': ('hostname',),
'verbose_name': 'Agent',
'verbose_name_plural': 'Agents',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='PerformanceLogEntry',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('timestamp', models.DateTimeField()),
('cpu_usage', models.IntegerField()),
('agent', models.ForeignKey(related_name='perflogs', to='manager.Agent')),
],
options={
'ordering': ('agent', '-timestamp'),
'verbose_name': 'Performance log entry',
'verbose_name_plural': 'Performance log entries',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='WindowsService',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('description', models.CharField(max_length=100)),
('service_name', models.CharField(max_length=100)),
('expected_status', models.CharField(default=b'RUNNING', max_length=16, choices=[(b'START_PENDING', b'Start pending'), (b'RUNNING', b'Running'), (b'STOP_PENDING', b'Stop pending'), (b'STOPPED', b'Stopped'), (b'PAUSE_PENDING', b'Pause pending'), (b'PAUSED', b'Paused'), (b'CONTINUE_PENDING', b'Continue pending'), (b'NOT_INSTALLED', b'Not installed'), (b'UNKNOWN', b'Unknown')])),
('hidden', models.BooleanField()),
('agent', models.ForeignKey(related_name='windows_services', to='manager.Agent')),
],
options={
'ordering': ('agent', 'description', 'service_name'),
'verbose_name': 'Windows Service',
'verbose_name_plural': 'Windows Services',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='WindowsServiceLog',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('timestamp', models.DateTimeField()),
('expected_status', models.CharField(max_length=16)),
('actual_status', models.CharField(max_length=16)),
('action_taken', models.CharField(max_length=50)),
('comments', models.TextField(null=True, blank=True)),
('service', models.ForeignKey(related_name='log', to='manager.WindowsService')),
],
options={
'ordering': ('service', '-timestamp'),
'verbose_name': 'Windows Service log',
'verbose_name_plural': 'Windows Service logs',
},
bases=(models.Model,),
),
]
|
{"/manager/api/resources.py": ["/manager/models.py"], "/manager/signals.py": ["/manager/models.py"], "/notify_pushover/signals.py": ["/manager/models.py"], "/vilicus/urls.py": ["/manager/api/resources.py"], "/dashboard/views.py": ["/manager/models.py"], "/notify_pushover/send.py": ["/notify_pushover/__init__.py"], "/manager/admin.py": ["/manager/models.py"]}
|
19,855
|
sjkingo/vilicus
|
refs/heads/master
|
/manager/admin.py
|
from django.contrib import admin
from manager.models import *
class AgentAdmin(admin.ModelAdmin):
readonly_fields = ('last_checkin', 'version', 'guid')
admin.site.register(Agent, AgentAdmin)
admin.site.register(WindowsService)
class WindowsServiceLogAdmin(admin.ModelAdmin):
readonly_fields = ('service', 'timestamp', 'actual_status', 'action_taken')
admin.site.register(WindowsServiceLog, WindowsServiceLogAdmin)
class PerformanceLogEntryAdmin(admin.ModelAdmin):
readonly_fields = ('agent', 'timestamp', 'cpu_usage')
admin.site.register(PerformanceLogEntry, PerformanceLogEntryAdmin)
|
{"/manager/api/resources.py": ["/manager/models.py"], "/manager/signals.py": ["/manager/models.py"], "/notify_pushover/signals.py": ["/manager/models.py"], "/vilicus/urls.py": ["/manager/api/resources.py"], "/dashboard/views.py": ["/manager/models.py"], "/notify_pushover/send.py": ["/notify_pushover/__init__.py"], "/manager/admin.py": ["/manager/models.py"]}
|
19,878
|
johnsonkee/AI_hw2
|
refs/heads/master
|
/test.py
|
from mydataset import _test_data
from mxnet.gluon.data.vision import transforms
from mxnet.gluon.data import DataLoader
from myNet import resnet18
from mxnet import cpu, gpu
from mxnet import ndarray as nd
from mxnet.test_utils import list_gpus
import pandas as pd
BATCH_SIZE = 1
MODEL_PATH = 'resnet18.params'
if list_gpus():
CTX = gpu()
else:
CTX = cpu()
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.4914, 0.4822, 0.4465],
[0.2023, 0.1994, 0.2010])
])
test_dataloader = DataLoader(_test_data.transform_first(transform_test),
batch_size=BATCH_SIZE,
shuffle=True,
last_batch='keep')
net = resnet18(10)
net.load_parameters(MODEL_PATH,ctx=CTX)
# net.initialize(ctx=CTX)
confusion_matrix = nd.zeros((10,10))
print("====>make confusion matrix")
for data,label in test_dataloader:
label_hat = net(data.as_in_context(CTX))
label_number = label.astype('int8').copyto(cpu()).asscalar()
hat_number = label_hat.argmax(axis=1).astype('int8').copyto(cpu())
hat_number = hat_number.asscalar()
confusion_matrix[label_number-1][hat_number-1] += 1
confusion_matrix = confusion_matrix.asnumpy()
data = pd.DataFrame(confusion_matrix,dtype='int32')
data.to_csv("confusion.csv",index=False, header=False)
|
{"/test.py": ["/mydataset.py"], "/run.py": ["/mydataset.py"]}
|
19,879
|
johnsonkee/AI_hw2
|
refs/heads/master
|
/mydataset.py
|
# coding=utf-8
from mxnet.gluon.data.vision import CIFAR10
import mxnet
# 目前读取的数据集是int8类型的,然而网络的输入要求是float类型的,
# 所以要进行转化,具体转化在
_train_data = CIFAR10(root="./dataset/cifar10", train=True)
_test_data = CIFAR10(root="./dataset/cifar10", train=False)
|
{"/test.py": ["/mydataset.py"], "/run.py": ["/mydataset.py"]}
|
19,880
|
johnsonkee/AI_hw2
|
refs/heads/master
|
/run.py
|
# coding=utf-8
from mydataset import _train_data, _test_data
from mxnet.gluon.data import DataLoader
from mxnet.gluon.data.vision import transforms
from mxnet.gluon import Trainer
from myNet import resnet18
from mxnet import autograd
from mxnet.gluon import loss
from mxnet import init
from mxnet import cpu
from mxnet import gpu
import time
import gluonbook as gb
from argparse import ArgumentParser
def parse_args():
parser = ArgumentParser(description="Train a resnet18 for"
" cifar10 dataset")
parser.add_argument('--data', type=str, default='./dataset/cifar10',
help='path to test and training data files')
parser.add_argument('-e', '--epochs', type=int, default=20,
help='number of epochs for training')
parser.add_argument('-b', '--batch_size', type=int, default=128,
help='number of examples for each iteration')
parser.add_argument('-lr', '--learning_rate', type=float, default=0.1,
help='learning rate for optimizer')
parser.add_argument('-lp', '--learning_period', type=float, default=80,
help='after learning_period, lr = lr * lr_decay')
parser.add_argument('-lc','--learning_decay',type=float, default=0.1,
help='after learning_period, lr = lr * lr_decay')
parser.add_argument('-wd',type=float, default=5e-4,
help='weight decay, used in SGD optimization')
parser.add_argument('--gpu', type=bool, default=False,
help='use available GPUs')
parser.add_argument('--use_model_path', type=str, default='resnet18.params',
help='the path of the pre-trained model')
parser.add_argument('--use_model', type=bool, default=False,
help='whether use a pre-trained model')
parser.add_argument('--save_model_path', type=str, default='resnet18.params',
help='where to save the trained model')
parser.add_argument('--save_model', type=bool, default=True,
help='whether save the model')
return parser.parse_args()
def train(net,
train_dataloader,
test_dataloader,
batch_size,
nums_epochs,
lr,
ctx,
wd,
lr_period,
lr_decay):
trainer = Trainer(net.collect_params(), 'sgd',
{'learning_rate': lr, 'momentum':0.9, 'wd': wd})
myloss = loss.SoftmaxCrossEntropyLoss()
for epoch in range(nums_epochs):
train_loss, train_acc, start = 0.0, 0.0, time.time()
if epoch > 0 and epoch % lr_period == 0:
trainer.set_learning_rate(trainer.learning_rate * lr_decay)
for X, y in train_dataloader:
# 原先的数据都是int8类型的,现在将其转化为float32
# 以便输入到网络里面
y = y.astype('float32').as_in_context(ctx)
X = X.astype('float32').as_in_context(ctx)
with autograd.record():
y_hat = net(X)
l = myloss(y_hat,y)
l.backward()
trainer.step(batch_size)
train_loss += l.mean().asscalar()
train_acc = evaluate(net,train_dataloader,ctx)
time_s = "time %.2f sec" % (time.time() - start)
test_acc = evaluate(net,test_dataloader,ctx)
epoch_s = ("epoch %d, loss %f, train_acc %f, test_acc %f, "
% (epoch+1,
train_loss/len(train_dataloader),
train_acc,
test_acc))
print(epoch_s + time_s + ', lr' + str(trainer.learning_rate))
def evaluate(net, test_dataloader, ctx):
return gb.evaluate_accuracy(test_dataloader, net, ctx)
def main():
args = parse_args()
BATCH_SIZE = args.batch_size
NUMS_EPOCHS = args.epochs
LR = args.learning_rate
USE_CUDA = args.gpu
WD = args.wd
LR_PERIOD = args.learning_period
LR_DECAY = args.learning_decay
MODEL_PATH = args.use_model_path
USE_MODEL = args.use_model
SAVE_MODEL = args.save_model
if USE_CUDA:
ctx = gpu()
else:
ctx = cpu()
transform_train = transforms.Compose([
transforms.Resize(40),
transforms.RandomResizedCrop(32,scale=(0.64,1.0),
ratio=(1.0, 1.0)),
transforms.RandomFlipLeftRight(),
transforms.ToTensor(),
transforms.Normalize([0.4914, 0.4822, 0.4465],
[0.2023, 0.1994, 0.2010])
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.4914, 0.4822, 0.4465],
[0.2023, 0.1994, 0.2010])
])
train_dataloader = DataLoader(_train_data.transform_first(transform_train),
batch_size=BATCH_SIZE,
shuffle=True,
last_batch='keep')
test_dataloader = DataLoader(_test_data.transform_first(transform_test),
batch_size=BATCH_SIZE,
shuffle=True,
last_batch='keep')
net = resnet18(num_classes=10)
net.hybridize()
if USE_MODEL:
net.load_parameters(MODEL_PATH,ctx=ctx)
else:
net.initialize(ctx=ctx, init=init.Xavier())
print("====>train and test")
train(net, train_dataloader, test_dataloader,
BATCH_SIZE, NUMS_EPOCHS, LR, ctx, WD,LR_PERIOD, LR_DECAY)
if SAVE_MODEL:
net.save_parameters(MODEL_PATH)
if __name__ == "__main__":
main()
|
{"/test.py": ["/mydataset.py"], "/run.py": ["/mydataset.py"]}
|
19,895
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/migrations/0009_auto_20181129_1132.py
|
# Generated by Django 2.1.2 on 2018-11-29 09:32
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('structure', '0008_auto_20181128_1648'),
]
operations = [
migrations.AddField(
model_name='country',
name='account_id',
field=models.OneToOneField(default=1, on_delete=django.db.models.deletion.CASCADE, to='structure.Customer_Account'),
),
migrations.AlterField(
model_name='customer_account',
name='customer',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,896
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/migrations/0005_customer_account_customer.py
|
# Generated by Django 2.1.2 on 2018-11-22 14:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('customer', '0001_initial'),
('structure', '0004_customer_account'),
]
operations = [
migrations.AddField(
model_name='customer_account',
name='customer',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='customer.Customer'),
preserve_default=False,
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,897
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/migrations/0004_customer_account.py
|
# Generated by Django 2.1.2 on 2018-11-21 10:14
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('structure', '0003_auto_20181121_1210'),
]
operations = [
migrations.CreateModel(
name='Customer_Account',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('world', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='structure.World_version')),
],
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,898
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/models.py
|
from django.db import models
#from customer.models import Customer
from django.contrib.auth.forms import User
# Create your models here.
class World_version(models.Model):
STATUS_OF_WORLD = (
('enable', '_enable'),
('disable', '_disable'),
('comingsoon', '_comingsoon'),
)
name = models.CharField(max_length=50)
status_of_world = models.CharField(max_length=10, choices=STATUS_OF_WORLD)
def __str__(self):
return 'Название - {0}'.format(self.name)
class Country(models.Model):
country_name = models.CharField(max_length=50)
world = models.ForeignKey(World_version, on_delete=models.CASCADE)
customer = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
def __str__(self):
return 'Название - {0}'.format(self.country_name)
class Clan(models.Model):
clan_name = models.CharField(max_length=50)
country = models.OneToOneField(Country, on_delete=models.CASCADE)
def __str__(self):
return 'Название - {0}'.format(self.clan_name)
class Customer_Account(models.Model):
account_name = models.CharField(max_length=50)
world = models.ForeignKey(World_version, on_delete=models.CASCADE)
customer = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
clan = models.ForeignKey(Clan, on_delete=models.SET_NULL,null=True, blank=True)
def __str__(self):
return 'Название - {0}, Статус {1}'.format(self.account_name, self.world.name)
class User_settings(models.Model):
customer = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
selected_world = models.ForeignKey(World_version, on_delete=models.CASCADE, default=4)
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,899
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/migrations/0013_auto_20181129_1639.py
|
# Generated by Django 2.1.2 on 2018-11-29 14:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('structure', '0012_auto_20181129_1637'),
]
operations = [
migrations.AlterField(
model_name='customer_account',
name='clan',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='structure.Clan'),
),
migrations.AlterField(
model_name='customer_account',
name='customer',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='customer_account',
name='world',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='structure.World_version'),
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,900
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/migrations/0011_auto_20181129_1415.py
|
# Generated by Django 2.1.2 on 2018-11-29 12:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('structure', '0010_auto_20181129_1218'),
]
operations = [
migrations.AlterField(
model_name='customer_account',
name='clan',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='structure.Clan'),
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,901
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/migrations/0010_auto_20181129_1218.py
|
# Generated by Django 2.1.2 on 2018-11-29 10:18
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('structure', '0009_auto_20181129_1132'),
]
operations = [
migrations.RemoveField(
model_name='country',
name='account_id',
),
migrations.AddField(
model_name='customer_account',
name='clan',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='structure.Clan'),
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,902
|
sergmalinov1/command_centr
|
refs/heads/master
|
/global_maps/apps.py
|
from django.apps import AppConfig
class GlobalmapsConfig(AppConfig):
name = 'global_maps'
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,903
|
sergmalinov1/command_centr
|
refs/heads/master
|
/customer/views.py
|
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import login, logout
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.http import HttpResponse, response
from customer.forms import RegistrationForm
from structure.models import Customer_Account, Country, Clan, World_version, User_settings
from structure.forms import CreateAccountForm, CreateCountryForm, CreateClanForm
from django.core.exceptions import ObjectDoesNotExist
def index(request):
# return HttpResponse("<h3>Hello world</h3>")
return redirect ('customer/login')
@csrf_exempt
def signup_view(request):
# Number of visits to this view, as counted in the session variable.
num_visits = request.session.get('num_visits', 0)
request.session['num_visits'] = num_visits + 1
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = form.save()
#log user here
login(request, user)
#устанавливаем мир по умолчанию = 1
world = World_version.objects.all()
settings = User_settings(customer=request.user, selected_world=world[0])
settings.save()
return render(request, 'customer/successful.html' )
else:
form = RegistrationForm()
return render(request, 'customer/signup.html', {'form': form, 'num_visits':num_visits}, )
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
user = form.get_user()
login(request, user)
if 'next' in request.POST:
return redirect(request.POST.get('next'))
else:
return render(request, 'customer/successful.html')
else:
form = AuthenticationForm()
return render(request, 'customer/login.html', {'form': form}, )
def logout_view(request):
if request.method == 'POST':
logout(request)
return render(request, 'customer/successful.html')
@login_required(login_url="/customer/login/")
def profile_view(request):
args = {}
args['accounts'] = list_of_accounts(request)
args['countries'] = list_of_countries(request)
args['world_list'] = World_version.objects.all()
args['selected_world'] = request.session.get('selected_world_num', 0)
return render(request, 'profile/profile.html', args)
def select_world_view(request):
if request.POST:
#user = User.objects.get(id=request.user.id)
selected_world_name = request.POST.get('world_number')
world = World_version.objects.get(name = selected_world_name)
try:
settings = User_settings.objects.get(customer=request.user.id)
settings.selected_world = world
settings.save()
except ObjectDoesNotExist:
settings = User_settings(customer = request.user, selected_world = world)
settings.save()
request.session['selected_world_num'] = world.id
else:
request.session['selected_world_num'] = 'aaaa'
return redirect('profile')
def password_reset_view(request):
return render(request, 'customer/password_reset.html')
''' CLASS '''
class MyAccounts:
account_id = 1
country = ""
clan = ""
account_name = ""
world_version = ""
def __init__(self, account_id, account_name, world_version, clan="-", country="-"):
self.account_id = account_id
self.account_name = account_name
self.world_version = world_version
self.country = country
self.clan = clan
class MyCountry:
country_id = 1
country_name = ""
num_of_accounts = 0
def __init__(self, country_name, num_of_accounts, country_id):
self.country_name = country_name
self.num_of_accounts = num_of_accounts
self.country_id = country_id
'''DEF '''
def list_of_accounts(request):
accounts = []
settings = User_settings.objects.get(customer=request.user)
list_of_accounts = Customer_Account.objects.filter(customer=request.user.id).filter(world = settings.selected_world.id)
# list_of_free_accounts
#list_of_accounts = Customer_Account.objects.filter(customer=request.user.id).filter(clan_id=None)
for item in list_of_accounts:
account_id = item.pk
account_name = item.account_name
world_version = item.world.name
clan_name = "-"
country_name = "-"
if item.clan is not None:
clan = Clan.objects.get(id__contains=item.clan.pk)
clan_name = clan.clan_name
country = Country.objects.get(id__contains=clan.country_id)
country_name = country.country_name
acc = MyAccounts(account_id, account_name, world_version, clan_name, country_name)
accounts.append(acc)
return accounts
def list_of_countries(request):
countries = []
countries_list = Country.objects.filter(customer_id=request.user.id)
for item in countries_list:
num_of_acc = 0
clan_list = Clan.objects.filter(country_id=item.id)
for clan_item in clan_list:
acc = Customer_Account.objects.filter(clan_id=clan_item.id)
num_of_acc = num_of_acc + acc.count()
my_country = MyCountry(item.country_name, num_of_acc, item.id)
countries.append(my_country)
return countries
'''ACCOUNT '''
@csrf_exempt
def accounts_view(request):
args = {}
args['accounts'] = list_of_accounts(request)
args['countries'] = list_of_countries(request)
args['account_form'] = CreateAccountForm()
args['country_form'] = CreateCountryForm()
return render(request, 'account/accounts.html', args)
def account_detail_view(request, account_id=1):
args = {}
args['account'] = Customer_Account.objects.get(id = account_id)
args['accounts'] = list_of_accounts(request)
args['countries'] = list_of_countries(request)
return render(request, 'account/account_detail.html', args)
@csrf_exempt
def create_account_view(request):
if request.POST:
form = CreateAccountForm(request.POST)
if form.is_valid():
account = form.save(commit=False)
user = User.objects.get(id__contains = request.user.id)
account.customer_id = user.id
form.save()
return redirect('/customer/account/')
return redirect('/')
'''COUNTRY '''
def country_view(request):
args = {}
args['accounts'] = list_of_accounts(request)
args['countries'] = list_of_countries(request)
args['country_form'] = CreateCountryForm()
args['clan_form'] = CreateClanForm()
return render(request, 'country/country.html', args)
def create_country(request):
if request.POST:
form = CreateCountryForm(request.POST)
if form.is_valid():
#Поиск связанного аккаунта
account_number = request.POST.get('account_number')
account = Customer_Account.objects.get(id=account_number)
# Создание страны
new_country = form.save(commit=False)
user = User.objects.get(id=request.user.id)
new_country.customer_id = user.id
new_country.world = account.world
form.save()
#Создание клана
clan_name = request.POST.get('clan_name')
new_clan = Clan(clan_name=clan_name, country=new_country )
new_clan.save();
#Присвоение клана для пользователя
account.clan = new_clan
account.save()
return redirect('/customer/account/')
return redirect('/')
return render(request, 'profile/templates/country/country.html')
def country_detail_view(request, country_id=1):
args = {}
args['country'] = Country.objects.get(id = country_id)
args['accounts'] = list_of_accounts(request)
args['countries'] = list_of_countries(request)
return render(request, 'country/country_detail.html', args)
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,904
|
sergmalinov1/command_centr
|
refs/heads/master
|
/global_maps/admin.py
|
from django.contrib import admin
from .models import Landscape, Cell
admin.site.register(Landscape)
admin.site.register(Cell)
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,905
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/forms.py
|
from django import forms
from structure.models import Customer_Account, Country, Clan
class CreateAccountForm(forms.ModelForm):
class Meta:
model = Customer_Account
fields = ['account_name', 'world']
class CreateCountryForm(forms.ModelForm):
class Meta:
model = Country
fields = ['country_name']
class CreateClanForm(forms.ModelForm):
class Meta:
model = Clan
fields = ['clan_name', 'country']
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,906
|
sergmalinov1/command_centr
|
refs/heads/master
|
/customer/migrations/0002_delete_customer.py
|
# Generated by Django 2.1.2 on 2018-11-25 08:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('structure', '0006_auto_20181125_1044'),
('customer', '0001_initial'),
]
operations = [
migrations.DeleteModel(
name='Customer',
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,907
|
sergmalinov1/command_centr
|
refs/heads/master
|
/global_maps/urls.py
|
from django.conf.urls import url, include
from django.urls import path
from . import views
urlpatterns = [
url(r'^$', views.global_maps_view, name='global'),
# url(r'^', views.index, name='index'),
# url(r'^1/', views.kakogo, name='kakogo'),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,908
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/migrations/0001_initial.py
|
# Generated by Django 2.1.2 on 2018-11-21 10:05
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='World_version',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('status_of_world', models.CharField(choices=[('en', 'enable'), ('dis', 'disable'), ('c', 'comingsoon')], max_length=1)),
],
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,909
|
sergmalinov1/command_centr
|
refs/heads/master
|
/global_maps/views.py
|
from django.shortcuts import render
from django.shortcuts import render_to_response
from global_maps.models import Landscape, Cell
from django.contrib.auth.decorators import login_required
def index(request):
return render(request, 'globalmaps/maps.html')
@login_required(login_url="/account/login/")
def global_maps_view(request):
list_of_cells = Cell.objects.all()
list_of_hex = [];
for cell in list_of_cells:
# my_landscape = Landscape.objects.filter(id__contains = cell.landscape_id)
my_landscape = Landscape.objects.get(id__contains=cell.landscape_id)
hex = Hex(cell.coord_x, cell.coord_y, my_landscape.img)
list_of_hex.append(hex)
return render_to_response('globalMaps/maps.html', {'list': list_of_hex})
class Hex:
img = "desert_hill.png";
coord_x = 1;
coord_y = 0;
hex_width = 105;
hex_height = 123;
#_class = "hex " + (_y % 2 == 0?"even":"odd");
#_html = '<span>' + _x + "-" + _y + '</span>';
def __init__(self, x, y, img="desrt_hill.png"):
self.coord_x = x
self.coord_y = y
self.img = img
def top(self):
return self.hex_height * 0.75 * self.coord_y
def left(self):
if(self.coord_y %2 ==0):
return self.hex_width * self.coord_x
else:
return self.hex_width * self.coord_x + self.hex_width*0.5
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,910
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/migrations/0003_auto_20181121_1210.py
|
# Generated by Django 2.1.2 on 2018-11-21 10:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('structure', '0002_auto_20181121_1208'),
]
operations = [
migrations.AlterField(
model_name='world_version',
name='status_of_world',
field=models.CharField(choices=[('enable', '_enable'), ('disable', '_disable'), ('comingsoon', '_comingsoon')], max_length=10),
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,911
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/migrations/0002_auto_20181121_1208.py
|
# Generated by Django 2.1.2 on 2018-11-21 10:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('structure', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='world_version',
name='status_of_world',
field=models.CharField(choices=[('e', 'enable'), ('d', 'disable'), ('c', 'comingsoon')], max_length=1),
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,912
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/migrations/0017_auto_20181207_1416.py
|
# Generated by Django 2.1.2 on 2018-12-07 12:16
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('structure', '0016_user_settings'),
]
operations = [
migrations.RemoveField(
model_name='user_settings',
name='world_by_default',
),
migrations.AddField(
model_name='user_settings',
name='customer',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='user_settings',
name='selected_world',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='structure.World_version'),
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,913
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/migrations/0018_auto_20181211_1218.py
|
# Generated by Django 2.1.2 on 2018-12-11 10:18
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('structure', '0017_auto_20181207_1416'),
]
operations = [
migrations.AlterField(
model_name='user_settings',
name='selected_world',
field=models.ForeignKey(default=4, on_delete=django.db.models.deletion.CASCADE, to='structure.World_version'),
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,914
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/admin.py
|
from django.contrib import admin
from .models import World_version, Customer_Account, Country, Clan
# Register your models here.
admin.site.register(World_version)
admin.site.register(Customer_Account)
admin.site.register(Country)
admin.site.register(Clan)
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,915
|
sergmalinov1/command_centr
|
refs/heads/master
|
/customer/models.py
|
from django.db import models
'''
class Customer(models.Model):
customer_name = models.CharField(max_length=100)
password = models.CharField(max_length=50)
def __str__(self):
return 'Имя пользователя - {0}'.format(self.customer_name)
'''
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,916
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/migrations/0008_auto_20181128_1648.py
|
# Generated by Django 2.1.2 on 2018-11-28 14:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('structure', '0007_auto_20181125_1208'),
]
operations = [
migrations.RenameField(
model_name='clan',
old_name='name',
new_name='clan_name',
),
migrations.RenameField(
model_name='country',
old_name='name',
new_name='country_name',
),
migrations.RenameField(
model_name='customer_account',
old_name='name',
new_name='account_name',
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,917
|
sergmalinov1/command_centr
|
refs/heads/master
|
/customer/apps.py
|
from django.apps import AppConfig
class CustomerAuthConfig(AppConfig):
name = 'customer'
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,918
|
sergmalinov1/command_centr
|
refs/heads/master
|
/customer/urls.py
|
from django.conf.urls import url, include
from customer import views
from django.contrib.auth.views import LoginView
from django.urls import path
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^signup/$', views.signup_view, name='signup'),
url(r'^login/$', LoginView.as_view(template_name='customer/login.html'), name='login'),
# url(r'^login/$', views.login_view, name='login'),
url(r'^logout/$', views.logout_view, name='logout'),
url(r'^profile/$', views.profile_view, name='profile'),
url(r'^select-world/$', views.select_world_view, name='select_world'),
url(r'^password_reset/$', views.password_reset_view, name='password_reset'),
url(r'^account/$', views.accounts_view, name='my_account'),
url(r'^account/get/(?P<account_id>\d+)$', views.account_detail_view, name='account_detail'),
url(r'^account/create/$', views.create_account_view, name='create_account'),
url(r'^country/$', views.country_view, name='my_country'),
url(r'^country/get/(?P<country_id>\d+)$', views.country_detail_view, name='country_detail'),
url(r'^country/create/$', views.create_country, name='crate_country'),
# url(r'^login/verifications/$', views.loginVerifications, name='index'),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,919
|
sergmalinov1/command_centr
|
refs/heads/master
|
/global_maps/models.py
|
from django.db import models
class Landscape(models.Model):
name = models.CharField(max_length=50)
img = models.CharField(max_length=50)
def __str__(self):
return 'Название - {0}, Картинка {1} '.format(self.name, self.img)
class Cell(models.Model):
name = models.CharField(max_length=50)
coord_x = models.IntegerField()
coord_y = models.IntegerField()
landscape = models.ForeignKey(Landscape, on_delete=models.CASCADE)
def __str__(self):
return 'Название:{0} Хоординаты Х\Y - {1} \ {2} '.format(self.name, self.coord_x, self.coord_y)
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,920
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/migrations/0012_auto_20181129_1637.py
|
# Generated by Django 2.1.2 on 2018-11-29 14:37
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('structure', '0011_auto_20181129_1415'),
]
operations = [
migrations.AlterField(
model_name='customer_account',
name='clan',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='structure.Clan'),
),
migrations.AlterField(
model_name='customer_account',
name='customer',
field=models.OneToOneField(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='customer_account',
name='world',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='structure.World_version'),
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,921
|
sergmalinov1/command_centr
|
refs/heads/master
|
/structure/migrations/0016_user_settings.py
|
# Generated by Django 2.1.2 on 2018-12-07 12:12
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('structure', '0015_country_customer'),
]
operations = [
migrations.CreateModel(
name='User_settings',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('world_by_default', models.OneToOneField(default=1, on_delete=django.db.models.deletion.CASCADE, to='structure.World_version')),
],
),
]
|
{"/customer/views.py": ["/structure/models.py", "/structure/forms.py"], "/global_maps/admin.py": ["/global_maps/models.py"], "/structure/forms.py": ["/structure/models.py"], "/global_maps/views.py": ["/global_maps/models.py"], "/structure/admin.py": ["/structure/models.py"]}
|
19,922
|
1594051054/final_Y12
|
refs/heads/master
|
/Restaurant/order_food/views.py
|
from django.shortcuts import render
from . models import Comment
def home_page(request):
if request.method == 'POST':
food_name = request.POST.get('food_name')
address = request.POST.get("address")
order_obj = Comment.objects.create(
food = food_name,
address = address,
)
return render(request, 'order_food/home_page.html', {'foods': order_obj})
return render(request, 'order_food/home_page.html')
|
{"/Restaurant/order_food/views.py": ["/Restaurant/order_food/models.py"]}
|
19,923
|
1594051054/final_Y12
|
refs/heads/master
|
/Restaurant/order_food/models.py
|
from django.db import models
# Create your models here.
class Comment(models.Model):
food = models.CharField(max_length=180, null=True, blank=True)
address = models.CharField(max_length=180, null=True, blank=True)
|
{"/Restaurant/order_food/views.py": ["/Restaurant/order_food/models.py"]}
|
19,940
|
bogobogo/bash-game
|
refs/heads/master
|
/tests/main_test.py
|
import unittest
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from src.main import addOutput, fill_line, addUserInput, prompt, InvalidArgument
class Tests(unittest.TestCase):
ls_output = 'ideas.py\nmain.py\ntest.py\nutils.py\n'
ps_putput = ' PID TTY TIME CMD\n 1366 ttys000 0:00.21 /bin/zsh -l\n 1743 ttys000 0:00.03 python\n 534 ttys001 0:00.02 python\n81324 ttys001 0:00.03 /Applications/iTerm.app/Contents/MacOS/iTerm2 --server login -fp eladbo\n81326 ttys001 0:00.54 -zsh\n 1756 ttys002 0:00.44 -zsh\n 4082 ttys002 0:00.03 /usr/bin/python ./main.py\n'
def test_fill_line(self):
l = 'asdf'
c = '.'
in_width = 80
expected = 'asdf' + ('.' * (in_width-len(l)))
result = fill_line(l, c, in_width=in_width)
self.assertEqual(expected, result)
def test_fill_line_invalid_char(self):
l = 'asdf'
c = '..'
in_width = 80
expected = 'asdf' + ('.' * (in_width-len(l)))
self.assertRaises(
InvalidArgument,
lambda: fill_line(l, c, in_width=in_width)
)
def test_addOutput_1_line(self):
output = 'ideas.py\n'
totalout_lines = []
result = [
fill_line('ideas.py','.'),
]
addOutput(output, totalout_lines)
self.assertEqual(totalout_lines, result)
def test_addOutput_ls(self):
totalout_lines = []
result = [
fill_line('ideas.py','.'),
fill_line('main.py','.'),
fill_line('test.py','.'),
fill_line('utils.py','.'),
]
addOutput(self.ls_output, totalout_lines, in_width=80)
self.assertEqual(totalout_lines, result)
def test_addOutput_over_IN_WIDTH(self):
totalout_lines = []
result = [
fill_line('ideas.py','.'),
fill_line('main.py','.'),
fill_line('test.py','.'),
fill_line('utils.py','.'),
]
addOutput(self.ls_output, totalout_lines)
self.assertEqual(totalout_lines, result)
def test_add_user_input_fill(self):
cmd = "top -a"
totalout_lines = [
prompt + "ls",
fill_line('main.py',c = '.'),
prompt
]
addUserInput(cmd, totalout_lines)
expected = [
prompt + "ls",
fill_line('main.py',c = '.'),
fill_line(prompt + cmd, c = '.', compensation=10)
]
self.assertEqual(totalout_lines, expected)
if __name__ == '__main__':
unittest.main()
|
{"/tests/main_test.py": ["/src/main.py"], "/tests/renderer_test.py": ["/src/consts.py", "/src/renderer.py", "/src/messages.py"], "/tests/messages_test.py": ["/src/messages.py"]}
|
19,941
|
bogobogo/bash-game
|
refs/heads/master
|
/src/utils.py
|
def removeNewLine(s):
if s.endswith("\n"):
return s[:-1]
return s
|
{"/tests/main_test.py": ["/src/main.py"], "/tests/renderer_test.py": ["/src/consts.py", "/src/renderer.py", "/src/messages.py"], "/tests/messages_test.py": ["/src/messages.py"]}
|
19,942
|
bogobogo/bash-game
|
refs/heads/master
|
/src/game.py
|
levels = {"1" : 100,
"2": 400,
"3": 1000}
def createMission(desiredOutput, desiredInput, messages, xp, errorMessages):
pass
mission1 = createMission()
mission2 = createMission()
missions = [mission1, mission2, mission3]
game(missions)
|
{"/tests/main_test.py": ["/src/main.py"], "/tests/renderer_test.py": ["/src/consts.py", "/src/renderer.py", "/src/messages.py"], "/tests/messages_test.py": ["/src/messages.py"]}
|
19,943
|
bogobogo/bash-game
|
refs/heads/master
|
/src/main.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import subprocess
import os
import fileinput
import time
import renderer
from consts import IN_WIDTH, TESTING
from utils import removeNewLine
from messages import level1_firstMessage, progressBar, totalxp
from strings import first_message
getUserInput = lambda: sys.stdin.readline()
class InvalidArgument(Exception):
pass
prompt = '\033[95m' + "level 1 Hi game >" + '\033[94m'
def addPrompt(totalout_lines, prompt):
totalout_lines.append('\033[95m' + "level 1 Hi game >" + '\033[94m')
def addUserInput(cmd, totalout_lines):
totalout_lines[-1] = fill_line(totalout_lines[-1] + cmd , c=" ", compensation = 10)
def fill_line(l, c=' ', in_width=IN_WIDTH, compensation = 0):
if len(c) != 1:
raise InvalidArgument
return l + c * ((in_width-len(l)) + compensation)
def addOutput(output, totalout_lines, in_width=IN_WIDTH):
lines = output.split("\n")
filled_lines = []
for l in lines:
if len(l) < in_width and l != '':
filled_lines.append(fill_line(l, c = " "))
totalout_lines += filled_lines
def turn(totalout_lines, n=0):
addPrompt(totalout_lines, prompt)
renderer.write(prompt)
userInput = getUserInput()
command = removeNewLine(userInput)
addUserInput(command, totalout_lines)
try:
process = subprocess.Popen(command, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = process.communicate()
subprocess.call("tput civis", shell=True)
totalxp.clean(totalout_lines)
progressBar.clean(totalout_lines)
level1_firstMessage.clean(totalout_lines)
if out:
addOutput(out, totalout_lines)
renderer.write(out)
elif err:
addOutput(err, totalout_lines)
renderer.write(err)
totalxp.overlay(totalout_lines)
progressBar.overlay(totalout_lines)
level1_firstMessage.overlay(totalout_lines)
subprocess.call("tput cnorm", shell=True)
turn(totalout_lines, n=n+1)
except Exception as e:
print 'Exception: %s' % e
if __name__ == '__main__':
renderer.cleanScreen()
# subprocess.call("tput cup 0 1", shell=True)
renderer.setTerminalSize(150, 150)
totalxp.overlay([])
progressBar.overlay([])
level1_firstMessage.overlay([])
turn([])
## if command == 'cd ..':
# os.chdir('..')
|
{"/tests/main_test.py": ["/src/main.py"], "/tests/renderer_test.py": ["/src/consts.py", "/src/renderer.py", "/src/messages.py"], "/tests/messages_test.py": ["/src/messages.py"]}
|
19,944
|
bogobogo/bash-game
|
refs/heads/master
|
/tests/renderer_test.py
|
import unittest
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from src.consts import IN_WIDTH
from src.renderer import getRelevantHistoryLines, combineHistoryAndMessage
from src.messages import Message
from test_strings import first_message_no_tabs
class RendererTest(unittest.TestCase):
def test_get_corrasponding_lines_with_long_line_history(self):
line_history = ["hello" for _ in xrange(1, 100)]
message_lines = first_message_no_tabs.split("\n")
screen_height = 50
msg_len = len(message_lines)
start_position_from_top = 11
result = getRelevantHistoryLines(line_history, screen_height, msg_len, start_position_from_top)
self.assertEqual(len(result), len(message_lines) - 1)
self.assertEqual(result, ["hello" for _ in xrange(0, len(message_lines) - 1)])
def test_combine_message_and_history_that_covers_the_screen(self):
line_history = [str(i) + (" " * (IN_WIDTH - len(str(i)))) for i in xrange(1, 100)]
msg = Message("yo\n"*29 + "yo", "first", (50, 11))
screen_height = 50
result = combineHistoryAndMessage(msg.message, 11, line_history, screen_height)
expectedResult = "yo\n" + ((" " * IN_WIDTH) + "yo\n") * 28 + (" " * IN_WIDTH) + "yo"
self.assertEqual(result, expectedResult)
def test_combine_message_and_history_that_intersects(self):
line_history = ["hello" + (IN_WIDTH - len("hello")) * " " for _ in xrange(0, 15)]
msg = Message("yo\n"*29 + "yo", "first", (50, 11))
screen_height = 50
result = combineHistoryAndMessage(msg.message, 11, line_history, screen_height)
expectedResult = "yo\n" + ("hello" + " " * (IN_WIDTH - len("hello")) + "yo\n") * 4 + (" " * IN_WIDTH + "yo\n") * 24 + " "*IN_WIDTH + "yo"
self.assertEqual(result, expectedResult)
def test_combine_message_and_history_that_doesnt_intersect(self):
line_history = ["hello"+ " " * 3 for _ in xrange(1, 9)]
msg = Message("yo\n"*29 + "yo", "first", (50, 11))
screen_height = 50
result = combineHistoryAndMessage(msg.message, 11, line_history, screen_height)
expectedResult = "yo\n" + 28* (IN_WIDTH*" " + "yo\n") + " "*IN_WIDTH + "yo"
self.assertEqual(result, expectedResult)
def test_combine_delete_message_and_history(self):
pass
if __name__ == '__main__':
unittest.main()
|
{"/tests/main_test.py": ["/src/main.py"], "/tests/renderer_test.py": ["/src/consts.py", "/src/renderer.py", "/src/messages.py"], "/tests/messages_test.py": ["/src/messages.py"]}
|
19,945
|
bogobogo/bash-game
|
refs/heads/master
|
/src/renderer.py
|
import sys
import subprocess
import itertools
from consts import IN_WIDTH
fillIn = " " * IN_WIDTH
def setTerminalSize(x, y):
sys.stdout.write("\x1b[8;{rows};{cols}t".format(rows=y, cols=x))
def getTerminalSize():
x = subprocess.check_output("tput cols", shell=True)
y = subprocess.check_output("tput lines", shell=True)
return (int(x), int(y))
def cleanScreen():
subprocess.call("clear", shell=True)
subprocess.call("printf '\e[3J'", shell=True)
def goto(x, y):
""" Moves curser to a position relative to current top of screen """
subprocess.call("tput cup %d %d" % (y, x), shell=True)
def saveCursorPosition():
subprocess.call("tput sc", shell=True)
def restoreCursorPosition():
subprocess.call("tput rc", shell=True)
def echoMessage(message):
""" Used for message writing after moving the cursor """
subprocess.call("echo '" + message + "'", shell=True)
def write(message):
""" default stdout message """
sys.stdout.write(message)
def printMessage(message):
""" Used for elaborate ASCII messages """
subprocess.call(["printf $'" + message + "'", "-n"] , shell=True)
def printMessageAt(message, location):
saveCursorPosition()
goto(location[0],location[1])
printMessage(message)
restoreCursorPosition()
def getRelevantHistoryLines(line_history, scrn_height, msg_len, startY):
line_history_first_line_pos = len(line_history) - (scrn_height - startY) + 2
line_history_last_line_pos = line_history_first_line_pos + msg_len - 1
history_lines_to_add = line_history[line_history_first_line_pos: line_history_last_line_pos]
return history_lines_to_add
def historyCoversScreen(line_history, scrn_height):
return len(line_history) >= scrn_height
def historyAndMsgIntersect(line_history, startY):
return len(line_history) > startY
def combinedMessages(msg_lines, history_lines):
if len(msg_lines) > len(history_lines):
return msg_lines[0] + '\n' + '\n'.join([line + msg_line for line, msg_line in list(itertools.izip_longest(history_lines, msg_lines[1:], fillvalue=fillIn))])
else:
raise ValueError('message length should always be longer than the history lines to combine')
def combineHistoryAndMessage(message, starting_line, line_history, scrn_height):
if historyCoversScreen(line_history, scrn_height):
msg_len = len(message)
# Since pressing enter pushes everything a line up in a full screen we deduce it by 1
starting_line = starting_line - 1
history_lines_to_add = getRelevantHistoryLines(line_history, scrn_height, msg_len, starting_line)
if len(history_lines_to_add) != msg_len - 1:
raise ValueError('message length be 1 less when historyCoversScreen')
return combinedMessages(message, history_lines_to_add)
elif historyAndMsgIntersect(line_history, starting_line):
msg_len = len(message)
history_lines_to_add = line_history[starting_line + 1: starting_line + msg_len]
return combinedMessages(message, history_lines_to_add)
else:
return combinedMessages(message, [])
|
{"/tests/main_test.py": ["/src/main.py"], "/tests/renderer_test.py": ["/src/consts.py", "/src/renderer.py", "/src/messages.py"], "/tests/messages_test.py": ["/src/messages.py"]}
|
19,946
|
bogobogo/bash-game
|
refs/heads/master
|
/src/consts.py
|
IN_WIDTH = 70
TESTING = True
|
{"/tests/main_test.py": ["/src/main.py"], "/tests/renderer_test.py": ["/src/consts.py", "/src/renderer.py", "/src/messages.py"], "/tests/messages_test.py": ["/src/messages.py"]}
|
19,947
|
bogobogo/bash-game
|
refs/heads/master
|
/src/strings.py
|
# -*- coding: utf-8 -*-
import subprocess
import os
#### welcome to syshero - a multiplayer game world where you cooperate and compete with others to gain reputation and resources,
# using unix knowledge. no prior knowledge is required. you will enter the multiplayer world when you reach level 10.
# to get Started create your character
# Name:
#
#
#to enter the world press y
#### use
#
totalxp = '80xp to level 2'
progressBar = "[=========================================================-------] 120"
# progressBar = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
first_message_content = """
Hey Dan. You don\\'t know me, but I need your
help.
I wish I could tell you more but time is short.
type \\'ls\\' to see files. use cat to
display their content.
"""
first_message_raw = """ .-----------------------------------------------------------------.
%-mamamas / .-. Hey Dan. You don\\'t know me, but I need your .-. \\
%-mamamas| / \ help. / \ |
%-mamamas| |\_. | I wish I could tell you more but time is short. | /| |
%-mamamas|\| | /| |\ | |/|
%-mamamas| `---\\' | type \\'ls\\' to see files. use cat to | `---\\' |
%-mamamas| | display their content. | |
%-mamamas| |-----------------------------------------------------| |
%-mamamas\ | | /
%-mamamas \ / \ /
%-mamamas `---\\' `---\\'"""
first_message = """ .-----------------------------------------------------------------.
/ .-. Hey Dan. You don\\'t know me, but I need your .-. \\
| / \ help. / \ |
| |\_. | I wish I could tell you more but time is short. | /| |
|\| | /| |\ | |/|
| `---\\' | type \\'ls\\' to see files. use cat to | `---\\' |
| | display their content. | |
| |-----------------------------------------------------| |
\ | | /
\ / \ /
`---\\' `---\\'"""
# first_message = first_message_raw.replace('mamama', '50')
#### ascii progress bar at the top
## use tput cols and tput lines to render
## use tput cup x y - see how it works
|
{"/tests/main_test.py": ["/src/main.py"], "/tests/renderer_test.py": ["/src/consts.py", "/src/renderer.py", "/src/messages.py"], "/tests/messages_test.py": ["/src/messages.py"]}
|
19,948
|
bogobogo/bash-game
|
refs/heads/master
|
/tests/messages_test.py
|
import unittest
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from src.messages import Message
from test_strings import first_message_no_tabs, first_message
class MessagesTest(unittest.TestCase):
def test_creates_message(self):
new_message = Message("hello", "111", (0,0))
self.assertEqual(new_message.message, ["hello"])
self.assertEqual(new_message.id, "111", (0,0))
def test_creates_message_with_new_lines(self):
new_message = Message(first_message_no_tabs, "111", (50,20))
self.assertEqual(new_message.message, first_message)
def test_deletes_message(self):
new_message = Message("hello", "111", (0,0))
self.assertEqual(new_message.deleteMessage, [" "])
def test_delete_message_with_new_lines(self):
new_message = Message("hello\n", "111", (0,0))
self.assertEqual(new_message.deleteMessage, [" "])
def test_delete_message_with_new_lines2(self):
new_message = Message("hel\n", "111", (0,0))
self.assertEqual(new_message.deleteMessage, [" "])
def test_delete_message_with_new_lines_in_middle_of_screen(self):
new_message = Message("hello\nhiiii\nyooooo\n", "111", (51,50))
self.assertEqual(new_message.deleteMessage, [" "," "," "])
def test_x_and_Y(self):
new_message = Message("hello\nhiiii\nyooooo\n", "111", (51,50))
self.assertEqual(new_message.x, 51)
self.assertEqual(new_message.y, 50)
def test_create_combined_message(self):
pass
if __name__ == '__main__':
unittest.main()
|
{"/tests/main_test.py": ["/src/main.py"], "/tests/renderer_test.py": ["/src/consts.py", "/src/renderer.py", "/src/messages.py"], "/tests/messages_test.py": ["/src/messages.py"]}
|
19,949
|
bogobogo/bash-game
|
refs/heads/master
|
/src/messages.py
|
import re
from strings import progressBar, first_message, totalxp
from consts import IN_WIDTH
from utils import removeNewLine
from renderer import saveCursorPosition, restoreCursorPosition, historyCoversScreen, goto, printMessage, write, printMessageAt, combineHistoryAndMessage, getTerminalSize
class Message():
@staticmethod
def createDeleteMessage(message, x):
split_message = removeNewLine(message).split("\n")
erased_split_message = [re.sub(r'.', " ", msg) for msg in split_message]
return erased_split_message
@staticmethod
def createMessage(message, x):
split_message = removeNewLine(message).split("\n")
return split_message
def __init__(self, message, id, startPosition):
self.id = id
self.message = self.createMessage(message, startPosition[0])
self.rawMessage = message
self.deleteMessage = self.createDeleteMessage(message, startPosition[0])
self.startPosition = startPosition
self.x = startPosition[0]
self.y = startPosition[1]
def write(self):
if len(self.message) == 1:
printMessageAt(self.message[0], self.startPosition)
printMessageAt(self.message, self.startPosition)
def erase(self):
printMessageAt(self.deleteMessage, (self.x, self.y-1) )
def overlay(self, line_history):
_ , screen_height = getTerminalSize()
y = self.y
if historyCoversScreen(line_history, screen_height):
y = y-1
if len(self.message) == 1:
printMessageAt(self.message[0], (self.x, y))
else:
combinedMessage = combineHistoryAndMessage(self.message, self.y, line_history, screen_height)
printMessageAt(combinedMessage, (self.x, y))
def clean(self, line_history):
_ , screen_height = getTerminalSize()
y = self.y
if historyCoversScreen(line_history, screen_height):
y = y-2
if len(self.deleteMessage) == 1:
printMessageAt(self.deleteMessage[0], (self.x, y))
return
combinedMessage = combineHistoryAndMessage(self.deleteMessage, y + 1 , line_history, screen_height)
printMessageAt(combinedMessage, (self.x, y))
return
if len(self.deleteMessage) == 1:
printMessageAt(self.deleteMessage[0], (self.x, y))
else:
combinedMessage = combineHistoryAndMessage(self.deleteMessage, y , line_history, screen_height)
printMessageAt(combinedMessage, (self.x, y))
totalxp = Message(totalxp, "xp message", (IN_WIDTH + 28, 9))
progressBar = Message(progressBar, "prg_bar", (IN_WIDTH + 2, 10))
level1_firstMessage = Message(first_message, "lvl1", (IN_WIDTH + 0, 11))
|
{"/tests/main_test.py": ["/src/main.py"], "/tests/renderer_test.py": ["/src/consts.py", "/src/renderer.py", "/src/messages.py"], "/tests/messages_test.py": ["/src/messages.py"]}
|
19,951
|
aahlborg/dht22
|
refs/heads/master
|
/pydht22.py
|
import ctypes
import sys
import subprocess
import json
# Load the C library
try:
dht22 = ctypes.CDLL("./dht22.so")
except OSError as e:
print(f"Error: {e}")
sys.exit()
class Sensor(ctypes.Structure):
_fields_ = [('pin', ctypes.c_int),
('status', ctypes.c_int),
('temp', ctypes.c_float),
('humidity', ctypes.c_float)]
def __init__(self):
self.status = -1
def __repr__(self):
return f"pin {self.pin}, status {self.status}, temp {self.temp:.1f}, humidity {self.humidity:.1f}"
def read_sensors_subproc(pins, num_retries=2):
cmd = ["./dht22", "--json", "-n", str(num_retries)] + [f"{x}" for x in pins]
# Set timeout to 5 seconds plus max retry time
timeout = 2 * (len(pins) * num_retries) + 5
try:
# Start subprocess and wait for it to terminate
out = subprocess.check_output(cmd, timeout=timeout)
# Decode JSON output
resp = json.loads(out.decode())
readings = dict()
for s in resp:
if s["status"] == "OK":
readings[int(s["pin"])] = (float(s["temp"]), float(s["humidity"]))
except subprocess.CalledProcessError as e:
print(e)
readings = dict()
except subprocess.TimeoutExpired as e:
print(e)
readings = dict()
return readings
def read_sensors(pins):
sensors = list()
for pin in pins:
sensor = Sensor()
sensor.pin = pin
sensors.append(sensor)
# Convert to ctypes array
sensors = (Sensor * len(sensors))(*sensors)
dht22.process_sensors(len(sensors), ctypes.byref(sensors), 3)
readings = dict()
for s in sensors:
readings[s.pin] = (s.temp, s.humidity)
return readings
|
{"/sensing.py": ["/pydht22.py"]}
|
19,952
|
aahlborg/dht22
|
refs/heads/master
|
/sensing.py
|
import pydht22
import time
from datetime import datetime, timedelta
import paho.mqtt.client as mqtt
broker = ("hass.lan", 1883)
sensors = {
# GPIO pin: topic
4: "home/garage",
# 17: "home/bedroom",
}
def get_next_even_minute(minutes):
now = datetime.now()
minute = (now.minute // minutes) * minutes + minutes
if minute >= 60:
now += timedelta(hours=1)
minute -= 60
return now.replace(minute=minute, second=0, microsecond=0)
def sleep_until_next_even_minute(minutes):
t = get_next_even_minute(minutes)
while (datetime.now() < t):
time.sleep(10)
def publish(client, topic, value):
rc, _ = client.publish(topic, value, qos=1)
if rc == 0:
print(f"{topic}: {value}")
else:
print(f"Failed to publish {topic} with error code {rc}")
def main():
while True:
sleep_until_next_even_minute(10)
print(datetime.now())
client = mqtt.Client()
client.connect(broker[0], broker[1], 60)
pins = sensors.keys()
readings = pydht22.read_sensors_subproc(pins)
for k, v in readings.items():
topic = sensors[k]
temp = v[0]
humidity = v[1]
print("{}: Temp: {:.1f} C, Humidity: {:.1f} % ".format(k, temp, humidity))
temp_topic = topic + "/temperature"
publish(client, temp_topic, temp)
humid_topic = topic + "/humidity"
publish(client, humid_topic, humidity)
if __name__ == "__main__":
main()
|
{"/sensing.py": ["/pydht22.py"]}
|
19,964
|
vishaver/flask_application2
|
refs/heads/master
|
/myproject/puppies/forms.py
|
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField,BooleanField,DateTimeField,RadioField,SelectField,TextAreaField,TextField,IntegerField
from wtforms.validators import DataRequired,Email,EqualTo, Length, ValidationError
class Add(FlaskForm):
name = StringField("Name of pupy",validators=[DataRequired()])
submit = SubmitField("Submit")
class Del(FlaskForm):
id = IntegerField("Enter the id:",validators=[DataRequired()])
submit = SubmitField("Submit")
|
{"/myproject/models.py": ["/myproject/__init__.py"], "/myproject/__init__.py": ["/myproject/puppies/views.py", "/myproject/owners/views.py"], "/app.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/forms.py"], "/myproject/forms.py": ["/myproject/models.py"], "/myproject/owners/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/owners/forms.py"], "/myproject/puppies/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/puppies/forms.py"]}
|
19,965
|
vishaver/flask_application2
|
refs/heads/master
|
/myproject/models.py
|
#setupdb inside __init__ file.
from myproject import db,login_manager
from werkzeug.security import generate_password_hash,check_password_hash
from flask_login import UserMixin
@login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
class User(db.Model,UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(64),index=True)
password_hash = db.Column(db.String(128))
def __init__(self,username,password):
self.username = username
self.password_hash = generate_password_hash(password)
def check_password(self,password):
check_password_hash(self.password_hash,password)
class Puppy(db.Model):
__tablename__ = 'puppies'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
owner = db.relationship('Owner', backref='puppy', uselist=False)
def __init__(self,name):
self.name = name
def __repr__(self):
if self.owner:
return f"Puppy name is {self.name} and owner is {self.owner.name}"
else:
return f"Puppy name is {self.name} and has no owner yet"
class Owner(db.Model):
__tablename__ = 'owners'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
puppy_id = db.Column(db.Integer, db.ForeignKey('puppies.id'))
def __init__(self,name,puppy_id):
self.name = name
self.puppy_id = puppy_id
def __repr__(self):
return f"owner name is {self.name}"
|
{"/myproject/models.py": ["/myproject/__init__.py"], "/myproject/__init__.py": ["/myproject/puppies/views.py", "/myproject/owners/views.py"], "/app.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/forms.py"], "/myproject/forms.py": ["/myproject/models.py"], "/myproject/owners/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/owners/forms.py"], "/myproject/puppies/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/puppies/forms.py"]}
|
19,966
|
vishaver/flask_application2
|
refs/heads/master
|
/myproject/__init__.py
|
import os
from flask import Flask,url_for,redirect,render_template,session
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
login_manager = LoginManager()
app = Flask(__name__)
app.config['SECRET_KEY'] = 'Thisisasecretkey'
# Database config goes here.
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir,'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Migrate(app,db)
login_manager.init_app(app)
login_manager.login_view = 'login'
from myproject.puppies.views import puppies_blueprint
from myproject.owners.views import owner_blueprint
app.register_blueprint(puppies_blueprint,url_prefix='/puppies')
app.register_blueprint(owner_blueprint,url_prefix='/owners')
|
{"/myproject/models.py": ["/myproject/__init__.py"], "/myproject/__init__.py": ["/myproject/puppies/views.py", "/myproject/owners/views.py"], "/app.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/forms.py"], "/myproject/forms.py": ["/myproject/models.py"], "/myproject/owners/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/owners/forms.py"], "/myproject/puppies/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/puppies/forms.py"]}
|
19,967
|
vishaver/flask_application2
|
refs/heads/master
|
/app.py
|
from flask import render_template,redirect,flash,request,abort,url_for
from myproject import app,db
from flask_login import login_user,login_required,logout_user
from myproject.models import User
from myproject.forms import LoginForm,RegistrationForm
from werkzeug.security import generate_password_hash,check_password_hash
@app.route('/')
def index():
return render_template('home.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
flash("You logged out")
return redirect(url_for('index'))
@app.route('/login',methods=['GET','POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
try:
if check_password_hash(user.password_hash,form.password.data) and user is not None:
login_user(user)
flash("You logged in successfully")
next = request.args.get('next')
if next == None or not next[0] == '/':
next = url_for('index')
return redirect(next)
except AttributeError:
redirect(url_for('login'))
return render_template('login.html',form=form)
@app.route('/Register',methods=['GET','POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
username = form.username.data
passwd = form.password.data
user = User(username,passwd)
db.session.add(user)
db.session.commit()
flash("Thanks for registration")
return redirect(url_for('login'))
return render_template('register.html',form=form)
|
{"/myproject/models.py": ["/myproject/__init__.py"], "/myproject/__init__.py": ["/myproject/puppies/views.py", "/myproject/owners/views.py"], "/app.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/forms.py"], "/myproject/forms.py": ["/myproject/models.py"], "/myproject/owners/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/owners/forms.py"], "/myproject/puppies/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/puppies/forms.py"]}
|
19,968
|
vishaver/flask_application2
|
refs/heads/master
|
/myproject/owners/forms.py
|
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField,BooleanField,DateTimeField,RadioField,SelectField,TextAreaField,TextField,IntegerField
from wtforms.validators import DataRequired,Email,EqualTo, Length, ValidationError
class Addowner(FlaskForm):
name = StringField("Name of owner:",validators=[DataRequired()])
puppy_id = IntegerField("Enter Puppy Id:",validators=[DataRequired()])
submit = SubmitField("Submit")
|
{"/myproject/models.py": ["/myproject/__init__.py"], "/myproject/__init__.py": ["/myproject/puppies/views.py", "/myproject/owners/views.py"], "/app.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/forms.py"], "/myproject/forms.py": ["/myproject/models.py"], "/myproject/owners/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/owners/forms.py"], "/myproject/puppies/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/puppies/forms.py"]}
|
19,969
|
vishaver/flask_application2
|
refs/heads/master
|
/myproject/forms.py
|
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,SubmitField
from wtforms.validators import DataRequired,EqualTo
from wtforms import ValidationError
from myproject.models import User
class LoginForm(FlaskForm):
username = StringField("Enter the username:",validators=[DataRequired()])
password = PasswordField("Password",validators=[DataRequired()])
submit = SubmitField("Log In")
class RegistrationForm(FlaskForm):
username = StringField("Username",validators=[DataRequired()])
password = PasswordField("Password",validators=[DataRequired(),EqualTo('pass_confirm',message='Password must match')])
pass_confirm = PasswordField("Confirm Password",validators=[DataRequired()])
submit = SubmitField("Register")
def check_user(self,field):
if User.query.filter_by(username=field.data).first():
raise ValidationError('This username is already registered')
|
{"/myproject/models.py": ["/myproject/__init__.py"], "/myproject/__init__.py": ["/myproject/puppies/views.py", "/myproject/owners/views.py"], "/app.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/forms.py"], "/myproject/forms.py": ["/myproject/models.py"], "/myproject/owners/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/owners/forms.py"], "/myproject/puppies/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/puppies/forms.py"]}
|
19,970
|
vishaver/flask_application2
|
refs/heads/master
|
/myproject/owners/views.py
|
from flask import Blueprint,render_template,redirect,url_for
from myproject import db
from myproject.models import Owner
from myproject.owners.forms import Addowner
from flask_login import login_user,login_required,logout_user
owner_blueprint = Blueprint('owners',__name__,template_folder='templates/owners')
@owner_blueprint.route('/add',methods=['GET','POST'])
@login_required
def add():
form = Addowner()
if form.validate_on_submit():
name = form.name.data
puppyid = form.puppy_id.data
owner_details = Owner(name,puppyid)
db.session.add(owner_details)
db.session.commit()
return redirect(url_for('puppies.list'))
return render_template('add_owner.html',form=form)
|
{"/myproject/models.py": ["/myproject/__init__.py"], "/myproject/__init__.py": ["/myproject/puppies/views.py", "/myproject/owners/views.py"], "/app.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/forms.py"], "/myproject/forms.py": ["/myproject/models.py"], "/myproject/owners/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/owners/forms.py"], "/myproject/puppies/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/puppies/forms.py"]}
|
19,971
|
vishaver/flask_application2
|
refs/heads/master
|
/myproject/puppies/views.py
|
from flask import Blueprint,render_template,url_for,redirect
from myproject import db
from myproject.models import Puppy
from myproject.puppies.forms import Add,Del
from flask_login import login_user,login_required,logout_user
puppies_blueprint = Blueprint('puppies',__name__,template_folder='templates/puppies')
@puppies_blueprint.route('/add',methods=['GET','POST'])
@login_required
def add():
form = Add()
if form.validate_on_submit():
name = form.name.data
new_puppy = Puppy(name)
db.session.add(new_puppy)
db.session.commit()
return redirect(url_for('puppies.list'))
return render_template('add.html',form=form)
@puppies_blueprint.route('/list')
@login_required
def list():
puppy_list = Puppy.query.all()
return render_template('list.html',puppies=puppy_list)
@puppies_blueprint.route('/delete',methods=['GET','POST'])
@login_required
def delete():
form = Del()
if form.validate_on_submit():
id_num = form.id.data
id_to_del = Puppy.query.get(id_num)
db.session.delete(id_to_del)
db.session.commit()
return redirect(url_for('puppies.list'))
return render_template('delete.html',form=form)
|
{"/myproject/models.py": ["/myproject/__init__.py"], "/myproject/__init__.py": ["/myproject/puppies/views.py", "/myproject/owners/views.py"], "/app.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/forms.py"], "/myproject/forms.py": ["/myproject/models.py"], "/myproject/owners/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/owners/forms.py"], "/myproject/puppies/views.py": ["/myproject/__init__.py", "/myproject/models.py", "/myproject/puppies/forms.py"]}
|
19,996
|
AvatarGanymede/ChinesePaintingStyle
|
refs/heads/master
|
/models/models.py
|
import torch
import torch.nn as nn
from torch.nn import init
import functools
from torch.optim import lr_scheduler
from utils.params import opt
def init_net(net, init_gain=0.02, gpu_ids=[]):
# init net
if len(gpu_ids) > 0:
assert (torch.cuda.is_available())
net.to(gpu_ids[0])
net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs
# using kaiming init to init weights
def init_func(m): # define the initialization function
classname = m.__class__.__name__
if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
init.normal_(m.weight.data, 0.0, init_gain)
elif classname.find(
'BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies.
init.normal_(m.weight.data, 1.0, init_gain)
init.constant_(m.bias.data, 0.0)
net.apply(init_func)
return net
class ResnetBlock(nn.Module):
"""Define a Resnet block"""
def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):
"""Initialize the Resnet block
A resnet block is a conv block with skip connections
We construct a conv block with build_conv_block function,
and implement skip connections in <forward> function.
Original Resnet paper: https://arxiv.org/pdf/1512.03385.pdf
"""
super(ResnetBlock, self).__init__()
self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias)
def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias):
"""Construct a convolutional block.
Parameters:
dim (int) -- the number of channels in the conv layer.
padding_type (str) -- the name of padding layer: reflect | replicate | zero
norm_layer -- normalization layer
use_dropout (bool) -- if use dropout layers.
use_bias (bool) -- if the conv layer uses bias or not
Returns a conv block (with a conv layer, a normalization layer, and a non-linearity layer (ReLU))
"""
conv_block = []
p = 0
if padding_type == 'reflect':
conv_block += [nn.ReflectionPad2d(1)]
elif padding_type == 'replicate':
conv_block += [nn.ReplicationPad2d(1)]
elif padding_type == 'zero':
p = 1
else:
raise NotImplementedError('padding [%s] is not implemented' % padding_type)
conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim), nn.ReLU(True)]
if use_dropout:
conv_block += [nn.Dropout(0.5)]
p = 0
if padding_type == 'reflect':
conv_block += [nn.ReflectionPad2d(1)]
elif padding_type == 'replicate':
conv_block += [nn.ReplicationPad2d(1)]
elif padding_type == 'zero':
p = 1
else:
raise NotImplementedError('padding [%s] is not implemented' % padding_type)
conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim)]
return nn.Sequential(*conv_block)
def forward(self, x):
"""Forward function (with skip connections)"""
out = x + self.conv_block(x) # add skip connections
return out
class ResnetGenerator(nn.Module):
"""
Adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style)
"""
def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6,
padding_type='reflect'):
"""Construct a Resnet-based generator
Parameters:
input_nc (int) -- the number of channels in input images
output_nc (int) -- the number of channels in output images
ngf (int) -- the number of filters in the last conv layer
norm_layer -- normalization layer
use_dropout (bool) -- if use dropout layers
n_blocks (int) -- the number of ResNet blocks
padding_type (str) -- the name of padding layer in conv layers: reflect | replicate | zero
"""
assert (n_blocks >= 0)
super(ResnetGenerator, self).__init__()
if type(norm_layer) == functools.partial:
use_bias = norm_layer.func == nn.InstanceNorm2d
else:
use_bias = norm_layer == nn.InstanceNorm2d
model = [nn.ReflectionPad2d(3),
nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias),
norm_layer(ngf),
nn.ReLU(True)]
n_downsampling = 2
for i in range(n_downsampling): # add downsampling layers
mult = 2 ** i
model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias),
norm_layer(ngf * mult * 2),
nn.ReLU(True)]
mult = 2 ** n_downsampling
for i in range(n_blocks): # add ResNet blocks
model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout,
use_bias=use_bias)]
for i in range(n_downsampling): # add upsampling layers
mult = 2 ** (n_downsampling - i)
model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),
kernel_size=3, stride=2,
padding=1, output_padding=1,
bias=use_bias),
norm_layer(int(ngf * mult / 2)),
nn.ReLU(True)]
model += [nn.ReflectionPad2d(3)]
model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)]
model += [nn.Tanh()]
self.model = nn.Sequential(*model)
def forward(self, input):
"""Standard forward"""
return self.model(input)
def define_G(input_nc, output_nc, ngf, use_dropout=False, init_gain=0.02, gpu_ids=[]):
"""Create a generator
Parameters:
input_nc (int) -- the number of channels in input images
output_nc (int) -- the number of channels in output images
ngf (int) -- the number of filters in the last conv layer
netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks | unet_256 | unet_128
norm (str) -- the name of normalization layers used in the network: batch | instance | none
use_dropout (bool) -- if use dropout layers.
init_type (str) -- the name of our initialization method.
init_gain (float) -- scaling factor for normal, xavier and orthogonal.
gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2
Returns a generator
Our current implementation provides two types of generators:
U-Net: [unet_128] (for 128x128 input images) and [unet_256] (for 256x256 input images)
The original U-Net paper: https://arxiv.org/abs/1505.04597
Resnet-based generator: [resnet_6blocks] (with 6 Resnet blocks) and [resnet_9blocks] (with 9 Resnet blocks)
Resnet-based generator consists of several Resnet blocks between a few downsampling/upsampling operations.
We adapt Torch code from Justin Johnson's neural style transfer project (https://github.com/jcjohnson/fast-neural-style).
The generator has been initialized by <init_net>. It uses RELU for non-linearity.
"""
# using batch norm
norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True)
# using resnet-9blocks
net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9)
# init net
return init_net(net, init_gain, gpu_ids)
class NLayerDiscriminator(nn.Module):
"""Defines a PatchGAN discriminator"""
def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):
"""Construct a PatchGAN discriminator
Parameters:
input_nc (int) -- the number of channels in input images
ndf (int) -- the number of filters in the last conv layer
n_layers (int) -- the number of conv layers in the discriminator
norm_layer -- normalization layer
"""
super(NLayerDiscriminator, self).__init__()
if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters
use_bias = norm_layer.func == nn.InstanceNorm2d
else:
use_bias = norm_layer == nn.InstanceNorm2d
kw = 4
padw = 1
sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]
nf_mult = 1
nf_mult_prev = 1
for n in range(1, n_layers): # gradually increase the number of filters
nf_mult_prev = nf_mult
nf_mult = min(2 ** n, 8)
sequence += [
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),
norm_layer(ndf * nf_mult),
nn.LeakyReLU(0.2, True)
]
nf_mult_prev = nf_mult
nf_mult = min(2 ** n_layers, 8)
sequence += [
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),
norm_layer(ndf * nf_mult),
nn.LeakyReLU(0.2, True)
]
sequence += [
nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map
self.model = nn.Sequential(*sequence)
def forward(self, input):
"""Standard forward."""
return self.model(input)
def define_D(input_nc, ndf, n_layers_D=3, init_gain=0.02, gpu_ids=[]):
"""Create a discriminator
Parameters:
input_nc (int) -- the number of channels in input images
ndf (int) -- the number of filters in the first conv layer
netD (str) -- the architecture's name: basic | n_layers | pixel
n_layers_D (int) -- the number of conv layers in the discriminator; effective when netD=='n_layers'
norm (str) -- the type of normalization layers used in the network.
init_type (str) -- the name of the initialization method.
init_gain (float) -- scaling factor for normal, xavier and orthogonal.
gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2
Returns a discriminator
Our current implementation provides three types of discriminators:
[basic]: 'PatchGAN' classifier described in the original pix2pix paper.
It can classify whether 70×70 overlapping patches are real or fake.
Such a patch-level discriminator architecture has fewer parameters
than a full-image discriminator and can work on arbitrarily-sized images
in a fully convolutional fashion.
[n_layers]: With this mode, you can specify the number of conv layers in the discriminator
with the parameter <n_layers_D> (default=3 as used in [basic] (PatchGAN).)
[pixel]: 1x1 PixelGAN discriminator can classify whether a pixel is real or not.
It encourages greater color diversity but has no effect on spatial statistics.
The discriminator has been initialized by <init_net>. It uses Leakly RELU for non-linearity.
"""
# using batch norm
norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True)
net = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer)
# init net
return init_net(net, init_gain, gpu_ids)
def get_scheduler(optimizer):
def lambda_rule(epoch):
lr_l = 1.0 - max(0, epoch + opt['epoch_count'] - opt['n_epochs']) / float(opt['n_epochs_decay'] + 1)
return lr_l
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)
return scheduler
|
{"/models/models.py": ["/utils/params.py"], "/test.py": ["/utils/__init__.py", "/models/__init__.py", "/utils/params.py"], "/main.py": ["/gui/chinesepaintings.py", "/models/__init__.py", "/edge/hed.py", "/utils/params.py", "/utils/__init__.py"], "/utils/__init__.py": ["/utils/dataset.py", "/utils/params.py"], "/gui/chinesepaintings.py": ["/gui/notitle.py"], "/utils/dataset.py": ["/utils/params.py"], "/models/cycle_gan.py": ["/utils/params.py", "/models/__init__.py"]}
|
19,997
|
AvatarGanymede/ChinesePaintingStyle
|
refs/heads/master
|
/test.py
|
import os
from utils import create_dataset
from models import create_model
from utils.visualizer import save_images
from utils import html
from utils.params import opt
import warnings
warnings.filterwarnings("ignore")
if __name__ == '__main__':
dataset = create_dataset('test') # create a dataset given opt.dataset_mode and other options
dataset_size = len(dataset)
print('The number of training images = %d' % dataset_size)
model = create_model(False) # create a model given opt.model and other options
model.setup() # regular setup: load and print networks; create schedulers
# create a website
web_dir = os.path.join(opt['results_dir'], opt['name'], '{}_{}'.format(opt['phase'], opt['epoch'])) # define the website directory
if opt['load_iter'] > 0: # load_iter is 0 by default
web_dir = '{:s}_iter{:d}'.format(web_dir, opt.load_iter)
print('creating web directory', web_dir)
webpage = html.HTML(web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt['name'], opt['phase'], opt['epoch']))
# test with eval mode. This only affects layers like batchnorm and dropout.
# For [pix2pix]: we use batchnorm and dropout in the original pix2pix. You can experiment it with and without eval() mode.
# For [CycleGAN]: It should not affect CycleGAN as CycleGAN uses instancenorm without dropout.
# if opt.eval:
# model.eval()
for i, data in enumerate(dataset):
if i >= opt['num_test']: # only apply our model to opt.num_test images.
break
model.set_input(data) # unpack data from data loader
model.test() # run inference
visuals = model.get_current_visuals() # get image results
img_path = model.get_image_paths() # get image paths
if i % 5 == 0: # save images to an HTML file
print('processing (%04d)-th image... %s' % (i, img_path))
save_images(webpage, visuals, img_path, aspect_ratio=opt['aspect_ratio'], width=opt['display_winsize'])
webpage.save() # save the HTML
|
{"/models/models.py": ["/utils/params.py"], "/test.py": ["/utils/__init__.py", "/models/__init__.py", "/utils/params.py"], "/main.py": ["/gui/chinesepaintings.py", "/models/__init__.py", "/edge/hed.py", "/utils/params.py", "/utils/__init__.py"], "/utils/__init__.py": ["/utils/dataset.py", "/utils/params.py"], "/gui/chinesepaintings.py": ["/gui/notitle.py"], "/utils/dataset.py": ["/utils/params.py"], "/models/cycle_gan.py": ["/utils/params.py", "/models/__init__.py"]}
|
19,998
|
AvatarGanymede/ChinesePaintingStyle
|
refs/heads/master
|
/main.py
|
import os
import sys
import threading
import time
import cv2 as cv
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import *
from gui.chinesepaintings import Ui_MainWindow
from models import create_model
from edge.hed import extract_edge
import warnings
from utils.params import opt
from utils import create_dataset, html
from utils.visualizer import save_images
warnings.filterwarnings("ignore")
StyleSheet = """
/*标题栏*/
TitleBar {
background-color: red;
}
/*最小化最大化关闭按钮通用默认背景*/
#buttonMinimum,#buttonClose {
border: none;
background-color: red;
}
/*悬停*/
#buttonMinimum:hover{
background-color: red;
color: white;
}
#buttonClose:hover {
color: white;
}
/*鼠标按下不放*/
#buttonMinimum:pressed{
background-color: Firebrick;
}
#buttonClose:pressed {
color: white;
background-color: Firebrick;
}
"""
def remove(path):
filelist = os.listdir(path) # 打开对应的文件夹
for item in filelist:
os.remove(path+'/'+item)
def getImage(img, self):
img = cv.cvtColor(img, cv.COLOR_RGB2BGR)
width = img.shape[1]
height = img.shape[0]
image = QImage(img, width, height, QImage.Format_RGB888)
scale_factor = 0
if width > height:
scale_factor = self.org_image.width() / float(width)
else:
scale_factor = self.org_image.height() / float(height)
image = image.scaled(width * scale_factor, height * scale_factor, Qt.IgnoreAspectRatio,
Qt.SmoothTransformation)
return image
class MyMainForm(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MyMainForm, self).__init__(parent)
self.setupUi(self)
self.model = create_model(False)
self.isvideo = False
self.is_pause = False
def Open(self):
sc_name, filetype = QFileDialog.getOpenFileName(caption="选取文件", directory=os.getcwd(),
filter="All Files (*)")
if sc_name.split(".")[-1] != 'jpg' and sc_name.split(".")[-1] != 'png' and sc_name.split(".")[-1] != 'mp4':
QMessageBox.critical(self, 'File Type Not Right', 'The type of file selected is not supported!',
buttons=QMessageBox.Cancel)
elif sc_name.split(".")[-1] == 'mp4':
self.isvideo = True
i = 0
remove('./data/testA')
capture = cv.VideoCapture(sc_name)
self.frame_count = capture.get(cv.CAP_PROP_FRAME_COUNT)
self.frameRate = capture.get(cv.CAP_PROP_FPS)
if capture.isOpened():
while True:
ret, img = capture.read()
self.progressBar.setValue(i / self.frame_count * 100)
if not ret:
break
last_img = img
cv.imwrite('./data/testA/'+str(i)+'.jpg', img)
i = i + 1
image = getImage(last_img, self)
self.org_image.setPixmap(QPixmap.fromImage(image))
else:
img = cv.imread(sc_name)
remove('./data/testA')
cv.imwrite('./data/testA/1.jpg', img)
image = getImage(img, self)
self.org_image.setPixmap(QPixmap.fromImage(image))
def Transfer(self):
dataset = create_dataset('test') # create a dataset given opt.dataset_mode and other options
dataset_size = len(dataset)
self.model.setup()
web_dir = os.path.join(opt['results_dir'], opt['name'],
'{}_{}'.format(opt['phase'], opt['epoch'])) # define the website directory
webpage = html.HTML(web_dir,
'Experiment = %s, Phase = %s, Epoch = %s' % (opt['name'], opt['phase'], opt['epoch']))
for i, data in enumerate(dataset):
self.progressBar.setValue(i/dataset_size*100)
if i >= opt['num_test']: # only apply our model to opt.num_test images.
break
self.model.set_input(data) # unpack data from data loader
self.model.test() # run inference
visuals = self.model.get_current_visuals() # get image results
img_path = self.model.get_image_paths() # get image paths
if i % 5 == 0: # save images to an HTML file
print('processing (%04d)-th image... %s' % (i, img_path))
save_images(webpage, visuals, img_path, aspect_ratio=opt['aspect_ratio'], width=opt['display_winsize'])
webpage.save() # save the HTML
if not self.isvideo:
self.progressBar.setValue(100)
rst = cv.imread('./results/Chinese Painting Style/test_latest/images/1_fake_B.png')
image = getImage(rst, self)
self.after_image.setPixmap(QPixmap.fromImage(image))
org = cv.imread('./results/Chinese Painting Style/test_latest/images/1_real_A.png')
image = getImage(org, self)
self.org_image.setPixmap(QPixmap.fromImage(image))
else:
self.progressBar.setValue(0)
th = threading.Thread(target=self.Display)
th.setDaemon(True)
th.start()
# display the video on the QLabel
def Display(self):
i = 0
while i < self.frame_count:
# calculate the processing time
time_start = time.time()
if self.is_pause:
continue
frame = cv.imread('./results/Chinese Painting Style/test_latest/images/'+str(i)+'_fake_B.png')
org = cv.imread('./results/Chinese Painting Style/test_latest/images/'+str(i)+'_real_A.png')
image = getImage(frame, self)
self.after_image.setPixmap(QPixmap.fromImage(image))
image = getImage(org, self)
self.org_image.setPixmap(QPixmap.fromImage(image))
time_end = time.time()
time_wait = int(1000 / self.frameRate - 1000 * (time_end - time_start))
if time_wait <= 0:
time_wait = 1
cv.waitKey(time_wait)
self.progressBar.setValue(i/self.frame_count*100)
i = i + 1
def Pause(self):
self.is_pause = not self.is_pause
def Play(self):
self.is_pause = False
if __name__ == "__main__":
# 固定的,PyQt5程序都需要QApplication对象。sys.argv是命令行参数列表,确保程序可以双击运行
app = QApplication(sys.argv)
app.setStyleSheet(StyleSheet)
# 初始化
myWin = MyMainForm()
# 将窗口控件显示在屏幕上
myWin.show()
# 程序运行,sys.exit方法确保程序完整退出。
sys.exit(app.exec_())
|
{"/models/models.py": ["/utils/params.py"], "/test.py": ["/utils/__init__.py", "/models/__init__.py", "/utils/params.py"], "/main.py": ["/gui/chinesepaintings.py", "/models/__init__.py", "/edge/hed.py", "/utils/params.py", "/utils/__init__.py"], "/utils/__init__.py": ["/utils/dataset.py", "/utils/params.py"], "/gui/chinesepaintings.py": ["/gui/notitle.py"], "/utils/dataset.py": ["/utils/params.py"], "/models/cycle_gan.py": ["/utils/params.py", "/models/__init__.py"]}
|
19,999
|
AvatarGanymede/ChinesePaintingStyle
|
refs/heads/master
|
/utils/__init__.py
|
""" Python package for image processing """
import torch.utils.data
from utils.dataset import Dataset
from utils.params import opt
from PIL import Image
def save_image(image_numpy, image_path, aspect_ratio=1.0):
"""Save a numpy image to the disk
Parameters:
image_numpy (numpy array) -- input numpy array
image_path (str) -- the path of the image
"""
image_pil = Image.fromarray(image_numpy)
h, w, _ = image_numpy.shape
if aspect_ratio > 1.0:
image_pil = image_pil.resize((h, int(w * aspect_ratio)), Image.BICUBIC)
if aspect_ratio < 1.0:
image_pil = image_pil.resize((int(h / aspect_ratio), w), Image.BICUBIC)
image_pil.save(image_path)
def create_dataset(train_or_test, max_dataset_size=float("inf")):
"""Create a dataset given the option.
This function wraps the class CustomDatasetDataLoader.
This is the main interface between this package and 'train.py'/'test.py'
Example:
>>> from utils import create_dataset
>>> dataset = create_dataset(train_or_test, max_dataset_size)
"""
data_loader = DataLoader(train_or_test, max_dataset_size)
data_set = data_loader.load_data()
return data_set
def __print_size_warning(ow, oh, w, h):
"""Print warning information about image size(only print once)"""
if not hasattr(__print_size_warning, 'has_printed'):
print("The image size needs to be a multiple of 4. "
"The loaded image size was (%d, %d), so it was adjusted to "
"(%d, %d). This adjustment will be done to all images "
"whose sizes are not multiples of 4" % (ow, oh, w, h))
__print_size_warning.has_printed = True
class DataLoader:
"""Wrapper class of Dataset class that performs multi-threaded data loading"""
def __init__(self, train_or_test, max_dataset_size=float("inf")):
"""Initialize this class
Step 1: create a dataset instance given the name [dataset_mode]
Step 2: create a multi-threaded data loader.
"""
self.max_dataset_size = max_dataset_size
self.dataset = Dataset(train_or_test)
print("dataset [%s] was created" % type(self.dataset).__name__)
self.dataloader = torch.utils.data.DataLoader(
self.dataset,
batch_size=opt['batch_size'],
# shuffle=not opt.serial_batches,
shuffle=True,
num_workers=int(opt['num_threads']))
def load_data(self):
return self
def __len__(self):
"""Return the number of data in the dataset"""
return min(len(self.dataset), self.max_dataset_size)
def __iter__(self):
"""Return a batch of data"""
for i, data in enumerate(self.dataloader):
if i * opt['batch_size'] >= self.max_dataset_size:
break
yield data
|
{"/models/models.py": ["/utils/params.py"], "/test.py": ["/utils/__init__.py", "/models/__init__.py", "/utils/params.py"], "/main.py": ["/gui/chinesepaintings.py", "/models/__init__.py", "/edge/hed.py", "/utils/params.py", "/utils/__init__.py"], "/utils/__init__.py": ["/utils/dataset.py", "/utils/params.py"], "/gui/chinesepaintings.py": ["/gui/notitle.py"], "/utils/dataset.py": ["/utils/params.py"], "/models/cycle_gan.py": ["/utils/params.py", "/models/__init__.py"]}
|
20,000
|
AvatarGanymede/ChinesePaintingStyle
|
refs/heads/master
|
/gui/chinesepaintings.py
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'chinesepaintings.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from .notitle import TitleBar
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(958, 535)
MainWindow.setStyleSheet("")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
MainWindow.setWindowFlags(Qt.FramelessWindowHint) # 隐藏边框
# 标题栏
self.titleBar = TitleBar(MainWindow)
self.titleBar.setGeometry(QtCore.QRect(-1, -1, 960, 42))
font = QtGui.QFont()
font.setFamily("Consolas")
self.titleBar.setFont(font)
self.titleBar.setStyleSheet("font:bold;background-image: url(:/pic/imgs/bg.png);color:#f9f1db;")
self.titleBar.windowMinimumed.connect(MainWindow.showMinimized)
self.titleBar.windowClosed.connect(MainWindow.close)
self.titleBar.windowMoved.connect(self.move)
MainWindow.windowTitleChanged.connect(self.titleBar.setTitle)
MainWindow.windowIconChanged.connect(self.titleBar.setIcon)
self.background = QtWidgets.QLabel(self.centralwidget)
self.background.setGeometry(QtCore.QRect(0, 0, 960, 540))
self.background.setStyleSheet("background-image: url(:/pic/imgs/bg.png);")
self.background.setText("")
self.background.setObjectName("background")
self.org_image = QtWidgets.QLabel(self.centralwidget)
self.org_image.setGeometry(QtCore.QRect(80, 110, 320, 320))
self.org_image.setStyleSheet("border-width: 5px;\n"
"border-style: solid;\n"
"border-color: rgb(192, 72, 81);")
self.org_image.setText("")
self.org_image.setObjectName("org_image")
self.after_image = QtWidgets.QLabel(self.centralwidget)
self.after_image.setGeometry(QtCore.QRect(560, 110, 320, 320))
self.after_image.setStyleSheet("border-width: 5px;\n"
"border-style: solid;\n"
"border-color: rgb(192, 72, 81);")
self.after_image.setText("")
self.after_image.setObjectName("after_image")
self.transfer = QtWidgets.QPushButton(self.centralwidget)
self.transfer.setGeometry(QtCore.QRect(430, 290, 101, 41))
self.transfer.setStyleSheet("QPushButton{\n"
"font: 32pt \"方正字迹-周崇谦小篆繁体\";\n"
"color: rgb(192, 72, 81);\n"
"background-color:transparent;\n"
"}\n"
"QPushButton:hover{\n"
"color: #f9f1db;\n"
"}")
self.transfer.setObjectName("transfer")
self.OIMG = QtWidgets.QLabel(self.centralwidget)
self.OIMG.setGeometry(QtCore.QRect(190, 70, 81, 41))
self.OIMG.setStyleSheet("font: 32pt \"方正字迹-周崇谦小篆繁体\";\n"
"color: rgb(192, 72, 81);")
self.OIMG.setObjectName("OIMG")
self.AIMG = QtWidgets.QLabel(self.centralwidget)
self.AIMG.setGeometry(QtCore.QRect(680, 70, 81, 41))
self.AIMG.setStyleSheet("font: 32pt \"方正字迹-周崇谦小篆繁体\";\n"
"color: rgb(192, 72, 81);")
self.AIMG.setObjectName("AIMG")
self.open = QtWidgets.QPushButton(self.centralwidget)
self.open.setGeometry(QtCore.QRect(430, 190, 101, 41))
self.open.setStyleSheet("QPushButton{\n"
"font: 32pt \"方正字迹-周崇谦小篆繁体\";\n"
"color: rgb(192, 72, 81);\n"
"background-color:transparent;\n"
"}\n"
"QPushButton:hover{\n"
"color: #f9f1db;\n"
"}")
self.open.setObjectName("open")
self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
self.progressBar.setGeometry(QtCore.QRect(80, 460, 321, 31))
self.progressBar.setStyleSheet("QProgressBar {\n"
" border: 2px solid grey;\n"
" border-radius: 5px;\n"
" border-color: #c04851;\n"
" text-align: center;\n"
" font: 75 12pt \"黑体-简\";\n"
" color: #b78d12;\n"
"}\n"
"\n"
"QProgressBar::chunk {\n"
" background-color: #c04851;\n"
" width: 20px;\n"
"}")
self.progressBar.setProperty("value", 0)
self.progressBar.setObjectName("progressBar")
self.pause = QtWidgets.QPushButton(self.centralwidget)
self.pause.setGeometry(QtCore.QRect(560, 450, 101, 41))
self.pause.setStyleSheet("QPushButton{\n"
"font: 32pt \"方正字迹-周崇谦小篆繁体\";\n"
"color: rgb(192, 72, 81);\n"
"background-color:transparent;\n"
"}\n"
"QPushButton:hover{\n"
"color: #f9f1db;\n"
"}")
self.pause.setObjectName("pause")
self.play = QtWidgets.QPushButton(self.centralwidget)
self.play.setGeometry(QtCore.QRect(780, 450, 101, 41))
self.play.setStyleSheet("QPushButton{\n"
"font: 32pt \"方正字迹-周崇谦小篆繁体\";\n"
"color: rgb(192, 72, 81);\n"
"background-color:transparent;\n"
"}\n"
"QPushButton:hover{\n"
"color: #f9f1db;\n"
"}")
self.play.setObjectName("play")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
self.open.clicked.connect(MainWindow.Open)
self.transfer.clicked.connect(MainWindow.Transfer)
self.pause.clicked.connect(MainWindow.Pause)
self.play.clicked.connect(MainWindow.Play)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("", ""))
self.transfer.setText(_translate("MainWindow", "转化"))
self.OIMG.setText(_translate("MainWindow", "原图"))
self.AIMG.setText(_translate("MainWindow", "国画"))
self.open.setText(_translate("MainWindow", "打开"))
self.pause.setText(_translate("MainWindow", "暂停"))
self.play.setText(_translate("MainWindow", "播放"))
from . import source_rc
|
{"/models/models.py": ["/utils/params.py"], "/test.py": ["/utils/__init__.py", "/models/__init__.py", "/utils/params.py"], "/main.py": ["/gui/chinesepaintings.py", "/models/__init__.py", "/edge/hed.py", "/utils/params.py", "/utils/__init__.py"], "/utils/__init__.py": ["/utils/dataset.py", "/utils/params.py"], "/gui/chinesepaintings.py": ["/gui/notitle.py"], "/utils/dataset.py": ["/utils/params.py"], "/models/cycle_gan.py": ["/utils/params.py", "/models/__init__.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.