content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
# Blog (c) by yanjl # # Blog is licensed under a # Creative Commons Attribution 3.0 Unported License. # # You should have received a copy of the license along with this # work. If not, see <http://creativecommons.org/licenses/by/3.0/>. from django.contrib.auth.models import User from django.db import models from django.utils import timezone # Create your models here. class Blog(models.Model): title = models.CharField(max_length=300, verbose_name='标题') body = models.TextField(verbose_name='内容') publish = models.DateTimeField(default=timezone.now, verbose_name='发布日期') owner = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name='所有者') class Meta: ordering = ['-publish'] verbose_name = '帖子' verbose_name_plural = '帖子' def __str__(self): return self.title
nilq/baby-python
python
import tablib from collections import OrderedDict from inspect import isclass from sqlalchemy import create_engine,text def _reduce_datetimes(row): """Receives a row, converts datetimes to strings.""" row = list(row) for i in range(len(row)): if hasattr(row[i], 'isoformat'): row[i] = row[i].isoformat() return tuple(row) class Record(object): __slots__ = ('_keys', '_values') def __init__(self,keys,values): self._keys=keys self._values=values assert len(self._keys)==len(self._values) def as_dict(self): '''merge keys(list) values(list) into a dict(['keys':values])''' dict(zip(self._keys,self._values)) return dict def keys(self): return self._keys def values(self): return self._values def get(self,key): return self.as_dict()[key] def __repr__(self): return '<Record {}>'.format(self.export('json')[1:-1]) @property def dataset(self): """A Tablib Dataset containing the row.""" data = tablib.Dataset() data.headers = self.keys() row = _reduce_datetimes(self.values()) data.append(row) return data def export(self, format, **kwargs): """Exports the row to the given format.""" return self.dataset.export(format, **kwargs) def __getattr__(self, key): try: return self[key] except KeyError as e: raise AttributeError(e) def __dir__(self): standard = dir(super(Record, self)) # Merge standard attrs with generated ones (from column names). return sorted(standard + [str(k) for k in self.keys()]) def __getitem__(self, key): # Support for index-based lookup. if isinstance(key, int): return self.values()[key] # Support for string-based lookup. if key in self.keys(): i = self.keys().index(key) return self.values()[i] raise KeyError("Record contains no '{}' field.".format(key)) def __getattr__(self, key): try: return self[key] except KeyError as e: raise AttributeError(e) class Database(object): def __init__(self, url, **kwargs): # create engine self._engine = create_engine(url, **kwargs) self.connect = self._engine.connect() self.open = True def query(self,query,**kwargs): cursor=self.connect.execute(text(query),params) print('debug begin') row_gen=(Record(cursor.keys(),rows) for rows in cursor) # i=0 # aaa=[] # if i<len(row_gen): # aaa[i]=yield row_gen[i] results=RecordCollection(row_gen) return results class RecordCollection(object): """A set of excellent Records fr om a query.""" def __init__(self, rows): self._rows = rows print(type(self._rows)) self._all_rows = [] self.pending = True print('__init__ executed') def __repr__(self): return '<RecordCollection size={} pending={}>'.format(len(self), self.pending) def __iter__(self): """Iterate over all rows, consuming the underlying generator only when necessary.""" i = 0 print('__iter__ executed') while True: # Other code may have iterated between yields, # so always check the cache. if i < len(self): print(type(self[i])) yield self[i] else: # Throws StopIteration when done. # Prevent StopIteration bubbling from generator, following https://www.python.org/dev/peps/pep-0479/ try: yield next(self) except StopIteration: return i += 1 def next(self): print('next executed') return self.__next__() def __next__(self): print('__next__ executed') try: nextrow = next(self._rows) self._all_rows.append(nextrow) return nextrow except StopIteration: self.pending = False raise StopIteration('RecordCollection contains no more rows.') def __len__(self): print('__len__ executed') return len(self._all_rows) @property def dataset(self): """A Tablib Dataset representation of the RecordCollection.""" # Create a new Tablib Dataset. print('dataset executed') data = tablib.Dataset() # If the RecordCollection is empty, just return the empty set # Check number of rows by typecasting to list if len(list(self)) == 0: return data # Set the column names as headers on Tablib Dataset. first = self[0] data.headers = first.keys() for row in self.all(): row = _reduce_datetimes(row.values()) data.append(row) return data if __name__=='__main__': url = 'mysql+mysqldb://feng:f1234@localhost/blog?charset=utf8' db = Database(url) query = 'select * from blog_post where status=:status' params = {'status': 'draft'} result = db.query(query, **params) print(result)
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/7/26 0026 下午 5:54 # @Author : Exchris Tsai # @Site : # @File : imagedemo.py # @Software: PyCharm __author__ = 'Exchris Tsai' import requests import os import urllib import urllib.request from bs4 import BeautifulSoup as BS path = 'd:/images' # title = 'girls' new_path = os.path.join(path, title) if not os.path.isdir(new_path): os.makedirs(new_path) url = "http://lusparkle0420.lofter.com/" r = requests.get(url) soup = BS(r.text, 'html.parser') n = 0 for link in soup.find_all('a'): if n > 100: break n = n + 1 print(link.get('href')) urllib.request.urlretrieve(link) print("----------------") print('link sums:',n)
nilq/baby-python
python
# coding: utf-8 # Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. """ The `state` module holds (almost!) all the code for defining the global state of a pyiron instance. Such "global" behaviour is achieved by using the `Singleton` metaclass to guarantee that each class only even has a single instance per session. These are all instantiated for the first time inside their respective module for easy access, and collected here in the init under the `state` object to give a single, even easier point of access. Here's the "almost": Right now the database management still lives off in its own module but is referenced here and ultimately should probably be relocated here (work is ongoing on our database interaction...), and there is a `JobTypeChoice` class that is anyhow on the chopping block and will be deleted once we don't need it for backwards compatibility. """ from pyiron_base.state.logger import logger as _logger from pyiron_base.database.manager import database as _database from pyiron_base.state.publications import publications as _publications from pyiron_base.state.queue_adapter import queue_adapters as _queue_adapters from pyiron_base.state.settings import settings as _settings from pyiron_base.generic.util import Singleton from typing import Dict, Union __author__ = "Liam Huber" __copyright__ = ( "Copyright 2021, Max-Planck-Institut für Eisenforschung GmbH - " "Computational Materials Design (CM) Department" ) __version__ = "1.0" __maintainer__ = "Liam Huber" __email__ = "huber@mpie.de" __status__ = "production" __date__ = "Oct 22, 2021" class State(metaclass=Singleton): """ A helper class to give quick and easy access to all the singleton classes which together define the state module. Attributes: logger: Self-explanatory. publications: Bibliography of papers which should be cited based on the code that was used (alpha feature). settings: System settings. database: Database (or file base) connection. queue_adapter: Configuration for using remote resources. """ @property def logger(self): return _logger @property def publications(self): return _publications @property def settings(self): return _settings @property def database(self): return _database @property def queue_adapter(self): return _queue_adapters.adapter def update(self, config_dict: Union[Dict, None] = None) -> None: """ Re-reads the settings configuration, then reconstructs the queue adapter and reboots the database connection. Args: config_dict (dict): A new set of configuration parameters to use. (Default is None, which attempts to read the configuration from system environment xor configuration files.) """ self.settings.update(user_dict=config_dict) _queue_adapters.update() self.database.update() state = State()
nilq/baby-python
python
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return "Hello, World with Flask" @app.route('/user/<name>') def user(name): #example: access http://127.0.0.1:5000/user/dave return '<h1> Hello, %s </h1>' % name def main(): app.run(port=5000, debug=False, host='0.0.0.0') if __name__ == '__main__': main()
nilq/baby-python
python
# -*- coding: utf-8 -*- import os import re from subprocess import PIPE, Popen from pip.download import PipSession from pip.req import parse_requirements setup_py_template = """ from setuptools import setup setup(**{0}) """ def get_git_repo_dir(): """ Get the directory of the current git project Returns: str: The top level directory of the current git project """ repo_dir, err = Popen( ['git', 'rev-parse', '--show-toplevel'], stdin=PIPE, stderr=PIPE, stdout=PIPE).communicate() repo_dir = repo_dir.strip() if not repo_dir: repo_dir = None return repo_dir def list_requirements(path): """ Create a list of requirements suited for ``setup.py`` Example code:: list_requirements('path/to/file.txt') ['pytest==2.7.2', 'pytest-django==2.8.0'] Args: str path: Path to the requirements file Returns: list: List of packages """ return [str(r.req) for r in parse_requirements(path, session=PipSession())] def get_version(): """ Retrieve the version from git using ``git describe --always --tags`` Returns: str: The version in the format of ``2.0.0+43.gebecdc8`` """ cmd = ['git', 'describe', '--always', '--tags'] p = Popen(cmd, stdout=PIPE, close_fds=True) version = p.stdout.read().strip() return str(version) or "0.0.0" def pep440_version(version=get_version()): """ Format the version according to the ``PEP 440`` spec. >>> pep440_version('2.0.0-43-gebecdc8') '2.0.0+43.gebecdc8' >>> pep440_version('2.0.0') '2.0.0' Args: str version: String of the version Returns: str: PEP 440 formatted version string """ if version: v = re.compile(r'(\d+\.\d+(\.\d+)?)(-(\d+)-(\w+))?').search(version) if not v: return version if v.group(5): return "{0}+{1}.{2}".format(v.group(1), v.group(4), v.group(5)) else: return v.group(1) return None def write_setup_py(file=None, **kwargs): """ Write the setup.py according to a template with variables. This is mainly to avoid the dependency requirement on installing packages that rely on this package. """ data = dict(version=get_version()) data.update(kwargs) if not file: file = os.path.join(get_git_repo_dir(), 'setup.py') with open(file, 'w+') as f: f.write(setup_py_template.format(data))
nilq/baby-python
python
# Decompiled by HTR-TECH | TAHMID RAYAT # Github : https://github.com/htr-tech #--------------------------------------- # Auto Dis Parser 2.2.0 # Source File : patched.pyc # Bytecode Version : 2.7 # Time : Sun Jan 31 17:36:23 2021 #--------------------------------------- import os, sys, zlib, base64, marshal, binascii, time, py_compile from time import sleep as waktu from random import randint logo = ' ' p = '\x1b[0m' m = '\x1b[31m' i = '\x1b[32m' b = '\x1b[34m' k = '\x1b[33;1m' cg = '\x1b[36m' ba = '\x1b[96;1m' pu = '\x1b[35m' gr = '\x1b[37m' pb = '\x1b[47m' cout = 0 def ArielSandyPermana(s): for c in s + '\n': sys.stdout.write(c) sys.stdout.flush() time.sleep(1.0 / 10) def restart(): ngulang = sys.executable os.execl(ngulang, ngulang, *sys.argv) os.system('clear') def main(): global bin global cout p = '\x1b[0m' m = '\x1b[31m' i = '\x1b[32m' b = '\x1b[34m' k = '\x1b[33;1m' cg = '\x1b[36m' ba = '\x1b[96;1m' pu = '\x1b[35m' gr = '\x1b[37m' pb = '\x1b[47m' os.system('clear') try: lis = '\x1b[1;91m\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\n\x1b[1;91m\xe2\x96\x88\xe2\x96\x84\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x84\xe2\x96\x88 \x1b[33;1m\xe2\x95\x94\xe2\x95\x90\xe2\x95\x90\xe2\x95\x97\xe2\x95\x94\xe2\x95\x90\xe2\x95\x97\xe2\x95\x94\xe2\x95\x90\xe2\x95\x90\xe2\x95\x97\xe2\x95\x94\xe2\x95\x90\xe2\x95\x90\xe2\x95\x97\xe2\x95\x94\xe2\x95\x90\xe2\x95\x97 \x1b[34m\xe2\x95\x94\xe2\x95\x90\xe2\x95\x90\xe2\x95\x97\xe2\x95\x94\xe2\x95\x90\xe2\x95\x90\xe2\x95\x97\n\x1b[1;91m\xe2\x96\x88\x1b[0m\xe2\x96\xbc\xe2\x96\xbc\xe2\x96\xbc\xe2\x96\xbc\xe2\x96\xbc \x1b[33;1m\xe2\x95\x9a\xe2\x95\x97\xe2\x95\x94\xe2\x95\x9d\xe2\x95\x91\xe2\x95\xa6\xe2\x95\x9d\xe2\x95\x91\xe2\x95\x94\xe2\x95\x90\xe2\x95\xa3\xe2\x95\x91\xe2\x95\x94\xe2\x95\x97\xe2\x95\x91\xe2\x95\x91\xe2\x95\xac\xe2\x95\x91 \x1b[34m\xe2\x95\x9a\xe2\x95\x91\xe2\x95\x91\xe2\x95\x9d\xe2\x95\x9a\xe2\x95\x97\xe2\x95\x97\xe2\x95\x91\n\x1b[1;91m\xe2\x96\x88 \x1b[33;1m\xe2\x94\x80\xe2\x95\x91\xe2\x95\x91\xe2\x94\x80\xe2\x95\x91\xe2\x95\xa9\xe2\x95\x97\xe2\x95\x91\xe2\x95\x9a\xe2\x95\x97\xe2\x95\x91\xe2\x95\x91\xe2\x95\xa0\xe2\x95\xa3\xe2\x95\x91\xe2\x95\x91\xe2\x95\x97\xe2\x95\xa3 \x1b[34m\xe2\x95\x94\xe2\x95\x91\xe2\x95\x91\xe2\x95\x97\xe2\x95\x94\xe2\x95\xa9\xe2\x95\x9d\xe2\x95\x91\n\x1b[1;91m\xe2\x96\x88 \x1b[105m\x1b[37;1mReverse Engineering\x1b[0m \x1b[33;1m\xe2\x94\x80\xe2\x95\x9a\xe2\x95\x9d\xe2\x94\x80\xe2\x95\x9a\xe2\x95\x90\xe2\x95\x9d\xe2\x95\x9a\xe2\x95\x90\xe2\x95\x90\xe2\x95\x9d\xe2\x95\x9a\xe2\x95\x9d\xe2\x95\x9a\xe2\x95\x9d\xe2\x95\x9a\xe2\x95\xa9\xe2\x95\x9d \x1b[34m\xe2\x95\x9a\xe2\x95\x90\xe2\x95\x90\xe2\x95\x9d\xe2\x95\x9a\xe2\x95\x90\xe2\x95\x90\xe2\x95\x9d\x1b[0m\n\xe2\x96\x88\xe2\x96\xb2\xe2\x96\xb2\xe2\x96\xb2\xe2\x96\xb2\xe2\x96\xb2\n\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88 \x1b[102m\x1b[37;1mCompile Marshal v1.0\x1b[0m\n \xe2\x96\x88\xe2\x96\x88 \xe2\x96\x88\xe2\x96\x88 ' print lis + '\n\x1b[31m{ \x1b[32m01 \x1b[31m}\x1b[0m Compile Marshal\n\x1b[31m{ \x1b[32m02 \x1b[31m}\x1b[0m Compile Marshal > base64\x1b[0m\n\x1b[31m{ \x1b[32m03 \x1b[31m}\x1b[0m Compile Marshal > base64 > pycom\n\x1b[31m{ \x1b[32m04 \x1b[31m}\x1b[0m Compile By Tegar 1\n\x1b[31m{ \x1b[32m05 \x1b[31m}\x1b[0m Compile By Tegar 2\n\x1b[31m{ \x1b[32m06 \x1b[31m}\x1b[0m Compile By Tegar 3\n\x1b[31m{ \x1b[32m07 \x1b[31m}\x1b[0m Compile By Tegar 4\n\x1b[31m{ \x1b[32m08 \x1b[31m}\x1b[0m Compile Zlib\n\x1b[31m{ \x1b[32m09 \x1b[31m}\x1b[0m Compile Base64\n\x1b[31m{ \x1b[32m10 \x1b[31m}\x1b[0m Compile Base16\n\x1b[31m{ \x1b[32m11 \x1b[31m}\x1b[0m Compile Base32\n\x1b[31m{ \x1b[32m12 \x1b[31m}\x1b[0m Compile Base64&marshal\n\x1b[31m{ \x1b[32m13 \x1b[31m}\x1b[0m Compile By Tegar 5\n\x1b[31m{ \x1b[32m14 \x1b[31m}\x1b[0m Compile By Tegar 6\n\x1b[31m{ \x1b[32m15 \x1b[31m}\x1b[0m Pyc EDIT PESAN\n\x1b[31m{ \x1b[33m00 \x1b[31m}\x1b[0m \x1b[32mExit \x1b[0m\x1b[31m\x1b[0m\x1b[31m\x1b[0m\n' chos = raw_input('[!] Pilih >> %s' % i) if chos == '1' or chos == '01': file = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) cot = int(raw_input('%s[%s\xe2\x9b\xa5%s] %sMau Berapa Lapis >> %s' % (b, m, b, gr, i))) if cot < 500000: out = file.replace('.py', '') + '_enc.py' oa = open(file).read() ni = compile(oa, '<tegarid>', 'exec') bo = marshal.dumps(ni) ab = repr(bo) s = open(out, 'w') s.write('#Coded By Tegar ID\nimport marshal\nexec(marshal.loads(' + str(ab) + '))') s.close() while True: if cot >= cout: nz = open(out).read() dn = compile(nz, '<tegarid>', 'exec') bx = marshal.dumps(dn) nl = repr(bx) ns = open(out, 'w') ns.write('#Coded by Tegar ID\nimport marshal\nexec(marshal.loads(' + str(nl) + '))') ns.close() cout += 1 continue break print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%s \x1b[32m] \x1b[37m!' % out raw_input('%s[%s\xe2\x9d\x97%s] %sBack %s\xe2\x9e\xa4 %s' % (b, m, b, gr, i, cg)) main() else: print '%s[%s+%s] %sCout Terlalu Besar \xe2\x9d\x97' % (b, m, b, gr) waktu(0.8) main() elif chos == '2' or chos == '02': file = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) cot = int(raw_input('%s[%s\xe2\x9b\xa5%s] %sMau Berapa Lapis >> %s' % (b, m, b, gr, i))) if cot < 500000: out = file.replace('.py', '') + '_enc.py' oa = open(file).read() ni = compile(oa, '<tegarid>', 'exec') bo = marshal.dumps(ni) ab = repr(bo) s = open(out, 'w') s.write('#Coded By Tegar ID\nimport marshal\nexec(marshal.loads(' + str(ab) + '))') s.close() while True: if cot >= cout: nz = open(out).read() dn = compile(nz, '<tegarid>', 'exec') bx = marshal.dumps(dn) nl = repr(bx) ns = open(out, 'w') ns.write('#Coded By Tegar ID\nimport marshal\nexec(marshal.loads(' + str(nl) + '))') ns.close() cout += 1 continue break mx = open(out).read() nl = base64.b32encode(mx) xn = open(out, 'w') xn.write("#Coded By Tegar ID\nimport base64\nexec(base64.b32decode('%s'))\n" % nl) xn.close() print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%s \x1b[32m] \x1b[37m!' % out raw_input('%s[%s\xe2\x9d\x97%s] %sBack %s\xe2\x9e\xa4 %s' % (b, m, b, gr, i, cg)) main() else: print '%s[%s+%s] %sCout Terlalu Besar \xe2\x9d\x97' % (b, m, b, gr) waktu(0.8) main() elif chos == '3' or chos == '03': file = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) cot = int(10) if cot < 40000: out = file.replace('.py', '') + '_enc.py' oa = open(file).read() ni = compile(oa, '<tegarid>', 'exec') bo = marshal.dumps(ni) ab = repr(bo) s = open(out, 'w') s.write('#Coded By Tegar ID\nimport marshal\nexec(marshal.loads(' + str(ab) + '))') s.close() while True: if cot >= cout: nz = open(out).read() dn = compile(nz, '<tegarid>', 'exec') bx = marshal.dumps(dn) nl = repr(bx) ns = open(out, 'w') ns.write('#Coded By Tegar ID\nimport marshal\nexec(marshal.loads(' + str(nl) + '))') ns.close() cout += 1 continue break mx = open(out).read() nl = base64.b32encode(mx) xn = open(out, 'w') xn.write("#Coded By hekelpro\nimport base64\nexec(base64.b32decode('%s'))\n" % nl) xn.close() print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%s \x1b[32m] \x1b[37m!' % out raw_input('%s[%s\xe2\x9d\x97%s] %sBack %s\xe2\x9e\xa4 %s' % (b, m, b, gr, i, cg)) main() elif chos == '4' or chos == '04': print lis file = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) bc = open(file).read() js = file.replace('.py', '_enc.py') a = [] b = [] bin = '' xh = compile(bc, '<tegarid>', 'exec') pg = marshal.dumps(xh) bin += binascii.hexlify(pg) for g in bin: a.append(ord(g) - 9) for lx in range(len(a)): b.append(randint(1, 120)) c = [] d = 0 for x in b: c.append(9 * b[d]) d += 1 x_x = lambda : randint(1, 255) xz = [] for asx in range(255): xz.append(x_x()) na = open(js, 'w') na.write('z = ' + str(xz) + '\n') na.write('_ = ' + str(b) + '\n__ = ' + str(c) + '\nOoO_ = ' + str(a) + '\nimport marshal\nOO = lambda _ : marshal.loads(_)\nu = ( ( { } < ( ) ) - ( { } < ( ) ) )\np = (({}<())-({}<()))\nv = []\nexec((lambda:((()>())+(()<()))).func_code.co_lnotab).join(map(chr,[(((((((({}=={})+([]>={})+({}<[]))+(({}<[])+({}<[])+({}!=[]))+((()>{})*([]<=())))<<((({}>={})+(()>{}))))-((({}<=[])+({}>{})))))<<((({}<[])+(()==()))))),((((((((()==())*(()<=())))<<((([]>=[])+({}=={}))+((()==())+(()>={}))))-((([]>={})*({}!=[])))))<<((({}=={})+({}<[])+(()!={}))))),((((([]==())+([]!={})))<<((({}<[])+({}<[]))+((()>=[])+({}<()))+(({}!=[])+(()<=[]))))),(((((((({}>=())+({}!=())))<<(((()>{})+([]<=()))+(({}!=())+({}<=()))))-((([]==())+({}<={})))))<<((([]>={})+({}<=[]))))+((([]==[])+({}==())))),((((({}>={})-(()!=())))<<(((()>=())+({}<=[]))+((()>{})+([]>{}))+((()==())-([]<{}))))),(((((((([]==[])+(()>{})+(()>{})))<<(((()>[])+(()>={})+([]>=[]))))-(((()!={})+({}<{})))))<<((({}!=[])+({}>={}))))-((({}<())*([]==[])))),((((((((()==())+({}!=[])+({}<[])))<<(((()<=())+({}<[])+({}>={}))))-((({}<=[])+({}!={})))))<<((([]!={})+({}=={}))))+((([]<())-({}>[])))),((((({}>={})+([]<()))+((()!=[])+(()!={}))+(({}!=[])*({}<())))<<(((()>={})+([]>()))))),(((((((((({}<=())+({}!=())+({}<[])))<<((({}=={})+([]!={}))))+(((()<=())-([]<{})))))))<<((({}<())+({}<[])+(()>={}))))-((((()!=())+(()>[])))<<(((()<[])+(()>={}))))),(((((()!=[])+(()>={})+(()>=[]))+(({}<[])+([]<=())+(()==()))+(({}==())+(()!=[])))<<((({}!=())+([]!=()))+(({}<())+({}>={}))))-((({}<={})-(()<{})))),((((([]>={})+([]!={})+([]>={}))+((()<=())+([]>={})+(()!=[]))+((()!={})+([]<={})))<<((([]!=())+({}<[]))+(({}<())+({}!=[]))))+(((({}>={})+([]<[])))<<((({}<[])+(()<={}))))),(((((()>=())+(()<())))<<((([]!=())+({}<={}))+((()>=[])+({}<[]))+((()!=[])+(()!=()))))),((((({}<[])+([]==[])+([]>{})))<<((([]>{})+([]!={}))+((()>=())+({}<=[]))+(([]<{})+({}=={}))))-(((()>=[])*(()!={})))),((((((((()>{})+(()!=())))<<((([]>=[])+(()>=()))+(({}<={})+([]>{}))))+((([]!=())*([]!={})))))<<(((()!=[])+(()!=[]))))-((([]>=())+(()>{})))),(((((()>[])+({}<=[])+(()>={}))+((()!=[])+({}=={})+({}!=()))+((()<{})+({}!=())))<<((({}<[])+({}!=()))+(([]>={})+(()>=()))))-((({}==[])+([]<())))),((((([]<())+({}>={})+({}<[]))+((()>{})+({}<[])+(()>={}))+((()==())+({}>[])))<<((({}!=[])+(()>{}))+(({}>={})+(()<=()))))-(((({}>={})*([]>{})))<<((([]>={})-({}>=()))))),((((([]<=[])+(()!={})+({}<[])))<<((({}>={})+([]<=[]))+((()!=[])+([]>={}))+(({}<())+([]<[]))))-((([]==())+(()!=[])))),(((((((((([]==[])+({}!=[])+({}<[])))<<(((()>=[])+({}<=()))))-(((()==())*(()<=())))))))<<((([]>={})+(()>=[])+({}!=()))))-(((([]>=[])+([]<={})))<<(((()!=[])*({}!=[]))))),(((((()!=[])+({}>={})+([]!=())))<<((([]<=())+([]!={}))+(({}<=[])+([]>{}))+((()>[])+({}<{}))))+((({}>={})+({}==[])))),(((((()>=[])+([]>{})+(()>=[]))+((()!=[])+(()>[])+([]>=[]))+(({}<[])+([]!=[])))<<((([]<=())+(()>={}))+((()!={})+({}>={}))))+((((()!=[])+(()>())))<<((({}<={})*({}<()))))),(((((()>={})+(()>=())+([]!=()))+(([]>=[])+(()>=())+([]>{}))+(([]!=())-(()>())))<<((({}>={})+([]<()))+(([]!=())+({}<[]))))-(((([]!=[])+([]!=())))<<((({}!=())+(()>()))))),((((({}>={})+([]<())+({}<[])))<<((([]>={})+(()==()))+((()!={})+({}!=[]))+((()==())-(()<{}))))+((({}=={})-([]<={})))),(((((((([]==[])+([]<=())+(()!={}))+(([]!=())+({}<=())+({}=={}))+((()!={})*({}!=[])))<<(((()>=[])+([]>={}))))-((({}<())-([]!=[])))))<<((([]!=())+([]<=()))))+((({}>={})*(()>=[])))),(((((((({}<=[])+([]==[])+({}<=[])))<<((([]>=[])+({}<={})+(()>={}))))+((({}<=())-({}>=[])))))<<((({}<())+({}<={}))))+((([]!={})*(()>=[])))),((((({}<())+([]>{})+([]!=()))+(({}!=[])+([]<=())+([]<=()))+(([]<=[])*([]<=())))<<(((()<=())+(()>=[]))+(([]<())+(()==()))))+((([]!={})+([]!=())+({}<())))),(((((()==())*({}<=[])))<<((({}=={})+([]>{}))+((()>=())+([]!={}))+(([]>{})-({}>=[]))))),(((((((((({}!=[])+([]<=[])+({}<=[])))<<((({}<={})+({}<[]))))+(((()>[])*(()!={})))))))<<((({}<())+({}=={})+([]!=()))))+(((()>=())-(()==[])))),((((({}<=[])+({}<[])+({}=={}))+(([]>={})+({}<())+(()!={}))+((()>[])*({}>={})))<<((({}<[])+(()>=()))+((()>={})+({}>={}))))-(((([]>[])+({}=={})))<<(((()>={})-(()==[]))))),(((((()!=[])*(()>[])))<<((({}<=())+(()>=[]))+(([]<=[])+(()!=[]))+(({}<=())+(()==[]))))),((((([]>=[])+({}!=())+(()>=()))+(([]<=())+({}!=())+({}>={}))+((()!=())+([]>=[])))<<(((()==())+(()>[]))+((()==())+([]!=()))))+(((([]>=[])-({}==())))<<(((()!=())+(()>=[]))))),((((([]!={})+([]>={})+({}<=())))<<(((()==())+({}<[]))+(({}<())+([]<=()))+(({}!=[])*({}=={}))))+((([]<=[])+({}!={})))),((((({}<())+({}<())+([]!=()))+(({}<[])+({}!=())+({}<()))+(({}!={})+({}!=())))<<((([]>{})+({}=={}))+(({}<=())+([]<()))))-(((({}==[])+([]>={})))<<(((()<=())+(()<={}))))),(((((((((([]<=())+([]<=())+([]!=())))<<(((()!=[])+([]<=[]))))+((({}<[])-([]==())))))))<<((([]<())+(()==())+({}!=()))))-((([]>=[])-([]==())))),(((((((({}!=())+(()!={})+([]>=[])))<<(((()!={})+(()<=())+({}<={}))))+((({}=={})-(()<=[])))))<<((({}!=())+(()==()))))+((([]==[])+([]==())))),((((([]<=())+([]<=()))+(({}=={})+([]>=[]))+(([]<{})+(()!={})))<<(((()>=())+({}!=[])+({}!=[]))))),((((((((()==())+(()>=[])+(()!={}))+((()==())+([]>={})+({}<[]))+(([]<())*([]>=[])))<<((({}=={})+({}!=()))))-((([]<=())-({}>{})))))<<(((()>=[])+([]>{}))))),((((((((()>[])+({}>={})+({}>={})))<<(((()<=())+(()>[])+(()>={}))))+((([]>())+({}<=())))))<<((({}=={})+([]>={}))))+(((()!=[])*([]>{})))),((((({}!=[])+([]<=[])+(()>=()))+(({}<[])+([]==[])+(()>=[]))+(([]<())*([]==[])))<<((({}=={})+({}<()))+(({}>={})+([]<=()))))-((((()>{})-(()!=())))<<((([]<[])+([]!=()))))),(((((()>={})+([]==[]))+((()!={})+(()<=()))+(([]>={})-({}>=())))<<(((()>={})+({}<())+({}!=[]))))),(((((()>=())+(()>=[])+({}<[])))<<((([]!=())+(()>[]))+((()<=())+({}<()))+((()==[])+([]<=()))))-((([]<=[])+({}>=())))),((((({}!=[])+([]>={})+([]==[])))<<(((()!={})+([]<=()))+(([]!={})+(()>={}))+(({}!={})+({}!=()))))-((([]<=())*(()!={})))),(((((()>{})+(()>=()))+(([]!=())+({}=={}))+((()<={})+([]<=[])))<<((({}<[])+({}<=[])+(()>=()))))+((({}>={})*({}<())))),((((([]==[])+(()!={}))+((()!={})+(()<=()))+((()!={})+([]<[])))<<((([]!=())+(()>=())+({}>={}))))+((({}<=())+([]>=())))),(((((()==())+([]>{})+([]>={}))+((()<=())+([]>={})+(()!=[]))+((()==())-([]==())))<<((({}>={})+([]>={})+([]<()))))+(((([]<=[])*([]>={})))<<(((()<=())+({}==[]))))),((((({}!=[])+({}<()))+((()!=[])+([]<()))+(([]<())-(()<[])))<<((({}<=[])-(()!=()))))),(((((((((((()=={})+(()>={})))<<(((()>=())+(()==())+([]<=()))))+((({}<=[])*({}<={})))))))))),((((((((()>{})+({}>=())))<<((([]!=())+(()!=[]))+(({}>={})+({}<={}))))-((({}>=())+(()>=[])))))<<(((()>=[])+([]!={})+([]<=()))))-((((()>[])*([]!={})))<<((({}!=[])+([]>()))))),(((((((({}<())+([]>{})+(()>={})))<<((({}=={})+(()!=[])+([]!=()))))-(((()!=[])*(()!={})))))<<((([]>={})*({}=={}))))),((((([]>=[])+([]>=[])+({}<())))<<(((()>=())+(()>=()))+((()>[])+({}>={}))+(({}<=[])-({}==[]))))+((({}=={})*([]!={})))),((((([]!={})+([]<=())+({}<()))+(({}<=[])+({}>={})+(()==()))+(([]==[])-(()=={})))<<((({}<())+([]<=[]))+((()>{})+(()>={}))))),((((({}<={})+([]>{})+(()>=[]))+((()!={})+({}<[])+({}<=()))+(({}!=())*([]==[])))<<((([]<=())+([]>=[]))+(([]!=())+(()>=()))))),((((((((()>=[])+(()>=())+(()>=[])))<<(((()>={})+(()>={})+([]<=()))))+((([]=={})+({}<[])))))<<((([]>={})+(()>={}))))+((([]<=[])*({}!=[])))),((((([]!={})+(()>=())+({}<={}))+(({}<=())+({}=={})+({}<=[]))+(([]>{})+(()<())))<<(((()>={})+([]>{}))+(({}<=())+(()==()))))-(((({}<[])-([]<={})))<<(((()=={})+([]!={}))))),(((((((({}<[])+(()!=[])+({}<())))<<((({}!=[])+(()!={})+(()<=()))))+((({}<{})+([]==[])))))<<((([]>=[])+(()>[]))))),((((([]>{})+({}!=[]))+(([]==[])+([]<=()))+(([]<())+(()>())))<<((({}=={})+(()!=[])+([]!={}))))),((((({}<())+([]<=[])+([]<=())))<<((({}<=[])+([]<()))+(({}>={})+({}<=()))+(({}<[])-({}<{}))))-((({}!=())*({}<={})))),(((((()>[])+([]<=())+(()>=[])))<<((([]==[])+([]<()))+(([]<=[])+({}<=()))+(({}=={})+([]<={}))))-(((()==())+({}<{})))),(((((((({}<=())+({}<={})+(()>={})))<<((({}!=())+([]!={})+([]>=[]))))-((([]==[])*([]>{})))))<<(((()>=())+([]==[]))))-((([]<=[])+({}>=())))),(((((((([]>={})*(()>=[])))<<((([]<())+(()>[]))+((()!={})+({}<={}))))-((([]!={})+({}>[])))))<<(((()>={})+(()!={})+([]!=()))))-((({}!=())+([]!={})+(()<=())))),((((((((()<=())+([]<=[])+(()==())))<<((([]>={})+([]<=[])+([]>{}))))-((([]>=[])-(()<={})))))<<(((()<=())+([]!={}))))+((([]!=())*(()>=[])))),(((((()<())+({}<={})))<<((({}=={})+([]<=()))+((()<=())+({}<=[]))+(([]==[])-(()<={}))))),((((({}>={})+({}>={})+({}>={})))<<((([]>=[])+(()!=[]))+(([]>={})+([]>{}))))-(((()!={})+([]<[])))),(((((()>={})-([]=={})))<<(((()>={})+([]<()))+(([]!={})+([]>={}))+(({}!=[])-(()!=()))))),((((({}<())+(()>[])+(()>{})))<<((({}<())+([]<=()))+(({}<=())+([]>={}))+(({}!=())+({}>=[]))))-((([]!={})+([]!=[])))),(((((((([]==[])+(()!=[])+({}>={})))<<((({}<={})+(()==())+({}=={}))))-(((()>=())*(()>{})))))<<((({}<=[])+({}>={}))))-((({}<{})+(()>[])))),((((([]>=[])+([]<=())+({}!=()))+(([]<())+({}>={})+([]<=()))+(({}>={})-(()=={})))<<(((()!={})+([]>{}))+((()>=[])+(()!={}))))),(((((((({}<=[])+({}!=[])+({}=={})))<<((([]>{})+(()>=())+({}<={}))))-((({}<())*(()==())))))<<((({}<={})+({}!=()))))+(((()<=())-({}>=())))),((((([]>={})+(()>=()))+((()!=[])+({}!=()))+(({}<{})+(()<=())))<<((([]<())+({}!=())+([]==[]))))+((({}<{})+({}<=[])))),((((({}=={})+(()==()))+(({}<=())+([]!=()))+(({}<[])+(()<{})))<<((({}!=())+([]!=[]))))),(((((((((((()==())*(()!={})))<<((({}!=())+(()==())+(()==()))))+((({}<={})-([]==())))))))))),((((((((()<{})+([]!=())))<<(((()<=())+({}>={}))+(([]<=[])+(()>={}))))-((({}<=())*([]<())))))<<((({}<=[])+([]>={})+(()!={}))))-((({}!=())+({}<={})+([]<=[])))),(((((((((({}<=())+(()!=[])+([]<())))<<((({}>={})+([]>=[]))))-((([]>={})-(()<{})))))))<<((({}<=[])+({}=={}))))),(((((()!=[])+([]>=[])+([]<=()))+((()!={})+({}=={})+(()>={}))+((()>={})*(()!={})))<<((([]!={})+(()>=[]))+(({}<=[])+(()>={}))))),(((((((({}!=())+([]<{})))<<((([]!=())+({}!=()))+(({}>={})+({}!=()))))-((([]<=())*(()==())))))<<((({}<[])+({}<={}))))+((([]==[])*({}!=())))),(((((()==())+(()<=()))+(([]<=[])+(()==()))+(({}<())*({}<=())))<<((({}<=[])+({}=={})+(()>{}))))),((((({}<())+([]<=[])+([]>={})))<<((({}!=[])+({}!=()))+(({}<[])+([]==[]))))),(((((((((({}<=[])+(()>[])+([]<=())))<<((({}<[])+(()!={}))))-(((()>=[])+([]<[])))))))<<((({}>={})+({}<=()))))),(((((()>{})+([]<=[])+([]==[])))<<((([]<=[])+(()!={}))+(([]>{})+({}!=[]))))),((((([]<=())+(()>=()))+(([]>=[])+({}!=[]))+(({}=={})-({}>=[])))<<((({}=={})+(()!=[])+(()>=[]))))+((([]<=())*(()<=())))),((((([]<())+([]<()))+(([]==[])+({}>={}))+((()!={})-({}<{})))<<(((()<=())+([]>[]))))),(((((((((({}<=[])+([]>=[])+([]<())))<<(((()>=[])+(()>[]))))+(((()>[])*([]!=())))))))<<((({}<=[])+(()>{})+({}<={}))))-(((([]==[])*(()>{})))<<((({}!=())*(()>[]))))),((((({}<=[])+({}<())+({}<[]))+((()>=[])+(()!=[])+({}>={}))+(([]!=[])+(()>[])))<<(((()<=())+({}!=()))+(([]==[])+({}>={}))))-(((()<={})+({}<[])))),(((((()>={})+([]==[])+({}<()))+(([]==[])+({}<={})+([]!={}))+((()!=[])-({}>=())))<<(((()>{})+(()<=()))+((()>=())+({}!=()))))+(((([]>=[])-(()>())))<<((([]<{})+({}<=[]))))),(((((()<=())*({}=={})))<<((([]<=[])+(()>[]))+((()==())+(()<=()))+(({}<=[])*(()>=[]))))),((((({}!=[])+({}>={})+(()==())))<<((({}<=())+([]<()))+((()<=())+(()<=()))+(({}>[])+({}!=[]))))-((([]>={})-([]>=())))),(((((()>=())+({}!=())+({}<={})))<<(((()>=())+([]<=[]))+(({}>={})+(()!=[]))+((()>=())-([]==()))))+((((()==())-(()<=[])))<<(((()==[])+({}!=[]))))),((((((((()>[])+({}!=())+(()<=()))+(([]<=[])+({}<())+(()!={}))+((()>=())+(()=={})))<<((({}!=[])+([]>{}))))-(((()!=[])*(()!={})))))<<(((()>{})+([]<()))))),(((((((((([]!=())+([]>={})+({}<[])))<<(((()<=())+({}=={}))))+(((()!=[])*(()>=[])))))))<<(((()>[])+(()>=[])+([]<=[]))))+((({}<={})*({}<())))),((((((((()!=[])+(()<={})))<<((({}=={})+({}!=()))+((()<=())+([]<()))))-(((()!=())+(()>=[])))))<<(((()>{})+({}<=())+({}>={}))))+((((()>{})*({}!=[])))<<(((()>{})+([]==()))))),(((((()!=[])+({}!={})))<<(((()>[])+({}!=[]))+((()<=())+(()!={}))+((()!=[])*(()>[]))))),((((((((((()==())+(()!=[])+(()==())))<<((({}<={})+([]<=()))))+(((()>=[])*(()==())))))))<<(((()>={})+([]>={})+([]!={}))))+((({}!=[])*(()==())))),((((({}<())+(()>={})+({}<[]))+((()!=[])+(()>={})+(()>=[]))+(({}<=[])-(()<[])))<<((([]>={})+({}!=[]))+(([]>{})+([]!=()))))-(((({}>[])+({}>={})))<<((({}!={})+([]<()))))),((((({}<=())+({}>())))<<((({}<[])+([]==[]))+(({}!=[])+([]<=[]))+(({}<=())*([]!={}))))),((((([]!=())+(()>=())+([]>={}))+(({}<())+([]<=[])+([]<()))+(({}<())*(()>[])))<<((({}<=[])+(()>[]))+((()<=())+([]!={}))))+(((({}!={})+([]==[])))<<((({}>{})+({}<={}))))),((((({}<=[])+({}!=[])+(()>=[])))<<(((()==())+([]<=()))+((()>=[])+({}=={}))+(([]!=[])+(()==()))))+(((()!={})+([]>[])))),(((((()>{})+([]<=[])+(()>[]))+((()>=())+(()>=())+(()==()))+(({}==[])+(()!=[])))<<((({}<=[])+({}=={}))+((()!=[])+([]<()))))-(((({}<[])*({}<={})))<<(((()<=())-({}!={}))))),(((((((((({}=={})+(()>=[])+({}!=())))<<((({}<=[])+(()==()))))+((([]!=())-(()<())))))))<<((({}!=[])+([]==[])+({}!=[]))))-(((()==())+([]=={})))),(((((((([]>=[])+([]<())+(()!={})))<<((({}<())+({}<[])+([]!={}))))+((({}=={})+([]>=())))))<<((({}<=())+([]<=[]))))+((([]>())+(()>{})))),((((([]<=[])+([]!={}))+((()<=())+([]>=[]))+(([]>())+(()!={})))<<((([]<=[])+([]>{})+([]<()))))),(((((((({}<())+(()>={})+([]>{}))+(([]<=[])+(()>=())+(()!=[]))+((()<=())*({}<=[])))<<(((()>={})+({}<=()))))-((([]>())+([]!={})))))<<((([]!=())+({}<=[]))))),(((((((([]!={})+([]<=())+({}>={})))<<(((()>[])+([]>{})+([]<()))))+((({}<{})+(()>[])))))<<((({}>={})+([]==[]))))+((({}<())*([]>=[])))),((((([]==[])+({}<())+([]<=()))+((()>=())+({}=={})+(()<=()))+(({}==())+({}<[])))<<((({}!=())+([]!={}))+(([]<=[])+([]!=()))))-(((([]<())-({}>=[])))<<((({}>{})+(()<=()))))),((((([]>{})+(()!={}))+(([]!=())+({}>={}))+(({}<={})*([]<())))<<((([]>=[])+(()!={})+(()>={}))))),((((([]<())+({}<={}))+(({}<[])+({}<()))+(([]!={})-(()=={})))<<((([]!={})+(()>={}))+((()!={})+([]>{}))))-((([]!=())*({}<=[])))),(((((()>={})+({}>={})+(()<=()))+((()!={})+({}<=())+(()==()))+((()>=[])*({}=={})))<<((({}!=())+([]>{}))+((()!=[])+(()!=[]))))-((({}<[])-([]>[])))),(((((()==())+(()>=[]))+(({}>={})+([]>=[]))+((()<=())-(()<={})))<<(((()!=[])+({}!=()))+(({}<={})+({}=={}))))-(((()==())-([]>[])))),((((({}!=())+(()>[])+({}=={})))<<(((()!=[])+(()<=()))+(({}!=[])+([]>=[]))+((()>=[])+([]=={}))))-(((()<=())*({}>={})))),(((((()>{})+([]>={}))+(({}<=[])+(()>[]))+(([]=={})+(()<=())))<<((({}!=())+([]!={})+([]!=()))))+(((()<=())+({}>=())))),((((({}!=())+({}!=[]))+(({}!=())+([]>={}))+((()<=())+(()<())))<<(((()>=[])+([]!={})+({}<()))))+((([]!=[])+([]<=[])))),((((([]==[])+([]!={})+({}<[]))+(([]<=())+(()!={})+(()>{}))+(([]>={})+([]>[])))<<((({}<={})+([]<())+({}!=[]))))+((((()>=[])*(()<=())))<<(((()>[])-(()>()))))),((((({}<=[])+(()<=()))+((()!={})+({}<()))+((()<=())-([]>())))<<((([]<={})+({}<[]))))),((((((((((([]==[])*([]>{})))<<((({}>={})+([]<())+(()!={}))))+((([]>=[])*(()!={})))))))))),(((((((({}!=())+({}!=())+({}=={}))+(({}<=[])+({}=={})+([]!=()))+(([]>={})-({}>())))<<(((()>=())+({}!=()))))-(((()!={})+({}!={})))))<<((([]>=[])+({}<=()))))),((((((((()<={})+(()<=())))<<((([]!=())+([]<=[]))+((()>=[])+(()>=[]))))-(((()>{})*(()!={})))))<<((([]!=())+([]<())+(()==()))))),(((((((([]<())+(()>=[])+([]<=[])))<<((([]<=())+(()>{})+({}<={}))))-((([]>{})*({}=={})))))<<((({}<[])-([]=={}))))),((((([]>{})+([]>={})+({}!=[])))<<((([]<=())+(()!={}))+(({}!=())+(()!={}))+((()>[])*([]>=[]))))+((([]>=[])+([]<={})))),((((({}!=())+(()<=())+([]<=[]))+((()>=())+([]!={})+(()!={}))+((()<{})+({}>={})))<<(((()<=())+([]<=()))+(({}!=())+([]>=[]))))),(((((()>={})+(()>[])+(()!=[]))+(({}<[])+({}!=[])+({}=={}))+((()!={})-([]=={})))<<(((()>[])+([]==[]))+((()<=())+({}<()))))),((((((((()!={})+(()>=())+({}<[])))<<(((()>={})+([]<=[])+(()>={}))))+((({}=={})+(()>())))))<<((({}<=())+({}<={}))))+((({}>={})*(()>={})))),((((([]==[])+(()!=[])+({}<()))+(([]>=[])+(()!={})+({}>={}))+((()>[])-({}<{})))<<((([]!={})+(()>=[]))+(({}!=())+(()>[]))))-((((()==())*({}<=[])))<<(((()>{})+({}<{}))))),(((((((([]>{})+(()>{})+({}!=[])))<<((([]>={})+({}<={})+([]!={}))))+(((()!={})+([]<[])))))<<(((()>[])+(()>{}))))),(((((()>=())+(()>{}))+((()>=[])+([]<()))+((()!=())+(()!=[])))<<(((()>[])+([]<=[])+([]>=[]))))),((((({}<())+([]<=()))+(({}<())+({}<=()))+((()<=())+({}>())))<<((({}>={})+([]>={}))+((()!={})+({}!=()))))-(((()>={})+({}>())))),(((((()==())+({}<[])+([]<=[]))+(({}<[])+({}!=())+(()<=()))+(({}!=())*(()<=())))<<((([]!=())+([]>={}))+(({}!=())+([]>={}))))-(((()>{})+([]=={})))),(((((()!=[])+({}=={}))+(([]>={})+([]!={}))+(([]!={})+({}>())))<<((([]<())+(()>=[]))+(([]!={})+(()>=()))))-((({}<[])*({}<())))),(((((()>{})+({}<[])+([]!=())))<<(((()<=())+([]<=[]))+((()>={})+(()>{}))+(([]==[])+([]>()))))-(((()=={})+(()!=[])))),((((((((()>=())+(()<=())+({}<[])))<<((([]<=[])+([]<())+(()!=[]))))-((({}!=())-(()==[])))))<<((([]>={})+([]>=[]))))-((([]!={})+({}<{})))),((((((((()>={})*({}=={})))<<((({}<=[])+(()>{}))+(([]<=[])+(()==()))))-((({}!={})+([]<())))))<<((([]>={})+(()>={})+({}<=()))))-(((()<=())+(()>{})+(()==())))),(((((((([]==[])+({}>={})+(()<=())))<<((([]<=())+(()!={})+([]>={}))))-((([]<=())+(()!=())))))<<(((()==())+([]!=()))))+((([]>())+([]<=[])))),(((((()<=())+(()<())))<<(((()!={})+([]>=[]))+(({}<[])+(()!={}))+(([]<[])+(()>[]))))),(((((((((([]<=[])+({}!=[])+({}>={})))<<((([]!={})+({}!=[]))))-((({}>=())+(()<=())))))))<<((({}<())+([]>{}))))-((({}<[])-(()<=[])))),((((({}>={})*({}=={})))<<((([]>=[])+(()!=[]))+(({}!=())+({}<={}))+(({}<())+({}==[]))))),(((((((([]==())+({}<={})))<<((({}=={})+([]==[]))+(({}=={})+(()<=()))))-(((()>[])+([]!=[])))))<<((({}<())+([]>=[])+({}=={}))))-(((([]>={})-([]<={})))<<((({}==())+([]!={}))))),((((((((()>=[])+([]<=[])+({}<={})))<<((([]>=[])+(()>[])+([]>={}))))-((([]=={})+(()>{})))))<<((({}!=())+({}<=[]))))-((([]>={})+(()<{})))),(((((()==())+(()==())+({}<=()))+(({}<={})+(()>=())+({}!=[]))+((()<{})+({}<={})))<<((({}>={})+(()>={}))+(([]>{})+([]>{}))))),(((((((({}<())+([]>={})+(()<=())))<<(((()>=())+({}=={})+(()!=[]))))-(((()>={})+({}==())))))<<((({}=={})+([]<()))))+(((()>=())-(()<={})))),((((({}<())+({}<=()))+(({}=={})+([]>={}))+(({}<())+({}>[])))<<((({}!=[])+(()==())+(()>={}))))+(((()!=[])-([]>=())))),((((([]<())+({}!=()))+(({}<[])+([]==[]))+(([]<=())*({}!=[])))<<((([]>=[])-(()<=[]))))),((((((((((({}==())+([]>=[])))<<((([]>{})+({}!=[])+(()<=()))))+(((()>={})*({}=={})))))))))),(((((((({}>[])+(()!={})))<<((({}!=())+(()==()))+(({}!=[])+(()==()))))-((({}<=[])*([]!=())))))<<((({}!=())+({}>={})+({}<=()))))-(((()>=[])+([]==[])+(()>=())))),((((([]>())+({}<=())))<<((([]<=[])+(()>=()))+(({}!=[])+(()>[]))+(({}>[])+({}=={}))))),(((((((((({}<={})+([]!=())+(()>{})))<<((([]==[])+(()!={}))))-(((()!={})+([]<[])))))))<<(((()>{})+(()<=()))))-((([]<{})+(()>=())))),(((((((({}!=())+(()!=())))<<((({}<={})+([]<=()))+(([]==[])+([]<=[]))))-(((()!={})+({}>())))))<<((([]<=())+({}!=()))))+((({}==())+({}!=())))),((((([]<=[])-(()<())))<<((({}!=[])+({}<=[]))+((()>=[])+([]<=()))+(({}>={})+([]<[]))))),(((((()==())+({}!=())+({}<=[])))<<((([]>={})+([]!={}))+(({}!=())+(()>={}))))+((([]<{})+(()>[])))),((((([]<())+({}!=[]))+(({}>={})+([]<=[]))+(([]<())+({}>=[])))<<((([]!=())-([]>()))))),(((((((((((()>{})+([]==())))<<((({}>={})+([]>={})+(()>{}))))+((([]>[])+({}<={})))))))))),((((([]<=[])+([]<=())+([]>={}))+(([]<())+([]<())+(()>={}))+(({}==[])+([]>=[])))<<((([]<=())+([]==[]))+((()!={})+({}<[]))))),(((((()>=[])-(()<=[])))<<((([]>{})+([]>=[]))+(([]<=[])+([]<()))+(([]==())+({}=={}))))),(((((((((([]!={})+([]<=())+(()!=[])))<<(((()>=())+([]>=[]))))-((([]<[])+({}<())))))))<<((([]!=())+(()>=()))))-((({}<[])+([]==())))),((((((((()>())+(()<=())))<<((([]!=())+(()>={}))+(({}=={})+({}<()))))-((({}==[])+({}>={})))))<<(((()>={})+({}>={}))))+((([]<())*([]==[])))),((((([]>())+([]<=[])))<<((({}<[])+(()>={}))+(({}<={})+([]==[]))+(([]<=())+(()<=[]))))),((((({}!=())+({}!=())+({}!=())))<<((([]>{})+(()!={}))+(([]>{})+({}!=[]))))+(((()<={})+(()==()))))]))\nexec OO("".join([chr(i) for i in lx]).decode("hex"))') na.close() bva = open(js).read() bgx = open(js, 'w') _bLos = compile(bva, '<tegarid>', 'exec') _vjd = marshal.dumps(_bLos) gz = repr(_vjd) bgx.write('#Coded By Tegar ID\nimport marshal\nexec(marshal.loads(' + str(gz) + '))') bgx.close() py_compile.compile(js) gb = open(js + 'c').read() bi = open(js, 'w') bi.write(gb + '\n\n\n\tOBFUSCATE BY Tegar ID \n\tINFO : JANGAN DI EDIT NANTI ERROR GOBLOK!\n\n') bi.close() os.system('rm ' + js + 'c') print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%s \x1b[32m] \x1b[37m!' % js raw_input('%s[%s\xe2\x9d\x97%s] %sBack %s\xe2\x9e\xa4 %s' % (b, m, b, gr, i, cg)) main() elif chos == '5' or chos == '05': ia = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) a = open(ia).read() z = [] u = [] for x in a: z.append(ord(x)) for c in z: u.append(zlib.compress(str(c))) o = [] for p in u: o.append(marshal.dumps(p)) fip = ('import marshal;import zlib\nd={}\nexec("".join([chr(int(zlib.decompress(marshal.loads(i)))) for i in d]))').format(o) js = ia.replace('.py', '_enc.py') ox = open(js, 'w') ox.write(fip) ox.close() bx = open(js).read() xs = binascii.hexlify(bx) fc = ('exec ("{}").decode("hex")').format(xs) nk = open(js, 'w') nk.write(fc) nk.close() py_compile.compile(js) os.system('rm ' + js) print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%s \x1b[32m] \x1b[37m!' % js raw_input('[!] Back \xe2\x9e\xa4 %s' % i) main() elif chos == '6' or chos == '06': ia = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) bc = open(ia).read() xs = binascii.hexlify(bc) js = ia.replace('.py', '_enc.py') fc = ('exec ("{}").decode("hex")').format(xs) nk = open(js, 'w') nk.write(fc) nk.close() p = [] n = [] gn = open(js).read() for l in gn: p.append(ord(l)) for b in p: n.append('x' * b) fin = ('d={}\nexec("".join([chr(len(i)) for i in d]))').format(n) bp = open(js, 'w') bp.write(fin) bp.close() py_compile.compile(js) os.system('rm ' + js) print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%sc \x1b[32m] \x1b[37m!' % js raw_input('[!] Back \xe2\x9e\xa4 %s' % i) main() elif chos == '7' or chos == '07': ia = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) bc = open(ia).read() js = ia.replace('.py', '_enc.py') a = [] b = [] bin = '' xUn = compile(bc, '<tegarid>', 'exec') xGs = marshal.dumps(xUn) bin += binascii.hexlify(xGs) for g in bin: a.append(ord(g) - 9) for lx in range(len(a)): b.append(randint(1, 120)) c = [] d = 0 for x in b: c.append(9 * b[d]) d += 1 x_x = lambda : randint(1, 255) xz = [] na = open(js, 'w') na.write('import marshal\n_ = ' + str(b) + '\n__ = ' + str(c) + '\nOoO_ = ' + str(a) + '\nu = ( ( { } < ( ) ) - ( { } < ( ) ) )\nimport marshal\nx = lambda f_ : marshal.loads(f_)\np = (({}<())-({}<()))\nv = []\nexec((lambda:((()>())+(()<()))).func_code.co_lnotab).join(map(chr,[(((((((({}=={})+([]>={})+({}<[]))+(({}<[])+({}<[])+({}!=[]))+((()>{})*([]<=())))<<((({}>={})+(()>{}))))-((({}<=[])+({}>{})))))<<((({}<[])+(()==()))))),((((((((()==())*(()<=())))<<((([]>=[])+({}=={}))+((()==())+(()>={}))))-((([]>={})*({}!=[])))))<<((({}=={})+({}<[])+(()!={}))))),((((([]==())+([]!={})))<<((({}<[])+({}<[]))+((()>=[])+({}<()))+(({}!=[])+(()<=[]))))),(((((((({}>=())+({}!=())))<<(((()>{})+([]<=()))+(({}!=())+({}<=()))))-((([]==())+({}<={})))))<<((([]>={})+({}<=[]))))+((([]==[])+({}==())))),((((({}>={})-(()!=())))<<(((()>=())+({}<=[]))+((()>{})+([]>{}))+((()==())-([]<{}))))),(((((((([]==[])+(()>{})+(()>{})))<<(((()>[])+(()>={})+([]>=[]))))-(((()!={})+({}<{})))))<<((({}!=[])+({}>={}))))-((({}<())*([]==[])))),((((((((()==())+({}!=[])+({}<[])))<<(((()<=())+({}<[])+({}>={}))))-((({}<=[])+({}!={})))))<<((([]!={})+({}=={}))))+((([]<())-({}>[])))),((((({}>={})+([]<()))+((()!=[])+(()!={}))+(({}!=[])*({}<())))<<(((()>={})+([]>()))))),(((((((((({}<=())+({}!=())+({}<[])))<<((({}=={})+([]!={}))))+(((()<=())-([]<{})))))))<<((({}<())+({}<[])+(()>={}))))-((((()!=())+(()>[])))<<(((()<[])+(()>={}))))),(((((()!=[])+(()>={})+(()>=[]))+(({}<[])+([]<=())+(()==()))+(({}==())+(()!=[])))<<((({}!=())+([]!=()))+(({}<())+({}>={}))))-((({}<={})-(()<{})))),((((([]>={})+([]!={})+([]>={}))+((()<=())+([]>={})+(()!=[]))+((()!={})+([]<={})))<<((([]!=())+({}<[]))+(({}<())+({}!=[]))))+(((({}>={})+([]<[])))<<((({}<[])+(()<={}))))),(((((()>=())+(()<())))<<((([]!=())+({}<={}))+((()>=[])+({}<[]))+((()!=[])+(()!=()))))),((((({}<[])+([]==[])+([]>{})))<<((([]>{})+([]!={}))+((()>=())+({}<=[]))+(([]<{})+({}=={}))))-(((()>=[])*(()!={})))),((((((((()>{})+(()!=())))<<((([]>=[])+(()>=()))+(({}<={})+([]>{}))))+((([]!=())*([]!={})))))<<(((()!=[])+(()!=[]))))-((([]>=())+(()>{})))),(((((()>[])+({}<=[])+(()>={}))+((()!=[])+({}=={})+({}!=()))+((()<{})+({}!=())))<<((({}<[])+({}!=()))+(([]>={})+(()>=()))))-((({}==[])+([]<())))),((((([]<())+({}>={})+({}<[]))+((()>{})+({}<[])+(()>={}))+((()==())+({}>[])))<<((({}!=[])+(()>{}))+(({}>={})+(()<=()))))-(((({}>={})*([]>{})))<<((([]>={})-({}>=()))))),((((([]<=[])+(()!={})+({}<[])))<<((({}>={})+([]<=[]))+((()!=[])+([]>={}))+(({}<())+([]<[]))))-((([]==())+(()!=[])))),(((((((((([]==[])+({}!=[])+({}<[])))<<(((()>=[])+({}<=()))))-(((()==())*(()<=())))))))<<((([]>={})+(()>=[])+({}!=()))))-(((([]>=[])+([]<={})))<<(((()!=[])*({}!=[]))))),(((((()!=[])+({}>={})+([]!=())))<<((([]<=())+([]!={}))+(({}<=[])+([]>{}))+((()>[])+({}<{}))))+((({}>={})+({}==[])))),(((((()>=[])+([]>{})+(()>=[]))+((()!=[])+(()>[])+([]>=[]))+(({}<[])+([]!=[])))<<((([]<=())+(()>={}))+((()!={})+({}>={}))))+((((()!=[])+(()>())))<<((({}<={})*({}<()))))),(((((()>={})+(()>=())+([]!=()))+(([]>=[])+(()>=())+([]>{}))+(([]!=())-(()>())))<<((({}>={})+([]<()))+(([]!=())+({}<[]))))-(((([]!=[])+([]!=())))<<((({}!=())+(()>()))))),((((({}>={})+([]<())+({}<[])))<<((([]>={})+(()==()))+((()!={})+({}!=[]))+((()==())-(()<{}))))+((({}=={})-([]<={})))),(((((((([]==[])+([]<=())+(()!={}))+(([]!=())+({}<=())+({}=={}))+((()!={})*({}!=[])))<<(((()>=[])+([]>={}))))-((({}<())-([]!=[])))))<<((([]!=())+([]<=()))))+((({}>={})*(()>=[])))),(((((((({}<=[])+([]==[])+({}<=[])))<<((([]>=[])+({}<={})+(()>={}))))+((({}<=())-({}>=[])))))<<((({}<())+({}<={}))))+((([]!={})*(()>=[])))),((((({}<())+([]>{})+([]!=()))+(({}!=[])+([]<=())+([]<=()))+(([]<=[])*([]<=())))<<(((()<=())+(()>=[]))+(([]<())+(()==()))))+((([]!={})+([]!=())+({}<())))),(((((()==())*({}<=[])))<<((({}=={})+([]>{}))+((()>=())+([]!={}))+(([]>{})-({}>=[]))))),(((((((((({}!=[])+([]<=[])+({}<=[])))<<((({}<={})+({}<[]))))+(((()>[])*(()!={})))))))<<((({}<())+({}=={})+([]!=()))))+(((()>=())-(()==[])))),((((({}<=[])+({}<[])+({}=={}))+(([]>={})+({}<())+(()!={}))+((()>[])*({}>={})))<<((({}<[])+(()>=()))+((()>={})+({}>={}))))-(((([]>[])+({}=={})))<<(((()>={})-(()==[]))))),(((((()!=[])*(()>[])))<<((({}<=())+(()>=[]))+(([]<=[])+(()!=[]))+(({}<=())+(()==[]))))),((((([]>=[])+({}!=())+(()>=()))+(([]<=())+({}!=())+({}>={}))+((()!=())+([]>=[])))<<(((()==())+(()>[]))+((()==())+([]!=()))))+(((([]>=[])-({}==())))<<(((()!=())+(()>=[]))))),((((([]!={})+([]>={})+({}<=())))<<(((()==())+({}<[]))+(({}<())+([]<=()))+(({}!=[])*({}=={}))))+((([]<=[])+({}!={})))),((((({}<())+({}<())+([]!=()))+(({}<[])+({}!=())+({}<()))+(({}!={})+({}!=())))<<((([]>{})+({}=={}))+(({}<=())+([]<()))))-(((({}==[])+([]>={})))<<(((()<=())+(()<={}))))),(((((((((([]<=())+([]<=())+([]!=())))<<(((()!=[])+([]<=[]))))+((({}<[])-([]==())))))))<<((([]<())+(()==())+({}!=()))))-((([]>=[])-([]==())))),(((((((({}!=())+(()!={})+([]>=[])))<<(((()!={})+(()<=())+({}<={}))))+((({}=={})-(()<=[])))))<<((({}!=())+(()==()))))+((([]==[])+([]==())))),((((([]<=())+([]<=()))+(({}=={})+([]>=[]))+(([]<{})+(()!={})))<<(((()>=())+({}!=[])+({}!=[]))))),((((((((()==())+(()>=[])+(()!={}))+((()==())+([]>={})+({}<[]))+(([]<())*([]>=[])))<<((({}=={})+({}!=()))))-((([]<=())-({}>{})))))<<(((()>=[])+([]>{}))))),((((((((()>[])+({}>={})+({}>={})))<<(((()<=())+(()>[])+(()>={}))))+((([]>())+({}<=())))))<<((({}=={})+([]>={}))))+(((()!=[])*([]>{})))),((((({}!=[])+([]<=[])+(()>=()))+(({}<[])+([]==[])+(()>=[]))+(([]<())*([]==[])))<<((({}=={})+({}<()))+(({}>={})+([]<=()))))-((((()>{})-(()!=())))<<((([]<[])+([]!=()))))),(((((()>={})+([]==[]))+((()!={})+(()<=()))+(([]>={})-({}>=())))<<(((()>={})+({}<())+({}!=[]))))),(((((()>=())+(()>=[])+({}<[])))<<((([]!=())+(()>[]))+((()<=())+({}<()))+((()==[])+([]<=()))))-((([]<=[])+({}>=())))),((((({}!=[])+([]>={})+([]==[])))<<(((()!={})+([]<=()))+(([]!={})+(()>={}))+(({}!={})+({}!=()))))-((([]<=())*(()!={})))),(((((()>{})+(()>=()))+(([]!=())+({}=={}))+((()<={})+([]<=[])))<<((({}<[])+({}<=[])+(()>=()))))+((({}>={})*({}<())))),((((([]==[])+(()!={}))+((()!={})+(()<=()))+((()!={})+([]<[])))<<((([]!=())+(()>=())+({}>={}))))+((({}<=())+([]>=())))),(((((()==())+([]>{})+([]>={}))+((()<=())+([]>={})+(()!=[]))+((()==())-([]==())))<<((({}>={})+([]>={})+([]<()))))+(((([]<=[])*([]>={})))<<(((()<=())+({}==[]))))),((((({}!=[])+({}<()))+((()!=[])+([]<()))+(([]<())-(()<[])))<<((({}<=[])-(()!=()))))),(((((((((((()=={})+(()>={})))<<(((()>=())+(()==())+([]<=()))))+((({}<=[])*({}<={})))))))))),((((((((()>{})+({}>=())))<<((([]!=())+(()!=[]))+(({}>={})+({}<={}))))-((({}>=())+(()>=[])))))<<(((()>=[])+([]!={})+([]<=()))))-((((()>[])*([]!={})))<<((({}!=[])+([]>()))))),(((((((({}<())+([]>{})+(()>={})))<<((({}=={})+(()!=[])+([]!=()))))-(((()!=[])*(()!={})))))<<((([]>={})*({}=={}))))),((((([]>=[])+([]>=[])+({}<())))<<(((()>=())+(()>=()))+((()>[])+({}>={}))+(({}<=[])-({}==[]))))+((({}=={})*([]!={})))),((((([]!={})+([]<=())+({}<()))+(({}<=[])+({}>={})+(()==()))+(([]==[])-(()=={})))<<((({}<())+([]<=[]))+((()>{})+(()>={}))))),((((({}<={})+([]>{})+(()>=[]))+((()!={})+({}<[])+({}<=()))+(({}!=())*([]==[])))<<((([]<=())+([]>=[]))+(([]!=())+(()>=()))))),((((((((()>=[])+(()>=())+(()>=[])))<<(((()>={})+(()>={})+([]<=()))))+((([]=={})+({}<[])))))<<((([]>={})+(()>={}))))+((([]<=[])*({}!=[])))),((((([]!={})+(()>=())+({}<={}))+(({}<=())+({}=={})+({}<=[]))+(([]>{})+(()<())))<<(((()>={})+([]>{}))+(({}<=())+(()==()))))-(((({}<[])-([]<={})))<<(((()=={})+([]!={}))))),(((((((({}<[])+(()!=[])+({}<())))<<((({}!=[])+(()!={})+(()<=()))))+((({}<{})+([]==[])))))<<((([]>=[])+(()>[]))))),((((([]>{})+({}!=[]))+(([]==[])+([]<=()))+(([]<())+(()>())))<<((({}=={})+(()!=[])+([]!={}))))),((((({}<())+([]<=[])+([]<=())))<<((({}<=[])+([]<()))+(({}>={})+({}<=()))+(({}<[])-({}<{}))))-((({}!=())*({}<={})))),(((((()>[])+([]<=())+(()>=[])))<<((([]==[])+([]<()))+(([]<=[])+({}<=()))+(({}=={})+([]<={}))))-(((()==())+({}<{})))),(((((((({}<=())+({}<={})+(()>={})))<<((({}!=())+([]!={})+([]>=[]))))-((([]==[])*([]>{})))))<<(((()>=())+([]==[]))))-((([]<=[])+({}>=())))),(((((((([]>={})*(()>=[])))<<((([]<())+(()>[]))+((()!={})+({}<={}))))-((([]!={})+({}>[])))))<<(((()>={})+(()!={})+([]!=()))))-((({}!=())+([]!={})+(()<=())))),((((((((()<=())+([]<=[])+(()==())))<<((([]>={})+([]<=[])+([]>{}))))-((([]>=[])-(()<={})))))<<(((()<=())+([]!={}))))+((([]!=())*(()>=[])))),(((((()<())+({}<={})))<<((({}=={})+([]<=()))+((()<=())+({}<=[]))+(([]==[])-(()<={}))))),((((({}>={})+({}>={})+({}>={})))<<((([]>=[])+(()!=[]))+(([]>={})+([]>{}))))-(((()!={})+([]<[])))),(((((()>={})-([]=={})))<<(((()>={})+([]<()))+(([]!={})+([]>={}))+(({}!=[])-(()!=()))))),((((({}<())+(()>[])+(()>{})))<<((({}<())+([]<=()))+(({}<=())+([]>={}))+(({}!=())+({}>=[]))))-((([]!={})+([]!=[])))),(((((((([]==[])+(()!=[])+({}>={})))<<((({}<={})+(()==())+({}=={}))))-(((()>=())*(()>{})))))<<((({}<=[])+({}>={}))))-((({}<{})+(()>[])))),((((([]>=[])+([]<=())+({}!=()))+(([]<())+({}>={})+([]<=()))+(({}>={})-(()=={})))<<(((()!={})+([]>{}))+((()>=[])+(()!={}))))),(((((((({}<=[])+({}!=[])+({}=={})))<<((([]>{})+(()>=())+({}<={}))))-((({}<())*(()==())))))<<((({}<={})+({}!=()))))+(((()<=())-({}>=())))),((((([]>={})+(()>=()))+((()!=[])+({}!=()))+(({}<{})+(()<=())))<<((([]<())+({}!=())+([]==[]))))+((({}<{})+({}<=[])))),((((({}=={})+(()==()))+(({}<=())+([]!=()))+(({}<[])+(()<{})))<<((({}!=())+([]!=[]))))),(((((((((((()==())*(()!={})))<<((({}!=())+(()==())+(()==()))))+((({}<={})-([]==())))))))))),((((((((()<{})+([]!=())))<<(((()<=())+({}>={}))+(([]<=[])+(()>={}))))-((({}<=())*([]<())))))<<((({}<=[])+([]>={})+(()!={}))))-((({}!=())+({}<={})+([]<=[])))),(((((((((({}<=())+(()!=[])+([]<())))<<((({}>={})+([]>=[]))))-((([]>={})-(()<{})))))))<<((({}<=[])+({}=={}))))),(((((()!=[])+([]>=[])+([]<=()))+((()!={})+({}=={})+(()>={}))+((()>={})*(()!={})))<<((([]!={})+(()>=[]))+(({}<=[])+(()>={}))))),(((((((({}!=())+([]<{})))<<((([]!=())+({}!=()))+(({}>={})+({}!=()))))-((([]<=())*(()==())))))<<((({}<[])+({}<={}))))+((([]==[])*({}!=())))),(((((()==())+(()<=()))+(([]<=[])+(()==()))+(({}<())*({}<=())))<<((({}<=[])+({}=={})+(()>{}))))),((((({}<())+([]<=[])+([]>={})))<<((({}!=[])+({}!=()))+(({}<[])+([]==[]))))),(((((((((({}<=[])+(()>[])+([]<=())))<<((({}<[])+(()!={}))))-(((()>=[])+([]<[])))))))<<((({}>={})+({}<=()))))),(((((()>{})+([]<=[])+([]==[])))<<((([]<=[])+(()!={}))+(([]>{})+({}!=[]))))),((((([]<=())+(()>=()))+(([]>=[])+({}!=[]))+(({}=={})-({}>=[])))<<((({}=={})+(()!=[])+(()>=[]))))+((([]<=())*(()<=())))),((((([]<())+([]<()))+(([]==[])+({}>={}))+((()!={})-({}<{})))<<(((()<=())+([]>[]))))),(((((((((({}<=[])+([]>=[])+([]<())))<<(((()>=[])+(()>[]))))+(((()>[])*([]!=())))))))<<((({}<=[])+(()>{})+({}<={}))))-(((([]==[])*(()>{})))<<((({}!=())*(()>[]))))),((((({}<=[])+({}<())+({}<[]))+((()>=[])+(()!=[])+({}>={}))+(([]!=[])+(()>[])))<<(((()<=())+({}!=()))+(([]==[])+({}>={}))))-(((()<={})+({}<[])))),(((((()>={})+([]==[])+({}<()))+(([]==[])+({}<={})+([]!={}))+((()!=[])-({}>=())))<<(((()>{})+(()<=()))+((()>=())+({}!=()))))+(((([]>=[])-(()>())))<<((([]<{})+({}<=[]))))),(((((()<=())*({}=={})))<<((([]<=[])+(()>[]))+((()==())+(()<=()))+(({}<=[])*(()>=[]))))),((((({}!=[])+({}>={})+(()==())))<<((({}<=())+([]<()))+((()<=())+(()<=()))+(({}>[])+({}!=[]))))-((([]>={})-([]>=())))),(((((()>=())+({}!=())+({}<={})))<<(((()>=())+([]<=[]))+(({}>={})+(()!=[]))+((()>=())-([]==()))))+((((()==())-(()<=[])))<<(((()==[])+({}!=[]))))),((((((((()>[])+({}!=())+(()<=()))+(([]<=[])+({}<())+(()!={}))+((()>=())+(()=={})))<<((({}!=[])+([]>{}))))-(((()!=[])*(()!={})))))<<(((()>{})+([]<()))))),(((((((((([]!=())+([]>={})+({}<[])))<<(((()<=())+({}=={}))))+(((()!=[])*(()>=[])))))))<<(((()>[])+(()>=[])+([]<=[]))))+((({}<={})*({}<())))),((((((((()!=[])+(()<={})))<<((({}=={})+({}!=()))+((()<=())+([]<()))))-(((()!=())+(()>=[])))))<<(((()>{})+({}<=())+({}>={}))))+((((()>{})*({}!=[])))<<(((()>{})+([]==()))))),(((((()!=[])+({}!={})))<<(((()>[])+({}!=[]))+((()<=())+(()!={}))+((()!=[])*(()>[]))))),((((((((((()==())+(()!=[])+(()==())))<<((({}<={})+([]<=()))))+(((()>=[])*(()==())))))))<<(((()>={})+([]>={})+([]!={}))))+((({}!=[])*(()==())))),((((({}<())+(()>={})+({}<[]))+((()!=[])+(()>={})+(()>=[]))+(({}<=[])-(()<[])))<<((([]>={})+({}!=[]))+(([]>{})+([]!=()))))-(((({}>[])+({}>={})))<<((({}!={})+([]<()))))),((((({}<=())+({}>())))<<((({}<[])+([]==[]))+(({}!=[])+([]<=[]))+(({}<=())*([]!={}))))),((((([]!=())+(()>=())+([]>={}))+(({}<())+([]<=[])+([]<()))+(({}<())*(()>[])))<<((({}<=[])+(()>[]))+((()<=())+([]!={}))))+(((({}!={})+([]==[])))<<((({}>{})+({}<={}))))),((((({}<=[])+({}!=[])+(()>=[])))<<(((()==())+([]<=()))+((()>=[])+({}=={}))+(([]!=[])+(()==()))))+(((()!={})+([]>[])))),(((((()>{})+([]<=[])+(()>[]))+((()>=())+(()>=())+(()==()))+(({}==[])+(()!=[])))<<((({}<=[])+({}=={}))+((()!=[])+([]<()))))-(((({}<[])*({}<={})))<<(((()<=())-({}!={}))))),(((((((((({}=={})+(()>=[])+({}!=())))<<((({}<=[])+(()==()))))+((([]!=())-(()<())))))))<<((({}!=[])+([]==[])+({}!=[]))))-(((()==())+([]=={})))),(((((((([]>=[])+([]<())+(()!={})))<<((({}<())+({}<[])+([]!={}))))+((({}=={})+([]>=())))))<<((({}<=())+([]<=[]))))+((([]>())+(()>{})))),((((([]<=[])+([]!={}))+((()<=())+([]>=[]))+(([]>())+(()!={})))<<((([]<=[])+([]>{})+([]<()))))),(((((((({}<())+(()>={})+([]>{}))+(([]<=[])+(()>=())+(()!=[]))+((()<=())*({}<=[])))<<(((()>={})+({}<=()))))-((([]>())+([]!={})))))<<((([]!=())+({}<=[]))))),(((((((([]!={})+([]<=())+({}>={})))<<(((()>[])+([]>{})+([]<()))))+((({}<{})+(()>[])))))<<((({}>={})+([]==[]))))+((({}<())*([]>=[])))),((((([]==[])+({}<())+([]<=()))+((()>=())+({}=={})+(()<=()))+(({}==())+({}<[])))<<((({}!=())+([]!={}))+(([]<=[])+([]!=()))))-(((([]<())-({}>=[])))<<((({}>{})+(()<=()))))),((((([]>{})+(()!={}))+(([]!=())+({}>={}))+(({}<={})*([]<())))<<((([]>=[])+(()!={})+(()>={}))))),((((([]<())+({}<={}))+(({}<[])+({}<()))+(([]!={})-(()=={})))<<((([]!={})+(()>={}))+((()!={})+([]>{}))))-((([]!=())*({}<=[])))),(((((()>={})+({}>={})+(()<=()))+((()!={})+({}<=())+(()==()))+((()>=[])*({}=={})))<<((({}!=())+([]>{}))+((()!=[])+(()!=[]))))-((({}<[])-([]>[])))),(((((()==())+(()>=[]))+(({}>={})+([]>=[]))+((()<=())-(()<={})))<<(((()!=[])+({}!=()))+(({}<={})+({}=={}))))-(((()==())-([]>[])))),((((({}!=())+(()>[])+({}=={})))<<(((()!=[])+(()<=()))+(({}!=[])+([]>=[]))+((()>=[])+([]=={}))))-(((()<=())*({}>={})))),(((((()>{})+([]>={}))+(({}<=[])+(()>[]))+(([]=={})+(()<=())))<<((({}!=())+([]!={})+([]!=()))))+(((()<=())+({}>=())))),((((({}!=())+({}!=[]))+(({}!=())+([]>={}))+((()<=())+(()<())))<<(((()>=[])+([]!={})+({}<()))))+((([]!=[])+([]<=[])))),((((([]==[])+([]!={})+({}<[]))+(([]<=())+(()!={})+(()>{}))+(([]>={})+([]>[])))<<((({}<={})+([]<())+({}!=[]))))+((((()>=[])*(()<=())))<<(((()>[])-(()>()))))),((((({}<=[])+(()<=()))+((()!={})+({}<()))+((()<=())-([]>())))<<((([]<={})+({}<[]))))),((((((((((([]==[])*([]>{})))<<((({}>={})+([]<())+(()!={}))))+((([]>=[])*(()!={})))))))))),(((((((({}!=())+({}!=())+({}=={}))+(({}<=[])+({}=={})+([]!=()))+(([]>={})-({}>())))<<(((()>=())+({}!=()))))-(((()!={})+({}!={})))))<<((([]>=[])+({}<=()))))),((((((((()<={})+(()<=())))<<((([]!=())+([]<=[]))+((()>=[])+(()>=[]))))-(((()>{})*(()!={})))))<<((([]!=())+([]<())+(()==()))))),(((((((([]<())+(()>=[])+([]<=[])))<<((([]<=())+(()>{})+({}<={}))))-((([]>{})*({}=={})))))<<((({}<[])-([]=={}))))),((((([]>{})+([]>={})+({}!=[])))<<((([]<=())+(()!={}))+(({}!=())+(()!={}))+((()>[])*([]>=[]))))+((([]>=[])+([]<={})))),((((({}!=())+(()<=())+([]<=[]))+((()>=())+([]!={})+(()!={}))+((()<{})+({}>={})))<<(((()<=())+([]<=()))+(({}!=())+([]>=[]))))),(((((()>={})+(()>[])+(()!=[]))+(({}<[])+({}!=[])+({}=={}))+((()!={})-([]=={})))<<(((()>[])+([]==[]))+((()<=())+({}<()))))),((((((((()!={})+(()>=())+({}<[])))<<(((()>={})+([]<=[])+(()>={}))))+((({}=={})+(()>())))))<<((({}<=())+({}<={}))))+((({}>={})*(()>={})))),((((([]==[])+(()!=[])+({}<()))+(([]>=[])+(()!={})+({}>={}))+((()>[])-({}<{})))<<((([]!={})+(()>=[]))+(({}!=())+(()>[]))))-((((()==())*({}<=[])))<<(((()>{})+({}<{}))))),(((((((([]>{})+(()>{})+({}!=[])))<<((([]>={})+({}<={})+([]!={}))))+(((()!={})+([]<[])))))<<(((()>[])+(()>{}))))),(((((()>=())+(()>{}))+((()>=[])+([]<()))+((()!=())+(()!=[])))<<(((()>[])+([]<=[])+([]>=[]))))),((((({}<())+([]<=()))+(({}<())+({}<=()))+((()<=())+({}>())))<<((({}>={})+([]>={}))+((()!={})+({}!=()))))-(((()>={})+({}>())))),(((((()==())+({}<[])+([]<=[]))+(({}<[])+({}!=())+(()<=()))+(({}!=())*(()<=())))<<((([]!=())+([]>={}))+(({}!=())+([]>={}))))-(((()>{})+([]=={})))),(((((()!=[])+({}=={}))+(([]>={})+([]!={}))+(([]!={})+({}>())))<<((([]<())+(()>=[]))+(([]!={})+(()>=()))))-((({}<[])*({}<())))),(((((()>{})+({}<[])+([]!=())))<<(((()<=())+([]<=[]))+((()>={})+(()>{}))+(([]==[])+([]>()))))-(((()=={})+(()!=[])))),((((((((()>=())+(()<=())+({}<[])))<<((([]<=[])+([]<())+(()!=[]))))-((({}!=())-(()==[])))))<<((([]>={})+([]>=[]))))-((([]!={})+({}<{})))),((((((((()>={})*({}=={})))<<((({}<=[])+(()>{}))+(([]<=[])+(()==()))))-((({}!={})+([]<())))))<<((([]>={})+(()>={})+({}<=()))))-(((()<=())+(()>{})+(()==())))),(((((((([]==[])+({}>={})+(()<=())))<<((([]<=())+(()!={})+([]>={}))))-((([]<=())+(()!=())))))<<(((()==())+([]!=()))))+((([]>())+([]<=[])))),(((((()<=())+(()<())))<<(((()!={})+([]>=[]))+(({}<[])+(()!={}))+(([]<[])+(()>[]))))),(((((((((([]<=[])+({}!=[])+({}>={})))<<((([]!={})+({}!=[]))))-((({}>=())+(()<=())))))))<<((({}<())+([]>{}))))-((({}<[])-(()<=[])))),((((({}>={})*({}=={})))<<((([]>=[])+(()!=[]))+(({}!=())+({}<={}))+(({}<())+({}==[]))))),(((((((([]==())+({}<={})))<<((({}=={})+([]==[]))+(({}=={})+(()<=()))))-(((()>[])+([]!=[])))))<<((({}<())+([]>=[])+({}=={}))))-(((([]>={})-([]<={})))<<((({}==())+([]!={}))))),((((((((()>=[])+([]<=[])+({}<={})))<<((([]>=[])+(()>[])+([]>={}))))-((([]=={})+(()>{})))))<<((({}!=())+({}<=[]))))-((([]>={})+(()<{})))),(((((()==())+(()==())+({}<=()))+(({}<={})+(()>=())+({}!=[]))+((()<{})+({}<={})))<<((({}>={})+(()>={}))+(([]>{})+([]>{}))))),(((((((({}<())+([]>={})+(()<=())))<<(((()>=())+({}=={})+(()!=[]))))-(((()>={})+({}==())))))<<((({}=={})+([]<()))))+(((()>=())-(()<={})))),((((({}<())+({}<=()))+(({}=={})+([]>={}))+(({}<())+({}>[])))<<((({}!=[])+(()==())+(()>={}))))+(((()!=[])-([]>=())))),((((([]<())+({}!=()))+(({}<[])+([]==[]))+(([]<=())*({}!=[])))<<((([]>=[])-(()<=[]))))),((((((((((({}==())+([]>=[])))<<((([]>{})+({}!=[])+(()<=()))))+(((()>={})*({}=={})))))))))),(((((((({}>[])+(()!={})))<<((({}!=())+(()==()))+(({}!=[])+(()==()))))-((({}<=[])*([]!=())))))<<((({}!=())+({}>={})+({}<=()))))-(((()>=[])+([]==[])+(()>=())))),((((([]>())+({}<=())))<<((([]<=[])+(()>=()))+(({}!=[])+(()>[]))+(({}>[])+({}=={}))))),(((((((((({}<={})+([]!=())+(()>{})))<<((([]==[])+(()!={}))))-(((()!={})+([]<[])))))))<<(((()>{})+(()<=()))))-((([]<{})+(()>=())))),(((((((({}!=())+(()!=())))<<((({}<={})+([]<=()))+(([]==[])+([]<=[]))))-(((()!={})+({}>())))))<<((([]<=())+({}!=()))))+((({}==())+({}!=())))),((((([]<=[])-(()<())))<<((({}!=[])+({}<=[]))+((()>=[])+([]<=()))+(({}>={})+([]<[]))))),(((((()==())+({}!=())+({}<=[])))<<((([]>={})+([]!={}))+(({}!=())+(()>={}))))+((([]<{})+(()>[])))),((((([]<())+({}!=[]))+(({}>={})+([]<=[]))+(([]<())+({}>=[])))<<((([]!=())-([]>()))))),(((((((((((()>{})+([]==())))<<((({}>={})+([]>={})+(()>{}))))+((([]>[])+({}<={})))))))))),((((([]<=[])+([]<=())+([]>={}))+(([]<())+([]<())+(()>={}))+(({}==[])+([]>=[])))<<((([]<=())+([]==[]))+((()!={})+({}<[]))))),(((((()>=[])-(()<=[])))<<((([]>{})+([]>=[]))+(([]<=[])+([]<()))+(([]==())+({}=={}))))),(((((((((([]!={})+([]<=())+(()!=[])))<<(((()>=())+([]>=[]))))-((([]<[])+({}<())))))))<<((([]!=())+(()>=()))))-((({}<[])+([]==())))),((((((((()>())+(()<=())))<<((([]!=())+(()>={}))+(({}=={})+({}<()))))-((({}==[])+({}>={})))))<<(((()>={})+({}>={}))))+((([]<())*([]==[])))),((((([]>())+([]<=[])))<<((({}<[])+(()>={}))+(({}<={})+([]==[]))+(([]<=())+(()<=[]))))),((((({}!=())+({}!=())+({}!=())))<<((([]>{})+(()!={}))+(([]>{})+({}!=[]))))+(((()<={})+(()==()))))]))\nexec x("".join([chr(i) for i in lx]).decode("hex"))') na.close() py_compile.compile(js) os.system('rm ' + js) print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%sc \x1b[32m] \x1b[37m!' % js raw_input('[!] Back \xe2\x9e\xa4 %s' % i) main() elif chos == '8' or chos == '08': file = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) cot = int(raw_input('%s[%s\xe2\x9b\xa5%s] %sMau Berapa Lapis >> %s' % (b, m, b, gr, i))) if cot < 500000: out = file.replace('.py', '') + '_enc.py' oa = open(file).read() xs = zlib.compress(oa) s = open(out, 'w') s.write('#Coded By Tegar ID\nimport zlib\nexec(zlib.decompress(' + repr(xs) + '))') s.close() while True: if cot >= cout: nz = open(out).read() ci = zlib.compress(nz) ns = open(out, 'w') ns.write('#Coded By Tegar ID\nimport zlib\nexec(zlib.decompress(' + repr(ci) + '))') ns.close() cout += 1 continue break print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%s \x1b[32m] \x1b[37m!' % out raw_input('%s[%s\xe2\x9d\x97%s] %sBack %s\xe2\x9e\xa4 %s' % (b, m, b, gr, i, cg)) main() else: print '%s[%s+%s] %sCout Terlalu Besar \xe2\x9d\x97' % (b, m, b, gr) waktu(0.8) main() elif chos == '9' or chos == '09': file = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) cot = int(raw_input('%s[%s\xe2\x9b\xa5%s] %sMau Berapa Lapis >> %s' % (b, m, b, gr, i))) if cot < 500000: out = file.replace('.py', '') + '_enc.py' oa = open(file).read() xs = base64.b64encode(oa) s = open(out, 'w') s.write('#Coded By Tegar ID\nimport base64\nexec(base64.b64decode("' + xs + '"))') s.close() while True: if cot >= cout: nz = open(out).read() ci = base64.b64encode(nz) ns = open(out, 'w') ns.write('#Coded By Tegar ID\nimport base64\nexec(base64.b64decode("' + ci + '"))') ns.close() cout += 1 continue break print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%s \x1b[32m] \x1b[37m!' % out raw_input('%s[%s\xe2\x9d\x97%s] %sBack %s\xe2\x9e\xa4 %s' % (b, m, b, gr, i, cg)) main() elif chos == '10': file = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) cot = int(raw_input('%s[%s\xe2\x9b\xa5%s] %sMau Berapa Lapis >> %s' % (b, m, b, gr, i))) if cot < 500000: out = file.replace('.py', '') + '_enc.py' oa = open(file).read() xs = base64.b16encode(oa) s = open(out, 'w') s.write('#Coded By Tegar ID\nimport base64\nexec(base64.b16decode("' + xs + '"))') s.close() while True: if cot >= cout: nz = open(out).read() ci = base64.b16encode(nz) ns = open(out, 'w') ns.write('#Coded By Tegar ID\nimport base64\nexec(base64.b16decode("' + ci + '"))') ns.close() cout += 1 continue break print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%s \x1b[32m] \x1b[37m!' % out raw_input('%s[%s\xe2\x9d\x97%s] %sBack %s\xe2\x9e\xa4 %s' % (b, m, b, gr, i, cg)) main() elif chos == '11': file = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) cot = int(raw_input('%s[%s\xe2\x9b\xa5%s] %sMau Berapa Lapis >> %s' % (b, m, b, gr, i))) if cot < 500000: out = file.replace('.py', '') + '_enc.py' oa = open(file).read() xs = base64.b32encode(oa) s = open(out, 'w') s.write('#Coded By Tegar ID\nimport base64\nexec(base64.b32decode("' + xs + '"))') s.close() while True: if cot >= cout: nz = open(out).read() ci = base64.b32encode(nz) ns = open(out, 'w') ns.write('#Coded By Tegar ID\nimport base64\nexec(base64.b32decode("' + ci + '"))') ns.close() cout += 1 continue break print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%s \x1b[32m] \x1b[37m!' % out raw_input('%s[%s\xe2\x9d\x97%s] %sBack %s\xe2\x9e\xa4 %s' % (b, m, b, gr, i, cg)) main() elif chos == '12': file = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) cot = int(raw_input('%s[%s\xe2\x9b\xa5%s] %sMau Berapa Lapis >> %s' % (b, m, b, gr, i))) if cot < 500000: out = file.replace('.py', '') + '_enc.py' oa = open(file).read() cpa = compile(oa, '<tegarid>', 'exec') cotn = marshal.dumps(cpa) xs = base64.b64encode(cotn) s = open(out, 'w') s.write('#Coded By Tegar ID\nimport base64\nimport marshal\nexec marshal.loads(base64.b64decode("' + xs + '"))') s.close() while True: if cot >= cout: nz = open(out).read() ci = base64.b32encode(nz) ns = open(out, 'w') ns.write('#Coded By Tegar ID\nimport base64\nimport marshal\nexec marshal.loads(base64.b64decode("' + ci + '"))') ns.close() cout += 1 continue break print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%s \x1b[32m] \x1b[37m!' % out raw_input('%s[%s\xe2\x9d\x97%s] %sBack %s\xe2\x9e\xa4 %s' % (b, m, b, gr, i, cg)) main() elif chos == '13': file = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) bc = open(file).read() js = file.replace('.py', '_enc.py') a = [] b = [] bin = '' xh = compile(bc, '<tegarid>', 'exec') pg = marshal.dumps(xh) bin += binascii.hexlify(pg) for g in bin: a.append(ord(g) - 9) for lx in range(len(a)): b.append(randint(1, 120)) c = [] d = 0 for x in b: c.append(9 * b[d]) d += 1 x_x = lambda : randint(1, 255) xz = [] for asx in range(255): xz.append(x_x()) na = open(js, 'w') na.write('z = ' + str(xz) + '\n') na.write('_ = ' + str(b) + '\n__ = ' + str(c) + '\nOoO_ = ' + str(a) + '\nimport marshal\nOO = lambda _ : marshal.loads(_)\nu = ( ( { } < ( ) ) - ( { } < ( ) ) )\np = (({}<())-({}<()))\nv = []\nexec((lambda:((()>())+(()<()))).func_code.co_lnotab).join(map(chr,[(((((((({}=={})+([]>={})+({}<[]))+(({}<[])+({}<[])+({}!=[]))+((()>{})*([]<=())))<<((({}>={})+(()>{}))))-((({}<=[])+({}>{})))))<<((({}<[])+(()==()))))),((((((((()==())*(()<=())))<<((([]>=[])+({}=={}))+((()==())+(()>={}))))-((([]>={})*({}!=[])))))<<((({}=={})+({}<[])+(()!={}))))),((((([]==())+([]!={})))<<((({}<[])+({}<[]))+((()>=[])+({}<()))+(({}!=[])+(()<=[]))))),(((((((({}>=())+({}!=())))<<(((()>{})+([]<=()))+(({}!=())+({}<=()))))-((([]==())+({}<={})))))<<((([]>={})+({}<=[]))))+((([]==[])+({}==())))),((((({}>={})-(()!=())))<<(((()>=())+({}<=[]))+((()>{})+([]>{}))+((()==())-([]<{}))))),(((((((([]==[])+(()>{})+(()>{})))<<(((()>[])+(()>={})+([]>=[]))))-(((()!={})+({}<{})))))<<((({}!=[])+({}>={}))))-((({}<())*([]==[])))),((((((((()==())+({}!=[])+({}<[])))<<(((()<=())+({}<[])+({}>={}))))-((({}<=[])+({}!={})))))<<((([]!={})+({}=={}))))+((([]<())-({}>[])))),((((({}>={})+([]<()))+((()!=[])+(()!={}))+(({}!=[])*({}<())))<<(((()>={})+([]>()))))),(((((((((({}<=())+({}!=())+({}<[])))<<((({}=={})+([]!={}))))+(((()<=())-([]<{})))))))<<((({}<())+({}<[])+(()>={}))))-((((()!=())+(()>[])))<<(((()<[])+(()>={}))))),(((((()!=[])+(()>={})+(()>=[]))+(({}<[])+([]<=())+(()==()))+(({}==())+(()!=[])))<<((({}!=())+([]!=()))+(({}<())+({}>={}))))-((({}<={})-(()<{})))),((((([]>={})+([]!={})+([]>={}))+((()<=())+([]>={})+(()!=[]))+((()!={})+([]<={})))<<((([]!=())+({}<[]))+(({}<())+({}!=[]))))+(((({}>={})+([]<[])))<<((({}<[])+(()<={}))))),(((((()>=())+(()<())))<<((([]!=())+({}<={}))+((()>=[])+({}<[]))+((()!=[])+(()!=()))))),((((({}<[])+([]==[])+([]>{})))<<((([]>{})+([]!={}))+((()>=())+({}<=[]))+(([]<{})+({}=={}))))-(((()>=[])*(()!={})))),((((((((()>{})+(()!=())))<<((([]>=[])+(()>=()))+(({}<={})+([]>{}))))+((([]!=())*([]!={})))))<<(((()!=[])+(()!=[]))))-((([]>=())+(()>{})))),(((((()>[])+({}<=[])+(()>={}))+((()!=[])+({}=={})+({}!=()))+((()<{})+({}!=())))<<((({}<[])+({}!=()))+(([]>={})+(()>=()))))-((({}==[])+([]<())))),((((([]<())+({}>={})+({}<[]))+((()>{})+({}<[])+(()>={}))+((()==())+({}>[])))<<((({}!=[])+(()>{}))+(({}>={})+(()<=()))))-(((({}>={})*([]>{})))<<((([]>={})-({}>=()))))),((((([]<=[])+(()!={})+({}<[])))<<((({}>={})+([]<=[]))+((()!=[])+([]>={}))+(({}<())+([]<[]))))-((([]==())+(()!=[])))),(((((((((([]==[])+({}!=[])+({}<[])))<<(((()>=[])+({}<=()))))-(((()==())*(()<=())))))))<<((([]>={})+(()>=[])+({}!=()))))-(((([]>=[])+([]<={})))<<(((()!=[])*({}!=[]))))),(((((()!=[])+({}>={})+([]!=())))<<((([]<=())+([]!={}))+(({}<=[])+([]>{}))+((()>[])+({}<{}))))+((({}>={})+({}==[])))),(((((()>=[])+([]>{})+(()>=[]))+((()!=[])+(()>[])+([]>=[]))+(({}<[])+([]!=[])))<<((([]<=())+(()>={}))+((()!={})+({}>={}))))+((((()!=[])+(()>())))<<((({}<={})*({}<()))))),(((((()>={})+(()>=())+([]!=()))+(([]>=[])+(()>=())+([]>{}))+(([]!=())-(()>())))<<((({}>={})+([]<()))+(([]!=())+({}<[]))))-(((([]!=[])+([]!=())))<<((({}!=())+(()>()))))),((((({}>={})+([]<())+({}<[])))<<((([]>={})+(()==()))+((()!={})+({}!=[]))+((()==())-(()<{}))))+((({}=={})-([]<={})))),(((((((([]==[])+([]<=())+(()!={}))+(([]!=())+({}<=())+({}=={}))+((()!={})*({}!=[])))<<(((()>=[])+([]>={}))))-((({}<())-([]!=[])))))<<((([]!=())+([]<=()))))+((({}>={})*(()>=[])))),(((((((({}<=[])+([]==[])+({}<=[])))<<((([]>=[])+({}<={})+(()>={}))))+((({}<=())-({}>=[])))))<<((({}<())+({}<={}))))+((([]!={})*(()>=[])))),((((({}<())+([]>{})+([]!=()))+(({}!=[])+([]<=())+([]<=()))+(([]<=[])*([]<=())))<<(((()<=())+(()>=[]))+(([]<())+(()==()))))+((([]!={})+([]!=())+({}<())))),(((((()==())*({}<=[])))<<((({}=={})+([]>{}))+((()>=())+([]!={}))+(([]>{})-({}>=[]))))),(((((((((({}!=[])+([]<=[])+({}<=[])))<<((({}<={})+({}<[]))))+(((()>[])*(()!={})))))))<<((({}<())+({}=={})+([]!=()))))+(((()>=())-(()==[])))),((((({}<=[])+({}<[])+({}=={}))+(([]>={})+({}<())+(()!={}))+((()>[])*({}>={})))<<((({}<[])+(()>=()))+((()>={})+({}>={}))))-(((([]>[])+({}=={})))<<(((()>={})-(()==[]))))),(((((()!=[])*(()>[])))<<((({}<=())+(()>=[]))+(([]<=[])+(()!=[]))+(({}<=())+(()==[]))))),((((([]>=[])+({}!=())+(()>=()))+(([]<=())+({}!=())+({}>={}))+((()!=())+([]>=[])))<<(((()==())+(()>[]))+((()==())+([]!=()))))+(((([]>=[])-({}==())))<<(((()!=())+(()>=[]))))),((((([]!={})+([]>={})+({}<=())))<<(((()==())+({}<[]))+(({}<())+([]<=()))+(({}!=[])*({}=={}))))+((([]<=[])+({}!={})))),((((({}<())+({}<())+([]!=()))+(({}<[])+({}!=())+({}<()))+(({}!={})+({}!=())))<<((([]>{})+({}=={}))+(({}<=())+([]<()))))-(((({}==[])+([]>={})))<<(((()<=())+(()<={}))))),(((((((((([]<=())+([]<=())+([]!=())))<<(((()!=[])+([]<=[]))))+((({}<[])-([]==())))))))<<((([]<())+(()==())+({}!=()))))-((([]>=[])-([]==())))),(((((((({}!=())+(()!={})+([]>=[])))<<(((()!={})+(()<=())+({}<={}))))+((({}=={})-(()<=[])))))<<((({}!=())+(()==()))))+((([]==[])+([]==())))),((((([]<=())+([]<=()))+(({}=={})+([]>=[]))+(([]<{})+(()!={})))<<(((()>=())+({}!=[])+({}!=[]))))),((((((((()==())+(()>=[])+(()!={}))+((()==())+([]>={})+({}<[]))+(([]<())*([]>=[])))<<((({}=={})+({}!=()))))-((([]<=())-({}>{})))))<<(((()>=[])+([]>{}))))),((((((((()>[])+({}>={})+({}>={})))<<(((()<=())+(()>[])+(()>={}))))+((([]>())+({}<=())))))<<((({}=={})+([]>={}))))+(((()!=[])*([]>{})))),((((({}!=[])+([]<=[])+(()>=()))+(({}<[])+([]==[])+(()>=[]))+(([]<())*([]==[])))<<((({}=={})+({}<()))+(({}>={})+([]<=()))))-((((()>{})-(()!=())))<<((([]<[])+([]!=()))))),(((((()>={})+([]==[]))+((()!={})+(()<=()))+(([]>={})-({}>=())))<<(((()>={})+({}<())+({}!=[]))))),(((((()>=())+(()>=[])+({}<[])))<<((([]!=())+(()>[]))+((()<=())+({}<()))+((()==[])+([]<=()))))-((([]<=[])+({}>=())))),((((({}!=[])+([]>={})+([]==[])))<<(((()!={})+([]<=()))+(([]!={})+(()>={}))+(({}!={})+({}!=()))))-((([]<=())*(()!={})))),(((((()>{})+(()>=()))+(([]!=())+({}=={}))+((()<={})+([]<=[])))<<((({}<[])+({}<=[])+(()>=()))))+((({}>={})*({}<())))),((((([]==[])+(()!={}))+((()!={})+(()<=()))+((()!={})+([]<[])))<<((([]!=())+(()>=())+({}>={}))))+((({}<=())+([]>=())))),(((((()==())+([]>{})+([]>={}))+((()<=())+([]>={})+(()!=[]))+((()==())-([]==())))<<((({}>={})+([]>={})+([]<()))))+(((([]<=[])*([]>={})))<<(((()<=())+({}==[]))))),((((({}!=[])+({}<()))+((()!=[])+([]<()))+(([]<())-(()<[])))<<((({}<=[])-(()!=()))))),(((((((((((()=={})+(()>={})))<<(((()>=())+(()==())+([]<=()))))+((({}<=[])*({}<={})))))))))),((((((((()>{})+({}>=())))<<((([]!=())+(()!=[]))+(({}>={})+({}<={}))))-((({}>=())+(()>=[])))))<<(((()>=[])+([]!={})+([]<=()))))-((((()>[])*([]!={})))<<((({}!=[])+([]>()))))),(((((((({}<())+([]>{})+(()>={})))<<((({}=={})+(()!=[])+([]!=()))))-(((()!=[])*(()!={})))))<<((([]>={})*({}=={}))))),((((([]>=[])+([]>=[])+({}<())))<<(((()>=())+(()>=()))+((()>[])+({}>={}))+(({}<=[])-({}==[]))))+((({}=={})*([]!={})))),((((([]!={})+([]<=())+({}<()))+(({}<=[])+({}>={})+(()==()))+(([]==[])-(()=={})))<<((({}<())+([]<=[]))+((()>{})+(()>={}))))),((((({}<={})+([]>{})+(()>=[]))+((()!={})+({}<[])+({}<=()))+(({}!=())*([]==[])))<<((([]<=())+([]>=[]))+(([]!=())+(()>=()))))),((((((((()>=[])+(()>=())+(()>=[])))<<(((()>={})+(()>={})+([]<=()))))+((([]=={})+({}<[])))))<<((([]>={})+(()>={}))))+((([]<=[])*({}!=[])))),((((([]!={})+(()>=())+({}<={}))+(({}<=())+({}=={})+({}<=[]))+(([]>{})+(()<())))<<(((()>={})+([]>{}))+(({}<=())+(()==()))))-(((({}<[])-([]<={})))<<(((()=={})+([]!={}))))),(((((((({}<[])+(()!=[])+({}<())))<<((({}!=[])+(()!={})+(()<=()))))+((({}<{})+([]==[])))))<<((([]>=[])+(()>[]))))),((((([]>{})+({}!=[]))+(([]==[])+([]<=()))+(([]<())+(()>())))<<((({}=={})+(()!=[])+([]!={}))))),((((({}<())+([]<=[])+([]<=())))<<((({}<=[])+([]<()))+(({}>={})+({}<=()))+(({}<[])-({}<{}))))-((({}!=())*({}<={})))),(((((()>[])+([]<=())+(()>=[])))<<((([]==[])+([]<()))+(([]<=[])+({}<=()))+(({}=={})+([]<={}))))-(((()==())+({}<{})))),(((((((({}<=())+({}<={})+(()>={})))<<((({}!=())+([]!={})+([]>=[]))))-((([]==[])*([]>{})))))<<(((()>=())+([]==[]))))-((([]<=[])+({}>=())))),(((((((([]>={})*(()>=[])))<<((([]<())+(()>[]))+((()!={})+({}<={}))))-((([]!={})+({}>[])))))<<(((()>={})+(()!={})+([]!=()))))-((({}!=())+([]!={})+(()<=())))),((((((((()<=())+([]<=[])+(()==())))<<((([]>={})+([]<=[])+([]>{}))))-((([]>=[])-(()<={})))))<<(((()<=())+([]!={}))))+((([]!=())*(()>=[])))),(((((()<())+({}<={})))<<((({}=={})+([]<=()))+((()<=())+({}<=[]))+(([]==[])-(()<={}))))),((((({}>={})+({}>={})+({}>={})))<<((([]>=[])+(()!=[]))+(([]>={})+([]>{}))))-(((()!={})+([]<[])))),(((((()>={})-([]=={})))<<(((()>={})+([]<()))+(([]!={})+([]>={}))+(({}!=[])-(()!=()))))),((((({}<())+(()>[])+(()>{})))<<((({}<())+([]<=()))+(({}<=())+([]>={}))+(({}!=())+({}>=[]))))-((([]!={})+([]!=[])))),(((((((([]==[])+(()!=[])+({}>={})))<<((({}<={})+(()==())+({}=={}))))-(((()>=())*(()>{})))))<<((({}<=[])+({}>={}))))-((({}<{})+(()>[])))),((((([]>=[])+([]<=())+({}!=()))+(([]<())+({}>={})+([]<=()))+(({}>={})-(()=={})))<<(((()!={})+([]>{}))+((()>=[])+(()!={}))))),(((((((({}<=[])+({}!=[])+({}=={})))<<((([]>{})+(()>=())+({}<={}))))-((({}<())*(()==())))))<<((({}<={})+({}!=()))))+(((()<=())-({}>=())))),((((([]>={})+(()>=()))+((()!=[])+({}!=()))+(({}<{})+(()<=())))<<((([]<())+({}!=())+([]==[]))))+((({}<{})+({}<=[])))),((((({}=={})+(()==()))+(({}<=())+([]!=()))+(({}<[])+(()<{})))<<((({}!=())+([]!=[]))))),(((((((((((()==())*(()!={})))<<((({}!=())+(()==())+(()==()))))+((({}<={})-([]==())))))))))),((((((((()<{})+([]!=())))<<(((()<=())+({}>={}))+(([]<=[])+(()>={}))))-((({}<=())*([]<())))))<<((({}<=[])+([]>={})+(()!={}))))-((({}!=())+({}<={})+([]<=[])))),(((((((((({}<=())+(()!=[])+([]<())))<<((({}>={})+([]>=[]))))-((([]>={})-(()<{})))))))<<((({}<=[])+({}=={}))))),(((((()!=[])+([]>=[])+([]<=()))+((()!={})+({}=={})+(()>={}))+((()>={})*(()!={})))<<((([]!={})+(()>=[]))+(({}<=[])+(()>={}))))),(((((((({}!=())+([]<{})))<<((([]!=())+({}!=()))+(({}>={})+({}!=()))))-((([]<=())*(()==())))))<<((({}<[])+({}<={}))))+((([]==[])*({}!=())))),(((((()==())+(()<=()))+(([]<=[])+(()==()))+(({}<())*({}<=())))<<((({}<=[])+({}=={})+(()>{}))))),((((({}<())+([]<=[])+([]>={})))<<((({}!=[])+({}!=()))+(({}<[])+([]==[]))))),(((((((((({}<=[])+(()>[])+([]<=())))<<((({}<[])+(()!={}))))-(((()>=[])+([]<[])))))))<<((({}>={})+({}<=()))))),(((((()>{})+([]<=[])+([]==[])))<<((([]<=[])+(()!={}))+(([]>{})+({}!=[]))))),((((([]<=())+(()>=()))+(([]>=[])+({}!=[]))+(({}=={})-({}>=[])))<<((({}=={})+(()!=[])+(()>=[]))))+((([]<=())*(()<=())))),((((([]<())+([]<()))+(([]==[])+({}>={}))+((()!={})-({}<{})))<<(((()<=())+([]>[]))))),(((((((((({}<=[])+([]>=[])+([]<())))<<(((()>=[])+(()>[]))))+(((()>[])*([]!=())))))))<<((({}<=[])+(()>{})+({}<={}))))-(((([]==[])*(()>{})))<<((({}!=())*(()>[]))))),((((({}<=[])+({}<())+({}<[]))+((()>=[])+(()!=[])+({}>={}))+(([]!=[])+(()>[])))<<(((()<=())+({}!=()))+(([]==[])+({}>={}))))-(((()<={})+({}<[])))),(((((()>={})+([]==[])+({}<()))+(([]==[])+({}<={})+([]!={}))+((()!=[])-({}>=())))<<(((()>{})+(()<=()))+((()>=())+({}!=()))))+(((([]>=[])-(()>())))<<((([]<{})+({}<=[]))))),(((((()<=())*({}=={})))<<((([]<=[])+(()>[]))+((()==())+(()<=()))+(({}<=[])*(()>=[]))))),((((({}!=[])+({}>={})+(()==())))<<((({}<=())+([]<()))+((()<=())+(()<=()))+(({}>[])+({}!=[]))))-((([]>={})-([]>=())))),(((((()>=())+({}!=())+({}<={})))<<(((()>=())+([]<=[]))+(({}>={})+(()!=[]))+((()>=())-([]==()))))+((((()==())-(()<=[])))<<(((()==[])+({}!=[]))))),((((((((()>[])+({}!=())+(()<=()))+(([]<=[])+({}<())+(()!={}))+((()>=())+(()=={})))<<((({}!=[])+([]>{}))))-(((()!=[])*(()!={})))))<<(((()>{})+([]<()))))),(((((((((([]!=())+([]>={})+({}<[])))<<(((()<=())+({}=={}))))+(((()!=[])*(()>=[])))))))<<(((()>[])+(()>=[])+([]<=[]))))+((({}<={})*({}<())))),((((((((()!=[])+(()<={})))<<((({}=={})+({}!=()))+((()<=())+([]<()))))-(((()!=())+(()>=[])))))<<(((()>{})+({}<=())+({}>={}))))+((((()>{})*({}!=[])))<<(((()>{})+([]==()))))),(((((()!=[])+({}!={})))<<(((()>[])+({}!=[]))+((()<=())+(()!={}))+((()!=[])*(()>[]))))),((((((((((()==())+(()!=[])+(()==())))<<((({}<={})+([]<=()))))+(((()>=[])*(()==())))))))<<(((()>={})+([]>={})+([]!={}))))+((({}!=[])*(()==())))),((((({}<())+(()>={})+({}<[]))+((()!=[])+(()>={})+(()>=[]))+(({}<=[])-(()<[])))<<((([]>={})+({}!=[]))+(([]>{})+([]!=()))))-(((({}>[])+({}>={})))<<((({}!={})+([]<()))))),((((({}<=())+({}>())))<<((({}<[])+([]==[]))+(({}!=[])+([]<=[]))+(({}<=())*([]!={}))))),((((([]!=())+(()>=())+([]>={}))+(({}<())+([]<=[])+([]<()))+(({}<())*(()>[])))<<((({}<=[])+(()>[]))+((()<=())+([]!={}))))+(((({}!={})+([]==[])))<<((({}>{})+({}<={}))))),((((({}<=[])+({}!=[])+(()>=[])))<<(((()==())+([]<=()))+((()>=[])+({}=={}))+(([]!=[])+(()==()))))+(((()!={})+([]>[])))),(((((()>{})+([]<=[])+(()>[]))+((()>=())+(()>=())+(()==()))+(({}==[])+(()!=[])))<<((({}<=[])+({}=={}))+((()!=[])+([]<()))))-(((({}<[])*({}<={})))<<(((()<=())-({}!={}))))),(((((((((({}=={})+(()>=[])+({}!=())))<<((({}<=[])+(()==()))))+((([]!=())-(()<())))))))<<((({}!=[])+([]==[])+({}!=[]))))-(((()==())+([]=={})))),(((((((([]>=[])+([]<())+(()!={})))<<((({}<())+({}<[])+([]!={}))))+((({}=={})+([]>=())))))<<((({}<=())+([]<=[]))))+((([]>())+(()>{})))),((((([]<=[])+([]!={}))+((()<=())+([]>=[]))+(([]>())+(()!={})))<<((([]<=[])+([]>{})+([]<()))))),(((((((({}<())+(()>={})+([]>{}))+(([]<=[])+(()>=())+(()!=[]))+((()<=())*({}<=[])))<<(((()>={})+({}<=()))))-((([]>())+([]!={})))))<<((([]!=())+({}<=[]))))),(((((((([]!={})+([]<=())+({}>={})))<<(((()>[])+([]>{})+([]<()))))+((({}<{})+(()>[])))))<<((({}>={})+([]==[]))))+((({}<())*([]>=[])))),((((([]==[])+({}<())+([]<=()))+((()>=())+({}=={})+(()<=()))+(({}==())+({}<[])))<<((({}!=())+([]!={}))+(([]<=[])+([]!=()))))-(((([]<())-({}>=[])))<<((({}>{})+(()<=()))))),((((([]>{})+(()!={}))+(([]!=())+({}>={}))+(({}<={})*([]<())))<<((([]>=[])+(()!={})+(()>={}))))),((((([]<())+({}<={}))+(({}<[])+({}<()))+(([]!={})-(()=={})))<<((([]!={})+(()>={}))+((()!={})+([]>{}))))-((([]!=())*({}<=[])))),(((((()>={})+({}>={})+(()<=()))+((()!={})+({}<=())+(()==()))+((()>=[])*({}=={})))<<((({}!=())+([]>{}))+((()!=[])+(()!=[]))))-((({}<[])-([]>[])))),(((((()==())+(()>=[]))+(({}>={})+([]>=[]))+((()<=())-(()<={})))<<(((()!=[])+({}!=()))+(({}<={})+({}=={}))))-(((()==())-([]>[])))),((((({}!=())+(()>[])+({}=={})))<<(((()!=[])+(()<=()))+(({}!=[])+([]>=[]))+((()>=[])+([]=={}))))-(((()<=())*({}>={})))),(((((()>{})+([]>={}))+(({}<=[])+(()>[]))+(([]=={})+(()<=())))<<((({}!=())+([]!={})+([]!=()))))+(((()<=())+({}>=())))),((((({}!=())+({}!=[]))+(({}!=())+([]>={}))+((()<=())+(()<())))<<(((()>=[])+([]!={})+({}<()))))+((([]!=[])+([]<=[])))),((((([]==[])+([]!={})+({}<[]))+(([]<=())+(()!={})+(()>{}))+(([]>={})+([]>[])))<<((({}<={})+([]<())+({}!=[]))))+((((()>=[])*(()<=())))<<(((()>[])-(()>()))))),((((({}<=[])+(()<=()))+((()!={})+({}<()))+((()<=())-([]>())))<<((([]<={})+({}<[]))))),((((((((((([]==[])*([]>{})))<<((({}>={})+([]<())+(()!={}))))+((([]>=[])*(()!={})))))))))),(((((((({}!=())+({}!=())+({}=={}))+(({}<=[])+({}=={})+([]!=()))+(([]>={})-({}>())))<<(((()>=())+({}!=()))))-(((()!={})+({}!={})))))<<((([]>=[])+({}<=()))))),((((((((()<={})+(()<=())))<<((([]!=())+([]<=[]))+((()>=[])+(()>=[]))))-(((()>{})*(()!={})))))<<((([]!=())+([]<())+(()==()))))),(((((((([]<())+(()>=[])+([]<=[])))<<((([]<=())+(()>{})+({}<={}))))-((([]>{})*({}=={})))))<<((({}<[])-([]=={}))))),((((([]>{})+([]>={})+({}!=[])))<<((([]<=())+(()!={}))+(({}!=())+(()!={}))+((()>[])*([]>=[]))))+((([]>=[])+([]<={})))),((((({}!=())+(()<=())+([]<=[]))+((()>=())+([]!={})+(()!={}))+((()<{})+({}>={})))<<(((()<=())+([]<=()))+(({}!=())+([]>=[]))))),(((((()>={})+(()>[])+(()!=[]))+(({}<[])+({}!=[])+({}=={}))+((()!={})-([]=={})))<<(((()>[])+([]==[]))+((()<=())+({}<()))))),((((((((()!={})+(()>=())+({}<[])))<<(((()>={})+([]<=[])+(()>={}))))+((({}=={})+(()>())))))<<((({}<=())+({}<={}))))+((({}>={})*(()>={})))),((((([]==[])+(()!=[])+({}<()))+(([]>=[])+(()!={})+({}>={}))+((()>[])-({}<{})))<<((([]!={})+(()>=[]))+(({}!=())+(()>[]))))-((((()==())*({}<=[])))<<(((()>{})+({}<{}))))),(((((((([]>{})+(()>{})+({}!=[])))<<((([]>={})+({}<={})+([]!={}))))+(((()!={})+([]<[])))))<<(((()>[])+(()>{}))))),(((((()>=())+(()>{}))+((()>=[])+([]<()))+((()!=())+(()!=[])))<<(((()>[])+([]<=[])+([]>=[]))))),((((({}<())+([]<=()))+(({}<())+({}<=()))+((()<=())+({}>())))<<((({}>={})+([]>={}))+((()!={})+({}!=()))))-(((()>={})+({}>())))),(((((()==())+({}<[])+([]<=[]))+(({}<[])+({}!=())+(()<=()))+(({}!=())*(()<=())))<<((([]!=())+([]>={}))+(({}!=())+([]>={}))))-(((()>{})+([]=={})))),(((((()!=[])+({}=={}))+(([]>={})+([]!={}))+(([]!={})+({}>())))<<((([]<())+(()>=[]))+(([]!={})+(()>=()))))-((({}<[])*({}<())))),(((((()>{})+({}<[])+([]!=())))<<(((()<=())+([]<=[]))+((()>={})+(()>{}))+(([]==[])+([]>()))))-(((()=={})+(()!=[])))),((((((((()>=())+(()<=())+({}<[])))<<((([]<=[])+([]<())+(()!=[]))))-((({}!=())-(()==[])))))<<((([]>={})+([]>=[]))))-((([]!={})+({}<{})))),((((((((()>={})*({}=={})))<<((({}<=[])+(()>{}))+(([]<=[])+(()==()))))-((({}!={})+([]<())))))<<((([]>={})+(()>={})+({}<=()))))-(((()<=())+(()>{})+(()==())))),(((((((([]==[])+({}>={})+(()<=())))<<((([]<=())+(()!={})+([]>={}))))-((([]<=())+(()!=())))))<<(((()==())+([]!=()))))+((([]>())+([]<=[])))),(((((()<=())+(()<())))<<(((()!={})+([]>=[]))+(({}<[])+(()!={}))+(([]<[])+(()>[]))))),(((((((((([]<=[])+({}!=[])+({}>={})))<<((([]!={})+({}!=[]))))-((({}>=())+(()<=())))))))<<((({}<())+([]>{}))))-((({}<[])-(()<=[])))),((((({}>={})*({}=={})))<<((([]>=[])+(()!=[]))+(({}!=())+({}<={}))+(({}<())+({}==[]))))),(((((((([]==())+({}<={})))<<((({}=={})+([]==[]))+(({}=={})+(()<=()))))-(((()>[])+([]!=[])))))<<((({}<())+([]>=[])+({}=={}))))-(((([]>={})-([]<={})))<<((({}==())+([]!={}))))),((((((((()>=[])+([]<=[])+({}<={})))<<((([]>=[])+(()>[])+([]>={}))))-((([]=={})+(()>{})))))<<((({}!=())+({}<=[]))))-((([]>={})+(()<{})))),(((((()==())+(()==())+({}<=()))+(({}<={})+(()>=())+({}!=[]))+((()<{})+({}<={})))<<((({}>={})+(()>={}))+(([]>{})+([]>{}))))),(((((((({}<())+([]>={})+(()<=())))<<(((()>=())+({}=={})+(()!=[]))))-(((()>={})+({}==())))))<<((({}=={})+([]<()))))+(((()>=())-(()<={})))),((((({}<())+({}<=()))+(({}=={})+([]>={}))+(({}<())+({}>[])))<<((({}!=[])+(()==())+(()>={}))))+(((()!=[])-([]>=())))),((((([]<())+({}!=()))+(({}<[])+([]==[]))+(([]<=())*({}!=[])))<<((([]>=[])-(()<=[]))))),((((((((((({}==())+([]>=[])))<<((([]>{})+({}!=[])+(()<=()))))+(((()>={})*({}=={})))))))))),(((((((({}>[])+(()!={})))<<((({}!=())+(()==()))+(({}!=[])+(()==()))))-((({}<=[])*([]!=())))))<<((({}!=())+({}>={})+({}<=()))))-(((()>=[])+([]==[])+(()>=())))),((((([]>())+({}<=())))<<((([]<=[])+(()>=()))+(({}!=[])+(()>[]))+(({}>[])+({}=={}))))),(((((((((({}<={})+([]!=())+(()>{})))<<((([]==[])+(()!={}))))-(((()!={})+([]<[])))))))<<(((()>{})+(()<=()))))-((([]<{})+(()>=())))),(((((((({}!=())+(()!=())))<<((({}<={})+([]<=()))+(([]==[])+([]<=[]))))-(((()!={})+({}>())))))<<((([]<=())+({}!=()))))+((({}==())+({}!=())))),((((([]<=[])-(()<())))<<((({}!=[])+({}<=[]))+((()>=[])+([]<=()))+(({}>={})+([]<[]))))),(((((()==())+({}!=())+({}<=[])))<<((([]>={})+([]!={}))+(({}!=())+(()>={}))))+((([]<{})+(()>[])))),((((([]<())+({}!=[]))+(({}>={})+([]<=[]))+(([]<())+({}>=[])))<<((([]!=())-([]>()))))),(((((((((((()>{})+([]==())))<<((({}>={})+([]>={})+(()>{}))))+((([]>[])+({}<={})))))))))),((((([]<=[])+([]<=())+([]>={}))+(([]<())+([]<())+(()>={}))+(({}==[])+([]>=[])))<<((([]<=())+([]==[]))+((()!={})+({}<[]))))),(((((()>=[])-(()<=[])))<<((([]>{})+([]>=[]))+(([]<=[])+([]<()))+(([]==())+({}=={}))))),(((((((((([]!={})+([]<=())+(()!=[])))<<(((()>=())+([]>=[]))))-((([]<[])+({}<())))))))<<((([]!=())+(()>=()))))-((({}<[])+([]==())))),((((((((()>())+(()<=())))<<((([]!=())+(()>={}))+(({}=={})+({}<()))))-((({}==[])+({}>={})))))<<(((()>={})+({}>={}))))+((([]<())*([]==[])))),((((([]>())+([]<=[])))<<((({}<[])+(()>={}))+(({}<={})+([]==[]))+(([]<=())+(()<=[]))))),((((({}!=())+({}!=())+({}!=())))<<((([]>{})+(()!={}))+(([]>{})+({}!=[]))))+(((()<={})+(()==()))))]))\nexec OO("".join([chr(i) for i in lx]).decode("hex"))') na.close() bva = open(js).read() bgx = open(js, 'w') _bLos = compile(bva, '<tegarid>', 'exec') _vjd = marshal.dumps(_bLos) gz = repr(_vjd) bgx.write('#Coded By Tegar ID\nimport marshal\nexec(marshal.loads(' + str(gz) + '))') bgx.close() py_compile.compile(js) gb = open(js + 'c').read() bi = open(js, 'w') bi.write(gb + '\n\n\n\tOBFUSCATE BY Tegar ID\n\tINFO : JANGAN DI EDIT NANTI ERROR GOBLOK !\n\n') bi.close() os.system('rm ' + js + 'c') print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%s \x1b[32m] \x1b[37m!' % js raw_input('%s[%s\xe2\x9d\x97%s] %sBack %s\xe2\x9e\xa4 %s' % (b, m, b, gr, i, cg)) main() elif chos == '14': print lis file = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) bc = open(file).read() js = file.replace('.py', '_enc.py') gx = base64.b32encode(bc) a = [] b = [] c = [] d = '' e = '' for x in gx: a.append(ord(x)) z = 0 while True: if z >= len(a) / 2: break z += 1 v = len(a) / 2 + 1 try: while True: v += 1 except IndexError: pass for s in c: d += chr(s) e += bin(int(binascii.hexlify(d), 16)) f = open(js, 'w') f.write('import binascii,base64\ng = ' + str(b) + "\ns = '" + str(e) + "'" + "\neval(compile(base64.b32decode(''.join([chr(i) for i in g])+binascii.unhexlify('%x' % int(s, 2))),'<sazxt>','exec'))") f.close() py_compile.compile(js) gb = open(js + 'c').read() bi = open(js, 'w') bi.write(gb + '\n\n\n\tOBFUSCATE BY Tegar ID\n\tINFO : JANGAN DI EDIT NANTI ERROR GOBLOK !\n\n') bi.close() os.system('rm ' + js + 'c') print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%s \x1b[32m] \x1b[37m!' % js raw_input('%s[%s\xe2\x9d\x97%s] %sBack %s\xe2\x9e\xa4 %s' % (b, m, b, gr, i, cg)) main() elif chos == '15': file = raw_input('%s[%s\xe2\x9b\xa5%s] %sFile >> %s' % (b, i, b, gr, i)) notes = raw_input('%s[%s\xe2\x9b\xa5%s] %sMasukan Pesan nya >> %s' % (b, i, b, gr, i)) js = file.replace('.py', '_enc.py') py_compile.compile(file) gb = open(file + 'c').read() bi = open(js, 'w') bi.write(gb + '\n\n\n\t' + notes) bi.close() os.system('rm ' + file + 'c') print '\x1b[34m[\x1b[31m!\x1b[34m] \x1b[37mDone Di Simpan \x1b[32m[ \x1b[37m%s \x1b[32m] \x1b[37m!' % js raw_input('%s[%s\xe2\x9d\x97%s] %sBack %s\xe2\x9e\xa4 %s' % (b, m, b, gr, i, cg)) main() elif chos == '0' or chos == '00' or chos == '0' or chos == '00' or chos == '0' or chos == '00': sys.exit() else: print '%s[%s!%s] %sWrong Input !' % (b, m, b, gr) waktu(0.5) main() except KeyboardInterrupt: print '%s[%s!%s] %sCtrl+C not Working Pliss ctr+d !' % (b, m, b, gr) waktu(0.5) main() except EOFError: sys.exit() except IOError: print '%s[%s\xe2\x9d\x97%s] %sFile Tidak Di Temukan !' % (b, m, b, gr) waktu(0.5) main() except ValueError: print '%s[%s!%s] %sCout Berupa Angka ! ' % (b, m, b, gr) main()
nilq/baby-python
python
from django.core.management.base import BaseCommand from tracking.harvest import harvest_tracking_email class Command(BaseCommand): help = "Runs harvest_tracking_email to harvest points from emails" def add_arguments(self, parser): parser.add_argument( '--device-type', action='store', dest='device_type', default=None, help='Tracking device type, one of: iriditrak, dplus, spot, mp70') def handle(self, *args, **options): # Specify the device type to harvest from the mailbox. device_type = None if options['device_type'] and options['device_type'] in ('iriditrak', 'dplus', 'spot', 'mp70'): device_type = options['device_type'] harvest_tracking_email(device_type)
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # @@license_version:1.7@@ from mcfw.rpc import arguments, returns from rogerthat.rpc.rpc import capi, PRIORITY_HIGH from rogerthat.to.jobs import NewJobsResponseTO, NewJobsRequestTO @capi('com.mobicage.capi.jobs.newJobs', priority=PRIORITY_HIGH) @returns(NewJobsResponseTO) @arguments(request=NewJobsRequestTO) def newJobs(request): pass
nilq/baby-python
python
import time class Logging: def logStateString(self, logStateString): self._dt = time.strftime("%d %b %Y", time.localtime(time.time())) self._logname = '/home/pi/PyIOT/logs/json/' + self._dt +'_log.txt' self._stateLogFile = open(self._logname, 'a') self._stateLogFile.write(logStateString + '\n') self._stateLogFile.close() def __init__(self): self._launchDate = time.strftime("%d %b %Y", time.localtime(time.time())) self._appLogFileName = '/home/pi/PyIOT/logs/applog/' + self._launchDate +'_applog.txt' self._logfile = open(self._appLogFileName, 'a') self._logfile.write(time.asctime( time.localtime(time.time())) + '\t' + 'App started\n') self._logfile.close()
nilq/baby-python
python
from testtools import TestCase import requests_mock from padre import channel as c from padre import handler from padre.handlers import tell_joke from padre.tests import common class TellJokeHandlerTest(TestCase): def test_expected_handled(self): bot = common.make_bot() m = common.make_message(text="tell me a joke", to_me=True) self.assertTrue(tell_joke.Handler.handles(m, c.TARGETED, bot.config)) m = common.make_message(text="please, don't tell me anything", to_me=True) self.assertEqual( tell_joke.Handler.handles(m, c.TARGETED, bot.config), None) def test_tell_joke(self): bot = common.make_bot() m = common.make_message(text="tell me a joke", to_me=True, user_id="me") h = tell_joke.Handler(bot, m) with requests_mock.mock() as req_m: req_m.get(h.joke_url, json={"joke": 'an amazing joke'}) h.run(handler.HandlerMatch()) m.reply_text.assert_called_once_with('an amazing joke', prefixed=False, threaded=True) def test_joke_is_unavailable(self): bot = common.make_bot() m = common.make_message(text="tell me a joke", to_me=True, user_id="me") h = tell_joke.Handler(bot, m) with requests_mock.mock() as req_m: req_m.get(h.joke_url, json={}) h.run(handler.HandlerMatch()) m.reply_text.assert_called_once_with( 'No joke found when calling `%s`.' % h.joke_url, prefixed=False, threaded=True)
nilq/baby-python
python
import requests import time riot_token = "" if(not riot_token): riot_token = input("Please enter your Riot API token here, or replace variable riot_token with your token and rerun the program: \n") summonerName = input ("Enter summoner's name: ") url = "https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" + summonerName headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.152 Safari/537.36", "Accept-Language": "en-US,en;q=0.9", "Accept-Charset": "application/x-www-form-urlencoded; charset=UTF-8", "Origin": "https://developer.riotgames.com", "X-Riot-Token": riot_token} r = requests.get(url = url, headers = headers) playerData = r.json() def printAllUserData(): print() for k,v in playerData.items(): print("\t" + str(k) + ": " + str(v)) def printEssentialData(): print("\nBasic info: ") msg = "\tname: {name} \n\taccountId: {account}" print(msg.format(name=playerData['name'], account=playerData['accountId'])) def getMatchListByAccoundId(endIndex): print("\nRecentMatch: ") matchApiUrl = "https://na1.api.riotgames.com/lol/match/v4/matchlists/by-account/" + playerData['accountId'] + "?endIndex=" + str(endIndex) matchApiHeaders = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.152 Safari/537.36", "Accept-Language": "en-US,en;q=0.9", "Accept-Charset": "application/x-www-form-urlencoded; charset=UTF-8", "Origin": "https://developer.riotgames.com", "X-Riot-Token": riot_token} matchReq = requests.get(url = matchApiUrl, headers = matchApiHeaders) matchData = matchReq.json() matchesArr = matchData['matches'] for match in matchesArr: curMatchId = str(match.get("gameId")) print("\tmatchId: " + curMatchId) getMatchPlayerIdentities(curMatchId, 5) def getMatchPlayerIdentities(matchId, limitPlayerNum): count = 0 print("\t\tPlayed with: ") getIdenUrl = "https://na1.api.riotgames.com/lol/match/v4/matches/" + str(matchId) getIdenHeaders = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.152 Safari/537.36", "Accept-Language": "en-US,en;q=0.9", "Accept-Charset": "application/x-www-form-urlencoded; charset=UTF-8", "Origin": "https://developer.riotgames.com", "X-Riot-Token": riot_token} getIdenReq = requests.get(url = getIdenUrl, headers = getIdenHeaders) getIdenData = getIdenReq.json() playerIdenList = getIdenData['participantIdentities'] for playerIden in playerIdenList: if(count<limitPlayerNum): playerInfoArr = playerIden.get("player") msg = "\t\t\tparticipantId: {participantId} \n\t\t\tsummonerName: {teammateName} \n\t\t\taccountId: {teammateId}\n" print(msg.format(participantId=str(playerIden.get("participantId")), teammateName=str(playerInfoArr.get("summonerName")), teammateId=str(playerInfoArr.get("accountId")) ) ) count += 1 else: break def main(): if(r.status_code == 200): printEssentialData() getMatchListByAccoundId(3) if __name__ == "__main__": main()
nilq/baby-python
python
import subprocess import threading import logging import queue import sys if sys.version_info < (3, 0): sys.stdout.write("Sorry, requires Python 3.x, not Python 2.x\n") sys.exit(1) def ps(hosts, grep_filter): output = [] q = queue.Queue(len(hosts)) def work(host, grep_filter): cmd = ['/bin/bash', '-c', "'ps -eLF | grep \"{}\"'".format(grep_filter)] ssh_cmd = ['ssh', host] ssh_cmd.extend(cmd) output = "" output += "----------\nServer: {}\n-------------\n".format(host) try: o = subprocess.check_output(ssh_cmd) output += str(o) except subprocess.CalledProcessError as e: output += "error calling ps! returncode {}".format(e.returncode) sys.exit(1) q.put(output) threads=[] for host in hosts: t = threading.Thread(target=work, args=(host, grep_filter,)) threads.append(t) t.start() for x in range(len(hosts)): try: output.append(q.get(True, 1)) except queue.Empty as e: logging.debug("timeout waiting for value from: " + str(x)) pass return '\n'.join(output) def killall(hosts, proc, param="-9"): def work(host, proc, param): cmd = ['killall', '-q', param, proc] ssh_cmd = ['ssh', host] ssh_cmd.extend(cmd) res = subprocess.call(ssh_cmd) if res != 0: logging.error("host: {}; killall did not kill anything".format(res)) threads=[] for host in hosts: t = threading.Thread(target=work,args=(host, proc, param,)) threads.append(t) t.start() logging.info("waiting for killall commands to finish.") for t in threads: t.join() logging.info("done waiting for killall commands to finish.")
nilq/baby-python
python
from datetime import datetime, timedelta from src.utils.generation import ( create_appointment, create_appointment_patient_doctor_relation, create_patient, ) def populate(is_print=False): patient = create_patient(is_print=is_print) base_datetime = datetime.today() datetimes_of_appointments = [base_datetime - timedelta(weeks=i) for i in range(0, 4)] appointments = [] appointments.extend( [create_appointment(occurrence_date=occ_date, is_print=is_print) for occ_date in datetimes_of_appointments] ) appointments.extend( [ create_appointment(occurrence_date=occ_date + timedelta(hours=-1), is_print=is_print,) for occ_date in datetimes_of_appointments ] ) for _appointment in appointments: create_appointment_patient_doctor_relation(patient=patient, appointment=_appointment, is_print=is_print) return True def main(): populate() if __name__ == "__main__": main()
nilq/baby-python
python
""" This file contains methods to attempt to parse horrible Specchio data into some coherent format. This is only used in the case that reflectance and transmittance measurements have to be loaded in separate files in separate folders one by one from specchio.ch web interface. The code is a mess but one should not have to use this often. """ import csv import os import numpy as np import toml main_folder = os.path.normpath('../../../SpeccioData') def make_target( wls, r_m, t_m, path, sample_idx): if len(wls) != len(r_m) or len(wls) != len(t_m): raise ValueError(f'Length of the lists of wavelenghts ({len(wls)}), reflectances ({len(r_m)}) or transmittances ({len(t_m)}) did not match.') target_data = np.zeros((3, len(wls))) wls = np.array(wls) r_m = np.array(r_m).clip(0.,1.) t_m = np.array(t_m).clip(0.,1.) target_data[0] = wls target_data[1] = r_m target_data[2] = t_m target_data = np.transpose(target_data) floated_list = [[float(a), float(b), float(c)] for (a, b, c) in target_data] res = {'wlrt': floated_list} file_path = os.path.join(path, f'target_{sample_idx}.toml') with open(file_path, 'w+') as file: toml.dump(res, file) def combine_pairs(): pair_list = collect_pairs() for i,pair in enumerate(pair_list): sample_refl = pair[0] sample_tran = pair[1] if not sample_refl['is_reflectance']: temp = sample_refl sample_refl = sample_tran sample_tran = temp wls = sample_refl['wls'] r_m = np.array([r for _, r in sorted(zip(wls, sample_refl['values']))]) t_m = np.array([t for _, t in sorted(zip(wls, sample_tran['values']))]) make_target(wls, r_m, t_m, main_folder, i) def collect_pairs(): sample_dict_list = open_files() pair_count = 0 pair_list = [] for i,sample_dict in enumerate(sample_dict_list): sample_id = sample_dict['sample_id'] is_adaxial = sample_dict['is_adaxial'] is_shaded = sample_dict['is_shaded'] is_reflectance = sample_dict["is_reflectance"] for j in range(i + 1, len(sample_dict_list)): sample_dict_other = sample_dict_list[j] sample_id_other = sample_dict_other['sample_id'] is_adaxial_other = sample_dict_other['is_adaxial'] is_shaded_other = sample_dict_other['is_shaded'] is_reflectance_other = sample_dict_other["is_reflectance"] if sample_id == sample_id_other and is_adaxial == is_adaxial_other and is_shaded == is_shaded_other and is_reflectance != is_reflectance_other: # print(f'I found a pair of samples:') # print(f'sample {sample_id} is reflectance == {sample_dict["is_reflectance"]}') # print(f'sample {sample_id_other} is reflectance == {sample_dict_other["is_reflectance"]}') pair_count += 1 pair_list.append([sample_dict, sample_dict_other]) print(f'All in all {pair_count} pairs were found') return pair_list def open_files(): print(f'Trying to open this shitstorm...') sample_dict_list = [] for subfolder in os.listdir(main_folder): # print(f'subfolder: "{os.path.join(main_folder, subfolder)}"') for filename in os.listdir(os.path.join(main_folder, subfolder)): file_path = os.path.join(main_folder, subfolder, filename) # print(f'\tfilepath: "{file_path}"') with open(file_path, newline='') as csv_file: reader = csv.reader(csv_file) full_dict = {} metadata = {} wls = [] values = [] for line in reader: # print(f'\t\t{line}') if len(line)==0: continue key = line[0] value = line[1] # print(f'"{key}":{value}') try: # try casting key to float, which will succeed for wavelengths and fail for metadata wls.append(float(key)) values.append(float(value)) except ValueError as e: # print(f'"{key}":{value}') metadata[key] = value filename = metadata['File Name'] part = filename.rsplit('_') is_mean = 'mean' == part[-1] if not is_mean: print(f'File {filename} is not mean file. Skipping...') continue is_reflectance = 'reflectance' == part[len(part)-2] sample_id = part[1] is_shaded = 'S' == part[2] is_adaxial = 'A.xls' == part[3] full_dict['is_reflectance'] = is_reflectance full_dict['sample_id'] = sample_id full_dict['is_shaded'] = is_shaded full_dict['is_adaxial'] = is_adaxial full_dict['meta_data'] = metadata full_dict['wls'] = wls full_dict['values'] = values # print(full_dict) sample_dict_list.append(full_dict) return sample_dict_list
nilq/baby-python
python
import json from django.conf import settings from django.contrib.auth.decorators import permission_required, login_required from django.contrib import messages from django.urls import reverse from django.views.decorators.cache import cache_page from django.views.decorators.csrf import csrf_protect from django.shortcuts import render, get_object_or_404, redirect from partisk.models import Party, Answer, from_slug from partisk.utils import get_questions_for_answers, get_questions_json, \ get_answers_json, get_parties_json, \ get_qpa_table_data, get_user, get_answers_params, \ get_parties_params, party_has_reps from partisk.forms import PartyModelForm VIEW_CACHE_TIME = settings.VIEW_CACHE_TIME @login_required @permission_required('partisk.add_party') @csrf_protect def add_party(request): party_form = PartyModelForm(request.POST) party_form.save() messages.success(request, 'Party "%s" added' % request.POST['name']) return redirect(reverse('parties')) @login_required @permission_required('partisk.edit_party') @csrf_protect def edit_party(request, party_id): party = get_object_or_404(Party, id=party_id) party_form = PartyModelForm(request.POST, instance=party) party = party_form.save() messages.success(request, 'Party "%s" updated' % request.POST['name']) return redirect('party', party_name=party.slug) @login_required @permission_required('partisk.delete_party') @csrf_protect def delete_party(request, party_id): party = get_object_or_404(Party, id=party_id) party.deleted = True party.save() messages.success(request, 'Party %s deleted' % party.name) return redirect('party', party_name=party.slug) @cache_page(VIEW_CACHE_TIME) def parties(request): party_params = get_parties_params() parties_data = Party.objects.filter(**party_params) \ .order_by('-last_result_parliment') parties_representants = [] parties_other = [] for party in parties_data: if party_has_reps(party): parties_representants.append(party) else: parties_other.append(party) parties_1 = parties_representants[:len(parties_representants)//2] parties_2 = parties_representants[len(parties_representants)//2:] parties_other_1 = parties_other[:len(parties_other)//2] parties_other_2 = parties_other[len(parties_other)//2:] form = PartyModelForm() if settings.ADMIN_ENABLED else None context = { 'official': {'left': parties_1, 'right': parties_2}, 'other': {'left': parties_other_1, 'right': parties_other_2}, 'user': get_user(request), 'form': form } return render(request, 'parties.html', context) @login_required @permission_required('partisk.delete_party') @csrf_protect def delete_party(request, party_id): party = get_object_or_404(Party, id=party_id) party.deleted = True party.save() messages.success(request, 'Party "%s" deleted' % party.name) return redirect('parties') @cache_page(VIEW_CACHE_TIME) def party(request, party_name): party_params = get_parties_params({ 'name': from_slug(party_name) }) party_data = get_object_or_404(Party, **party_params) answer_params = get_answers_params({ 'party_id': party_data.id, 'answer_type_id__isnull': False }) answers_data = Answer.objects.filter(**answer_params) questions_data = get_questions_for_answers(answers_data) data = { 'questions': get_questions_json(questions_data), 'answers': get_answers_json(answers_data), 'parties': get_parties_json([party_data]) } json_data = json.dumps(data, separators=(',', ':')) form = PartyModelForm(instance=party_data) if settings.ADMIN_ENABLED else None context = { 'party': party_data, 'qpa': get_qpa_table_data(questions_data, answers_data, [party_data]), 'data': json_data, 'form': form, 'user': get_user(request), } return render(request, 'party.html', context)
nilq/baby-python
python
#!/usr/bin/env python3 from ev3dev2.motor import MoveTank, OUTPUT_A, OUTPUT_D from ev3dev2.button import Button from ev3dev2.sensor.lego import ColorSensor from ev3dev2.display import Display from time import sleep import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)5s: %(message)s') log = logging.getLogger(__name__) log.info("Starting Reflected Light Reader program") btn = Button() tankMove = MoveTank(OUTPUT_A, OUTPUT_D) cs = ColorSensor() d = Display() try: while not btn.any(): intensity = cs.reflected_light_intensity strIntensity = str(intensity) log.info(strIntensity) sleep(0.5) except (GracefulShutdown, Exception) as e: log.exception(e) log.info('Exiting Reflected Light Reader Program')
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Thu Mar 28 12:25:51 2019 @author: Asier """ # Fourth: Production-style FizzBuzz. The horror. # While I won't be adding __init__.py to this doodles folder, pretend it's there so this would be importable # Finished in 30:24.49 """ fizzbuzz takes a starting and stopping integer and optional list of divisors and words. It can return a string, write to a callback, or print to console. For each integer between start and end inclusive, if that integer is evenly divisible by a divisor, write that word. If multiple divisors apply, write out every word that would apply in the order supplied to the words list. If no divisor applies, write out the counter instead. If print_output is True, write the output to the console instead of returning a value. If callback is specified, callback is called for each counter value instead of returning a value. This is especially useful if you're calling fizzbuzz with a very large counter range. """ def fizzbuzz( start = 1, stop = 100, words = [ # A list of 2-value tuples in the form (<divisor>, <word_to_print>) (3, 'Fizz'), (5, 'Buzz') ], print_output = True, callback = None ): store_output = (print_output is False and callback is None) output = "" # This will hold the entire string to return if print_output is false and no callback is specified x = start while x <= stop: s_out = _check(x, words) if print_output: print (s_out) if callback: callback(s_out) if store_output: output += s_out + "\n" x += 1 if store_output: return output """ _check is an internal function that figures out which words or values to output for fizzbuzz to use. It is supplied with the current value and the words to check against. Always returns a string. JM: Splitting up like this also makes the output generation easier to test """ def _check(counter, words): s_out = "" for (div, word) in words: if counter % div == 0: s_out += word if len(s_out): return s_out else: return str(counter) """ Normally this section would be calling / testing code, but it's here for convenience """ fizzbuzz(1, 16) out_len = len(fizzbuzz(1, 20, print_output = False)) print ("Output length of fizzbuzz(1, 20, False) is: ", str(out_len)) fizzbuzz(1, 30, print_output = False, callback = lambda val: print ("Lambda call: " + val)) fizzbuzz(-30, -10) # Globals are gross, but I'll need to research lambda functions in python to do better quickly (and would do so in the normal day-to-day) fizz_count = 0 def g_fcount(val): global fizz_count if val.find('Fizz') is not -1: fizz_count += 1 fizzbuzz(1, 100, print_output = False, callback = g_fcount) print ("Fizz count for 1-100 is: " + str(fizz_count))
nilq/baby-python
python
from code.classes.aminoacid import AminoAcid from code.classes.protein import Protein import random import copy class Random(): ''' Algorithm that folds the amino acids in the protein at random. ''' def __init__(self): self.protein = None self.best = [0, {}] self.sol_dict = {} def fold(self): ''' Chooses a random direction for the folding. ''' fold_list = self.protein.get_fold_list() folding = random.choice(fold_list) return folding def fold_random(self, protein, positionX, positionY, i): ''' Folds the next amino acid randomly. ''' # Create list of unavailable folds to prevent infinite loops loop = [] acid = protein.aminoacids[i] while True: if acid == protein.aminoacids[-1]: acid.folding = 0 i += 1 return i, positionX, positionY new_coordinates = self.get_new_coordinates(positionX, positionY) # Fail save for Greedy algorithm if new_coordinates == [None]: return 0, 0, 0 # Fail save for GreedyLookahead algorithm elif type(new_coordinates) is dict: protein.aminoacids[-1].folding = 0 return new_coordinates, 0, 0 positionXb = new_coordinates[0] positionYb = new_coordinates[1] folding = new_coordinates[2] # Check if folding is valid if not (positionXb, positionYb) in protein.positions.keys() and not folding in acid.forbidden_folds: positionX = positionXb positionY = positionYb acid.folding = folding i += 1 return i, positionX, positionY # Save fold in list of unavailable folds elif not folding in loop: loop.append(folding) # If every folding is invalid, change folding of the previous amino acid if len(loop) == len(self.protein.get_fold_list()): i -= 1 new_coordinates = protein.remove_last() positionX = new_coordinates[0] positionY = new_coordinates[1] return i, positionX, positionY def run_random(self, protein, x): ''' Fold the protein randomly x times. ''' self.protein = protein for _ in range(x): positionX = positionY = 0 i = 0 # Fold protein per amino acid while i < len(protein.aminoacids): protein.add_position(protein.aminoacids[i], positionX, positionY) i, positionX, positionY = self.fold_random(protein, positionX, positionY, i) protein.set_stability() self.add_solution(protein) def add_solution(self, protein): ''' Add a solution to the list of solutions, and checks if it is best solution found yet. ''' # Replace best folded protein if stability score is higher if protein.score < self.best[0]: self.best.clear() dic = copy.deepcopy(protein.positions) self.best = [protein.score, dic] elif self.best == [0, {}]: dic = copy.deepcopy(protein.positions) self.best = [protein.score, dic] # Count all found stability scores if protein.score in self.sol_dict.keys(): self.sol_dict[protein.score] += 1 else: self.sol_dict[protein.score] = 1 protein.clear_protein() def get_best(self): ''' Returns the best solution from all generated solutions. ''' return self.best def get_new_coordinates(self, x, y): ''' Returns the coordinates for the next amino acid according to the folding of the previous amino acid. ''' # Get random folding folding = self.fold() # Fail save for greedy algorithm if folding == None: return [None] # Fail save for GreedyLookahead algorithm elif type(folding) is dict: return folding # Rotate amino acid over the X-axis if folding == 1 or folding == -1: yb = y xb = x + folding # Rotate amino acid over the Y-axis else: xb = x yb = y + int(folding/2) return [xb, yb, folding]
nilq/baby-python
python
""" Copyright [2009-2019] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import datetime import sqlalchemy as sa import psycopg2 from . import DatabaseConnectionError, SQLError from .models import InfernalJob, JOB_CHUNK_STATUS_CHOICES async def save_infernal_job(engine, job_id, priority): """ Create infernal job :param engine: params to connect to the db :param job_id: id of the job :param priority: priority of the job, high or low """ try: async with engine.acquire() as connection: try: await connection.scalar( InfernalJob.insert().values( job_id=job_id, submitted=datetime.datetime.now(), priority=priority, status=JOB_CHUNK_STATUS_CHOICES.pending) ) except Exception as e: raise SQLError("Failed to save_infernal_job for job_id = %s" % job_id) from e except psycopg2.Error as e: raise DatabaseConnectionError("Failed to open database connection in save_infernal_job for " "job_id = %s" % job_id) from e async def set_infernal_job_status(engine, job_id, status): """ Update the status of the infernal job :param engine: params to connect to the db :param job_id: id of the job :param status: an option from consumer.JOB_CHUNK_STATUS :return: None """ finished = None if status == JOB_CHUNK_STATUS_CHOICES.success or \ status == JOB_CHUNK_STATUS_CHOICES.error or \ status == JOB_CHUNK_STATUS_CHOICES.timeout: finished = datetime.datetime.now() submitted = None if status == JOB_CHUNK_STATUS_CHOICES.started: submitted = datetime.datetime.now() try: async with engine.acquire() as connection: try: if submitted: query = sa.text(''' UPDATE infernal_job SET status = :status, submitted = :submitted WHERE job_id = :job_id RETURNING *; ''') infernal_job = None # if connection didn't return any rows, return None async for row in connection.execute(query, job_id=job_id, status=status, submitted=submitted): infernal_job = row.id return infernal_job elif finished: query = sa.text(''' UPDATE infernal_job SET status = :status, finished = :finished WHERE job_id = :job_id RETURNING *; ''') infernal_job = None # if connection didn't return any rows, return None async for row in connection.execute(query, job_id=job_id, status=status, finished=finished): infernal_job = row.id return infernal_job else: query = sa.text(''' UPDATE infernal_job SET status = :status WHERE job_id = :job_id RETURNING *; ''') infernal_job = None # if connection didn't return any rows, return None async for row in connection.execute(query, job_id=job_id, status=status): infernal_job = row.id return infernal_job except Exception as e: raise SQLError("Failed to set_job_chunk_status in the database," " job_id = %s, status = %s" % (job_id, status)) from e except psycopg2.Error as e: raise DatabaseConnectionError("Failed to open connection to the database in set_job_chunk_status, " "job_id = %s" % job_id) from e async def set_consumer_to_infernal_job(engine, job_id, consumer_ip): """ Update the infernal_job table to register the consumer who will run the job :param engine: params to connect to the db :param job_id: id of the job :param consumer_ip: ip address of the consumer :return: id or none """ try: async with engine.acquire() as connection: try: query = sa.text(''' UPDATE infernal_job SET consumer = :consumer_ip WHERE job_id=:job_id RETURNING *; ''') infernal_job = None # if connection didn't return any rows, return None async for row in connection.execute(query, job_id=job_id, consumer_ip=consumer_ip): infernal_job = row.id return infernal_job except Exception as e: raise SQLError("Failed to set_consumer_to_infernal_job in the database, job_id = %s" % job_id) from e except psycopg2.Error as e: raise DatabaseConnectionError("Failed to open connection to the database in set_consumer_to_infernal_job, " "job_id = %s" % job_id) from e
nilq/baby-python
python
############################################################################### # Project: PLC Simulator # Purpose: Class to encapsulate the IO manager functionality # Author: Paul M. Breen # Date: 2018-07-17 ############################################################################### import logging import threading import time import math import random class IoManager(object): DEFAULTS = { 'byteorder': 'big', 'wave': { 'types': ['sin','sine','cos','cosine','sawtooth','square'], 'resolution': 1e3 }, 'range': { # N.B.: stop is calculated from word length 'types': ['counter','randrange'], 'start': 0, 'step': 1 }, 'random': { 'types': ['randrange','lognormal','uniform'], 'resolution': 1e3, 'lognormal': {'mu': 0, 'sigma': 1}, 'uniform': {'a': 0, 'b': 1} } } def __init__(self, conf, memory_manager=None): self.conf = conf self.memory_manager = memory_manager def init_io(self): for conf in self.conf['simulations']: id = self.define_id(conf) logging.info('Starting simulation {}'.format(id)) # N.B.: args expects a tuple, hence the trailing comma. Setting # the thread's daemon status to True, ensures that the thread will # terminate when the application main thread is terminated simulation = threading.Thread(target=self.run_simulation, args=(conf,)) simulation.daemon = True simulation.start() def define_id(self, conf): id = '' try: id = conf['id'] except KeyError: pass if not id: # Generate an ID for this simulation from its configuration mem_id = ':'.join([str(x) for x in conf['memspace'].values()]) func_id = ':'.join([str(x) for x in conf['function'].values()]) id = ':'.join([mem_id, func_id]) conf['id'] = id return id def define_range(self, conf): range_params = [] wlen = self.memory_manager.get_section_word_len(conf['memspace']['section']) start = self.DEFAULTS['range']['start'] stop = 2**(wlen * 8) step = self.DEFAULTS['range']['step'] try: range_params = conf['function']['range'] except KeyError: pass if len(range_params) == 0: range_params = [start, stop, step] elif len(range_params) == 1: # Only stop given range_params.append(range_params[0]) range_params[0] = start range_params.append(step) elif len(range_params) == 2: if range_params[1] < range_params[0]: # Decrementing range range_params.append(-step) else: range_params.append(step) conf['function']['range'] = range_params return range_params def define_parameter(self, name, conf, default): param = default[name] try: param = conf[name] except KeyError: pass return param def run_simulation(self, conf): sources = { 'counter': 0 } self.init_simulation(conf, sources) while True: data = self.simulate_data(conf, sources) if data is not None: self.memory_manager.set_data(**conf['memspace'], data=data) try: time.sleep(conf['pause']) except KeyError: pass def init_simulation(self, conf, sources): # If constrained to a range, ensure the range is fully specified and # that the sources are suitably initialised if conf['function']['type'] in self.DEFAULTS['range']['types']: self.define_range(conf) sources['counter'] = conf['function']['range'][0] if conf['function']['type'] in self.DEFAULTS['random']['types']: try: random.seed(a=conf['function']['seed']) except KeyError: pass # Fallback to default parameters if not specified in configuration if conf['function']['type'] == 'lognormal': conf['function']['mu'] = self.define_parameter('mu', conf['function'], self.DEFAULTS['random']['lognormal']) conf['function']['sigma'] = self.define_parameter('sigma', conf['function'], self.DEFAULTS['random']['lognormal']) elif conf['function']['type'] == 'uniform': conf['function']['a'] = self.define_parameter('a', conf['function'], self.DEFAULTS['random']['uniform']) conf['function']['b'] = self.define_parameter('b', conf['function'], self.DEFAULTS['random']['uniform']) def simulate_data(self, conf, sources): data = bytearray(0) wlen = self.memory_manager.get_section_word_len(conf['memspace']['section']) nwords = int(conf['memspace']['nwords']) if conf['function']['type'] == 'counter': value = sources['counter'] sources['counter'] = self.get_next_range_value(conf['function']['range'], value) data = self.value_to_bytes(value, nwords, wlen) elif conf['function']['type'] == 'binary': value = sources['counter'] sources['counter'] = (value + 1) % 2 data = self.value_to_bytes(value, nwords, wlen) elif conf['function']['type'] == 'static': value = int(conf['function']['value']) data = self.value_to_bytes(value, nwords, wlen) elif conf['function']['type'] in self.DEFAULTS['wave']['types']: res = int(self.DEFAULTS['wave']['resolution']) value = sources['counter'] sources['counter'] = (value + 1) % (2 * res + 1) if conf['function']['type'] in ['sin','sine']: y = int(math.sin((value / res) * math.pi) * res + res) elif conf['function']['type'] in ['cos','cosine']: y = int(math.cos((value / res) * math.pi) * res + res) elif conf['function']['type'] == 'sawtooth': y = value elif conf['function']['type'] == 'square': w = math.sin((value / res) * math.pi) y = res if w < 0.0 else 2 * res data = self.value_to_bytes(y, nwords, wlen) elif conf['function']['type'] == 'randrange': value = random.randrange(*conf['function']['range']) data = self.value_to_bytes(value, nwords, wlen) elif conf['function']['type'] in self.DEFAULTS['random']['types']: res = int(self.DEFAULTS['random']['resolution']) if conf['function']['type'] == 'lognormal': w = random.lognormvariate(conf['function']['mu'], conf['function']['sigma']) y = int(w * res) % 2**(wlen * 8) # Avoid OverflowError elif conf['function']['type'] == 'uniform': w = random.uniform(conf['function']['a'], conf['function']['b']) y = int(w * res) data = self.value_to_bytes(y, nwords, wlen) elif conf['function']['type'] == 'copy': data = self.memory_manager.get_data(**conf['source']['memspace']) elif conf['function']['type'] == 'transform': buf = self.memory_manager.get_data(**conf['source']['memspace']) word = int.from_bytes(buf, byteorder=self.DEFAULTS['byteorder']) value = self.transform_item(word, conf['function']['transform']) if value is not None: data = self.value_to_bytes(value, nwords, wlen) else: data = None return data def value_to_bytes(self, value, nwords, wlen): data = bytearray(0) b = value.to_bytes(wlen, byteorder=self.DEFAULTS['byteorder']) for i in range(nwords): data += b return data def get_next_range_value(self, range_params, value): next_value = value + range_params[2] if range_params[2] < 0: if next_value <= range_params[1]: next_value = range_params[0] else: if next_value >= range_params[1]: next_value = range_params[0] return next_value def transform_item(self, state, transform): item = None t_in = transform['in'] t_out = transform['out'] # If the transform output is configured as 'null', then it takes the # value of the state variable if t_out is None: t_out = state if isinstance(t_in, (list, tuple)): if t_in[0] <= state <= t_in[1]: item = t_out elif state == t_in: item = t_out return item
nilq/baby-python
python
from django.urls import path from api import view as local_view from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('top-movie/', local_view.top_movie), path('detail-movie/<int:id>', local_view.detail_movie), ] +static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
nilq/baby-python
python
import os import time import random import tkinter import threading import subprocess import glob from ascii_art import * from widgets import * import platform platform = platform.system() # thanks to everyone on https://www.asciiart.eu/ class FILE_HANDLER(object): """ File opening and closing yes""" def __init__(self, parent): self.current_dir = os.getcwd() print("start dir: ", self.current_dir) self.current_file = None self.current_file_name = None self.current_buffer = None self.buffer_dict = {} self.buffer_list = [] self.buffer_tab = None self.buffer_tab_index = None # buffer tabs have the same index as text widgets self.buffer_tab_list = [] self.scratch_buffer = None self.parent = parent def closing_sequence(self) -> None: for b in self.buffer_list[1:]: self.close_buffer(buffer_name=b[0].full_name) def init(self, buffer_name: str): self.scratch_buffer = TEXT(self.parent, buffer_name, "temp") self.buffer_list.append([self.scratch_buffer, BUFFER_TAB(buffer_name, self.parent, render=False)]) self.buffer_dict[buffer_name] = self.buffer_list[-1] self.parent.buffer_render_list.insert(self.parent.buffer_render_index, self.buffer_list[-1][0]) self.parent.buffer = self.parent.buffer_render_list[self.parent.buffer_render_index] self.buffer_tab = self.buffer_list[-1][1] self.buffer_tab_list.append(self.buffer_list[-1][1]) self.parent.title(f"Nix: <{self.parent.buffer.name}>") self.parent.buffer.insert("1.0", "\nhttps://www.asciiart.eu/") self.parent.buffer.insert("1.0", art[random.randint(0, len(art)-1)]) self.parent.buffer.mark_set("insert", len(self.parent.buffer.get("1.0", "end").split("\n"))/2) self.parent.buffer.tag_add("center", "1.0", "end") # def load_scratch(self, arg=None): # self.parent.buffer_unplace() # self.parent.buffer_render_list.insert(self.parent.buffer_render_index, self.buffer_list[0][0]) # self.parent.buffer = self.parent.buffer_render_list[self.parent.buffer_render_index] # self.parent.buffer.focus_set() # self.parent.reposition_widgets() # self.parent.title(f"Nix: <{self.parent.buffer.name}>") # self.parent.buffer.font_size_set() # self.parent.theme_load() # if (arg): return "break" def buffer_exists(self, buffer_name): try: self.buffer_dict[buffer_name] return 1 except KeyError: return 0 def rename_buffer(self, buffer_name: str, new_buffer_name: str): old = self.buffer_dict.pop(buffer_name) index = old[0].buffer_index self.buffer_list[index][0].change_name(new_buffer_name) self.buffer_list[index][1].change_name(new_buffer_name) self.buffer_tab_list[index].change_name(new_buffer_name) old[0].change_name(new_buffer_name) old[1].change_name(new_buffer_name) self.buffer_dict[new_buffer_name] = old self.parent.buffer = self.buffer_dict[new_buffer_name][0] self.current_file_name = self.current_buffer = new_buffer_name def new_buffer(self, buffer_name, buffer_type="normal"): if (self.buffer_exists(buffer_name)): self.load_buffer(buffer_name=buffer_name); return if (buffer_type == "GRAPHICAL"): self.buffer_list.append([GRAPHICAL_BUFFER(self.parent, buffer_name), BUFFER_TAB(buffer_name, self.parent)]) else: self.buffer_list.append([TEXT(self.parent, buffer_name, buffer_type), BUFFER_TAB(buffer_name, self.parent)]) self.buffer_dict[buffer_name] = self.buffer_list[-1] self.buffer_tab_list.append(self.buffer_list[-1][1]) self.load_buffer(buffer_name=buffer_name) def close_buffer(self, arg=None, buffer_name: str=None): if (not buffer_name): buffer_name = self.parent.buffer.full_name buffer_index = self.buffer_dict[buffer_name][0].buffer_index for i, buffer in enumerate(self.parent.buffer_render_list, 0): if (buffer == self.buffer_dict[buffer_name][0]): self.parent.buffer_render_list.pop(i) self.parent.split_mode = "nosplit" self.parent.buffer_render_index = i-1 if i-1 >= 0 else 0 self.buffer_dict[buffer_name][0].unplace() self.buffer_dict[buffer_name][1].unplace() if (self.parent.conf["backup_files"]): self.del_file(filename=f".{os.path.basename(buffer_name)}.error_swp") # if (len(self.buffer_dict[buffer_name].get("1.0", "end-1c")) == 0): self.del_file(filename=buffer_name) # deletes created file if the text buffer is empty self.buffer_tab_list.pop(buffer_index) self.buffer_list.pop(buffer_index) self.buffer_dict.pop(buffer_name) for i in range(0, len(self.buffer_list)): self.buffer_list[i][0].buffer_index = i self.buffer_list[i][1].buffer_index = i self.buffer_list[i][1].reposition() # self.load_buffer(buffer_index=len(self.buffer_list)-1) # if (len(self.buffer_list) == 0): self.load_buffer(buffer_index=buffer_index) if (arg): return "break" def load_buffer(self, arg=None, buffer_name: str = None, buffer_index: int = None): if (buffer_index and buffer_index >= len(self.buffer_list)): buffer_index = 0 if (buffer_index is not None): buffer_name = self.buffer_list[buffer_index][0].full_name if (self.parent.buffer.full_name == buffer_name): return p = self.parent.buffer if (len(self.parent.buffer_render_list)-1 < self.parent.buffer_render_index): self.parent.buffer_render_list.insert(self.parent.buffer_render_index, self.buffer_dict[buffer_name][0]) else: self.parent.buffer_render_list[self.parent.buffer_render_index] = self.buffer_dict[buffer_name][0] self.parent.buffer = self.parent.buffer_render_list[self.parent.buffer_render_index] self.buffer_tab = self.buffer_dict[buffer_name][1] self.buffer_tab_index = self.parent.buffer.buffer_index # text widget's buffer_index is the same as their buffer tab's buffer_index # if (buffer_index != 0): self.current_file_name = self.current_buffer = self.parent.buffer.full_name; self.current_dir = os.path.dirname(self.current_buffer) self.set_current_file(buffer_name=buffer_name) self.parent.title(f"Nix: <{self.parent.buffer.name}>") if (type(self.parent.buffer) == "TEXT"): self.parent.buffer.font_size_set() self.parent.theme_load() if (self.parent.conf["show_buffer_tab"]): self.buffer_tab.focus_highlight() self.parent.reposition_widgets() self.parent.notify(arg=f"buffer [{self.parent.buffer.name}] was loaded", tags=[["1.7", "1.8", "logical_keywords"], ["1.8", f"1.{8+len(self.parent.buffer.name)}"], [f"1.{8+len(self.parent.buffer.name)}", f"1.{9+len(self.parent.buffer.name)}", "logical_keywords"]]) if (self.parent.focus_get() == p or self.parent.focus_get() == self.parent.command_out): self.parent.buffer.focus_set() elif (self.parent.focus_get() == self.parent.find_entry): self.parent.find_entry.focus_set() p.unplace() # weird (seemingly) optimalization trick if (arg): return "break" def set_current_file(self, arg=None, buffer_name=None): self.current_file_name = self.current_buffer = self.parent.buffer.full_name tmp = os.path.dirname(self.current_buffer) if (tmp): self.current_dir = tmp self.buffer_tab_index = self.parent.buffer.buffer_index if (self.parent.conf["show_buffer_tab"]): self.buffer_tab.configure_self() self.buffer_tab = self.buffer_dict[buffer_name][1] self.buffer_tab.focus_highlight() else: self.buffer_tab = self.buffer_dict[buffer_name][1] def list_buffer(self, arg=None): result = "" for val in self.parent.file_handler.buffer_list: result += f"{val[1].full_name}\n" self.parent.command_out.change_ex(self.parent.command_out.buffer_load) if (not result): result = "<None>" self.parent.command_out_set(result) def del_file(self, arg=None, filename:str=""): if (not filename): filename=self.parent.buffer.full_name if (self.buffer_exists(filename)): self.close_buffer(buffer_name=filename) if (os.path.isfile(filename)): os.remove(filename); self.parent.notify(f"File [{filename}] was deleted") else: self.parent.notify(f"File ({filename}) does not exist") if (arg): return "break" def new_file(self, arg=None, filename: str=""): if (not filename): i = 0 filename = f"{self.current_dir}/untitled_{i}.txt" while (os.path.isfile(filename)): i += 1 filename = f"{self.current_dir}/untitled_{i}.txt" filename = os.path.abspath(filename) try: current_file = open(filename, "w+") self.new_buffer(filename) current_file.close() except PermissionError: self.new_buffer(filename, buffer_type="readonly") self.current_dir = os.path.dirname(filename) self.parent.title(f"Nix: <{self.parent.buffer.name}>") self.parent.buffer.set_highlighter() if (arg): return "break" def save_file(self, arg = None): """ saves current text into opened file """ if (self.parent.buffer.type != "normal"): self.parent.error(f"{self.parent.buffer.type} buffer") ;return "break" if (self.parent.buffer.full_name): size0 = os.path.getsize(self.parent.buffer.full_name) current_file = open(self.parent.buffer.full_name, "w") current_file.write(self.parent.buffer.get("1.0", "end-1c")) current_file.close() self.parent.buffer.file_start_time = os.stat(self.parent.buffer.full_name).st_mtime self.parent.buffer.set_highlighter() size1 = os.path.getsize(self.parent.buffer.full_name) self.current_dir = os.path.dirname(self.parent.buffer.full_name) self.parent.title(f"Nix: <{os.path.basename(self.parent.buffer.name)}>") self.parent.buffer.state_set(pop=["*", "!"]) # self.buffer_tab.change_name(extra_char=" ") self.parent.notify(rf"saved [{size1-size0}B|{size1}B|{self.parent.buffer.get_line_count()}L] to {self.current_file_name}") elif (not self.current_file_name): self.new_file() self.save_file() if (arg): return "break" def save_file_as(self, arg=None, filename=None, new_filename=None): """ saves current text into a new file """ if (filename): filename = os.path.abspath(f"{self.current_dir}/{filename}") else: filename = self.parent.buffer.full_name new_filename = os.path.abspath(f"{self.current_dir}/{new_filename}") print("saveas: ", new_filename) os.rename(filename, new_filename) self.rename_buffer(filename, new_filename) self.save_file() self.parent.highlight_chunk() if (arg): return "break" def load_file(self, arg=None, filename=None): """ opens a file and loads it's content into the text widget """ buffer_type = "normal" # if (filename): # if (not os.path.isfile(filename)): filename = os.path.abspath(f"{self.current_dir}/{filename}") # if (self.buffer_exists(filename)): self.load_buffer(buffer_name=filename) if (not os.path.isfile(filename)): self.new_file(filename=filename) return try: current_file = open(filename, "r+") #opens the file except PermissionError: current_file = open(filename, "r") buffer_type = "readonly" t0 = time.time() # timer| gets current time in miliseconds self.current_dir = os.path.dirname(filename) try: file_content = current_file.read() except Exception: current_file.close() self.new_buffer(filename, buffer_type="GRAPHICAL"); return self.new_buffer(filename, buffer_type=buffer_type) if (self.parent.conf["backup_files"]): file = open("."+os.path.basename(filename)+".error_swp", "w+") file.write(file_content) file.close() self.parent.buffer.delete("1.0", "end") #deletes the buffer so there's not any extra text self.parent.buffer.insert("1.0", file_content) #puts all of the file's text in the text widget self.parent.buffer.total_chars = len(file_content)+1 self.parent.buffer.total_lines = self.parent.buffer.get_line_count() # if (platform == "Windows"): self.parent.convert_to_crlf() # else: self.parent.convert_to_lf() self.parent.buffer.mark_set("insert", "1.0") #puts the cursor at the start of the file self.parent.buffer.see("insert") current_file.close() self.parent.highlight_chunk() #highlights the text in the text widget t1 = time.time() # timer| gets current time in miliseconds elapsed_time = round(t1-t0, 3) #elapsed time # puts the time it took to load and highlight the text in the command output widget self.parent.notify(f"total lines: {self.parent.buffer.get_line_count()}; loaded in: {elapsed_time} seconds", tags=[ ["1.12", f"1.{13+len(str(self.parent.buffer.get_line_count()))}"], [f"1.{15+len(str(self.parent.buffer.get_line_count()))+11}", f"1.{15+len(str(self.parent.buffer.get_line_count()))+11+len(str(elapsed_time))}"] ]) # wild... self.parent.title(f"Nix: <{self.parent.buffer.name}>") del file_content if (arg): return "break" def new_directory(self, arg=None, filename=None): path = f"{self.current_dir}/{filename}" if (os.path.isdir(path)): self.parent.notify(f"Directory <{filename}> already exists") else: os.mkdir(path) self.parent.notify(f"Directory <{filename}> was created") def delete_directory(self, arg=None, filename=None): path = f"{self.current_dir}/{filename}" if (os.path.isdir(path)): os.rmdir(path) self.parent.notify(f"Directory <{filename}> was succesfully deleted") else: self.parent.notify(f"Directory <{filename}> does not exist") def directory_list_get(self, dir=None, expr=None): if (not dir): dir = self.current_dir dir = os.listdir(dir) fdir = dir if (expr): expr = expr.replace(".", r"\.") expr = expr.replace("*", r"(.)*") dir = [file for file in fdir if re.match(expr, file)] dir.sort() dir.insert(0, "..") return dir def cd(self, dir): if (os.path.isdir(dir)): self.current_dir = dir self.parent.notify(arg=f"current directory: {self.current_dir}") else: self.parent.error(arg=f"File/Directory {dir} not found") return False return True def ls(self, dir=None, sep=" ", expr=None): if (not dir): dir = self.directory_list_get() result = "" for i, file in enumerate(dir, 0): result += file+sep return result def highlight_ls(self, dir=None): if (not dir): dir = self.directory_list_get() result = "" tags = [] for i, file in enumerate(dir, 0): if (os.path.isdir(f"{self.current_dir}/{file}")): tags.append([f"{i+1}.0", f"{i+1}.{len(file)}"]) result += file+"\n" return result, tags class TODO_HANDLER: def __init__(self, parent): self.parent = parent self.filename = self.parent.todo_filename def create_task(self): pass def delete_task(self): pass def set_task(self): pass def create_file(self): pass def format_file(self): pass def delete_file(self): pass def create_task_from_file(self): pass class MUSIC_PLAYER(object): def __init__(self, parent): try: from pygame import mixer except ImportError as e: parent.notify(f"ERROR: couldn't create music player, because pygame module couldn't be imported \n {e}"); return self.parent = parent self.volume = 1 self.paused = False mixer.init() mixer.music.set_volume(self.volume) def load_song(self, name: str): try: mixer.music.load(*name) mixer.music.play() except Exception as e: print(e) self.parent.notify("invalid file") def play_song(self, time: int = 0): mixer.music.play(start=time) def pause_song(self, unpause=False): if (not self.paused): self.paused = True mixer.music.pause() elif (self.paused or unpause): self.paused = False mixer.music.unpause() def stop_song(self): mixer.music.stop() def queue(self): pass class VIDEO_HANDLER: def __init__(self, parent): self.parent = parent def video_record_start(self, filename=f"{time.time()}"): """ if you wanna record some video of your code (probably only works on linux (and you have to have ffmpeg installed""" pos = f":1.0+{self.parent.winfo_rootx()},{self.parent.winfo_rooty()}" videosize = f"{self.parent.winfo_width()}x{self.parent.winfo_height()}" path = self.parent.file_handler.current_dir filename = f"{filename}.mkv" args = [ ["-f", "x11grab"], ["-framerate", "120"], # ["-video_size", videosize], ["-i", f"{self.parent.title()}"], ["-vcodec", "libx264"], ["-qscale", "0"] ] print(args) command = f"cd {path}; ffmpeg " for arg in args: command += f"{arg[0]} {arg[1]} " command += filename return subprocess.Popen(command, stdin=subprocess.PIPE, shell=True) def video_record_stop(self, process): process.communicate(b"q") print("terminated") def screenshot(self): def s(): process = self.video_record_start(filename="screenshot") time.sleep(0.5) self.video_record_stop(process) command = f"ffmpeg -i screenshot.mkv -ss 00:00:00 -frames:v 1 {time.time()}.png" process = subprocess.Popen(command, stdin=subprocess.PIPE, shell=True) while (process.poll() == None): continue os.remove("screenshot.mkv") threading.Thread(target=s, daemon=True).start()
nilq/baby-python
python
#!/usr/bin/env python # coding: utf-8 import os import numpy as np import pandas as pd import matplotlib.pylab as pylab import matplotlib.pyplot as plt import matplotlib.artist as martist from matplotlib.offsetbox import AnchoredText import pylab as plt os.chdir('/Users/pauline/Documents/Python') df = pd.read_csv("Tab-Morph.csv") params = {'figure.figsize': (4, 4), 'figure.dpi': 300, 'font.family': 'Palatino', 'axes.labelsize': 8, 'xtick.labelsize': 8, 'axes.labelpad': 1, 'lines.markerfacecolor': 'salmon', 'lines.markeredgewidth': .2, 'lines.markersize': 13, 'lines.linewidth': .5, 'figure.titlesize': 7, 'figure.constrained_layout.w_pad': 0.04167 } pylab.rcParams.update(params) def add_at(ax, t, loc=2): fp = dict(size=8) _at = AnchoredText(t, loc=loc, prop=fp) ax.add_artist(_at) return _at # define figure fig = plt.figure() fig.suptitle('Geomorphologycal analysis of the Mariana Trench: \n25 cross-section profiles unsorted (A) and sorted (B) \n by steepness gradient', x=0.5, y=0.97) # subplot 1 plt.subplot(2, 1, 1) ax1 = fig.add_subplot(211) x = df.profile values = df.tg_angle markerline, stemlines, baseline = plt.stem(x, values, markerfmt="o", basefmt='-', use_line_collection=True) plt.setp(markerline, alpha=0.7) plt.setp(stemlines, color='dimgray') plt.setp(baseline, color='purple', linewidth=1) plt.xlabel('Cross-section profiles') plt.ylabel('tg$^\circ$ (A/H)') add_at(ax1, "A") # subplot 2 plt.subplot(2, 1, 2) ax2 = fig.add_subplot(212) df = pd.DataFrame({'group':df.profile, 'values':df.tg_angle}) ordered_df = df.sort_values(by='values') markerline, stemlines, baseline = plt.stem(x, ordered_df['values']) plt.setp(markerline, alpha=0.7) plt.xticks(x, ordered_df['group']) plt.xlabel('Cross-section profiles') plt.ylabel('tg$^\circ$ (A/H)') add_at(ax2, "B") # visualizing plt.tight_layout() plt.subplots_adjust(top=0.85, bottom=0.15, left=0.20, right=0.95, hspace=0.25, wspace=2.8 ) plt.savefig('plot_Stems.png') plt.show()
nilq/baby-python
python
import sys import os from subprocess import (Popen, PIPE, STDOUT) APP = os.path.abspath(os.path.join(os.path.dirname(__file__), 'run.py')) """The Python script to run.""" def spawn(): """ Start the Quantitaive Imaging Profile REST server. :return: the completed process return code """ # The cumbersome but apparently necessary idiom below is required to # continuously pipe the server output to the console # (cf. http://stackoverflow.com/questions/4417546/constantly-print-subprocess-output-while-process-is-running). proc = Popen(['python', APP], stdout=PIPE, stderr=STDOUT) while True: line = proc.stdout.readline() if line == '' and proc.poll() != None: break sys.stdout.write(line) sys.stdout.flush() out, _ = proc.communicate() rc = proc.returncode return rc
nilq/baby-python
python
#! /usr/bin/env python import logging import os import sys gitpath=os.path.expanduser("~/git/cafa4") sys.path.append(gitpath) from fastcafa.fastcafa import * gitpath=os.path.expanduser("~/git/pyEGAD") sys.path.append(gitpath) from egad.egad import * #SALMON_NET=os.path.expanduser('~/data/cococonet/atlanticsalmon_prioAggNet.hdf5') #SALMON_NET=os.path.expanduser('~/data/cococonet/atlanticsalmon_metaAggNet.Rdata') HUMAN_NET=os.path.expanduser('~/data/cococonet/human_prioAggNet.hdf5') HUMAN_GOA=os.path.expanduser('~/data/goa/goa_human_gomatrix.csv') PREDOUT=os.path.expanduser('~/play/jones/gillis_seqs.predout') # G803000000001 GO:0005667 0.10 # G803000000001 GO:0043966 0.10 # G803000000001 GO:0045893 0.10 SEQ_IDMAP=os.path.expanduser('~/play/jones/salmon_hiprio_seqmap.tsv') # G803000000001 A0A1S3SK04_SALSA # G803000000002 A0A1S3RA14_SALSA # G803000000003 A0A1S3RDQ3_SALSA # UID_GN_MAP=os.path.expanduser('~/play/jones/uniprot-trembl-salmon.8030.map.tsv') # db acc uid gn # tr A0A1S3RID5 A0A1S3RID5_SALSA LOC106602976 # tr B5XFF4 B5XFF4_SALSA WRB # UID_GN_MAP=os.path.expanduser('~/data/cococonet/human_uid_map.tsv') OUTFILE=os.path.expanduser('~/play/jones/human_goa_results.tsv') def read_network_hdf5(filename): """ Loads data in file to dataframe. """ with h5py.File(filename, 'r') as f: logging.debug("reading matrix...") matrix = f['agg'][:] logging.debug("reading rows. converting to unicode.") rows = [ s.decode() for s in f['row'][:] ] logging.debug("reading columns. converting to unicode") columns = [ s.decode() for s in f['col'][:] ] logging.debug("making dataframe...") df = pd.DataFrame(matrix, index=rows, columns = columns ) logging.debug(f"network shape: {df.shape}") logging.debug(f"network:\n {df}") return df def read_predout(predout, seqidmap): columns = ['seqid','goterm','prob'] df = pd.read_csv(predout, sep='\t', header=None, names=columns) logging.debug(f"predout shape: {df.shape}") columns = ['seqid','uid'] smdf = pd.read_csv(seqidmap, sep='\t', header=None, names=columns) logging.debug(f"seqmap shape: {smdf.shape}") logging.debug(f"seqmap:\n{smdf}") fixedpredout = pd.merge(df, smdf, how='left', on=['seqid']) fixedpredout.drop(['seqid'], inplace=True, axis=1) logging.debug(f"fixed pred out is \n{fixedpredout}") return fixedpredout def fix_rowcol_names(network, mapfile): ugm = pd.read_csv(mapfile, sep='\t', header=0, index_col=0) logging.debug(f"uid_gn_map:\n{ugm}") #mapdict = pd.Series(ugm.uid.values, index=ugm.gn).to_dict() mapdict = pd.Series(ugm.gn.values, index=ugm.uid).to_dict() logging.debug(f"mapdict={mapdict}") gncolumns = list(network.columns) logging.debug(f"columnlist={gncolumns}") newcols = [] for g in gncolumns: try: n = mapdict[g] logging.debug(f"got mapping {g} ->{n}") if pd.isna(n): newcols.append(g) else: newcols.append(n) except KeyError: logging.debug(f"mapping error with {g}") newcols.append(g) logging.debug(f"newcols={newcols[:10]} length={len(newcols)}") logging.debug(f"network shape={network.shape} assigning columns..") network.columns=newcols logging.debug("assigning row index..") network.index = newcols logging.debug("done.") return network if __name__ == '__main__': FORMAT='%(asctime)s (UTC) [ %(levelname)s ] %(filename)s:%(lineno)d %(name)s.%(funcName)s(): %(message)s' logging.basicConfig(format=FORMAT) logging.getLogger().setLevel(logging.DEBUG) logging.info(f"Reading network: {HUMAN_NET}") nw = read_network_hdf5(HUMAN_NET) logging.info(f"network:\n{nw}") nw = fix_rowcol_names(nw, UID_GN_MAP) logging.info(f"fixed network:\n{nw}") #logging.info(f"Reading predictions: {PREDOUT}") #po = read_predout(PREDOUT, SEQ_IDMAP) #po.to_csv(f"{PREDOUT}.csv", sep="\t") #ogging.info(f"\n{po}") #amdf = build_annotation_matrix(po, 'uid','goterm') #logging.info(f"\n{amdf}") logging.debug(f"Reading in {HUMAN_GOA} ...") adf = pd.read_csv(HUMAN_GOA, sep=',', index_col=0) logging.info(f"input to run_egad: genesXgo:\n{adf}\ngenesXgenes:\n{nw}") outdf = run_egad(adf, nw ) logging.info(f"\n{outdf}") outdf.to_csv(f"{OUTFILE}", sep='\t') #logging.info(f"Wrote to {OUTFILE}")
nilq/baby-python
python
''' Created on Feb 7, 2011 @author: patnaik ''' import sys import time from collections import defaultdict from parallel_episode_mine import load_episodes from itertools import izip from numpy import diff from math import sqrt class S(object): def __init__(self, alpha, event): self.alpha = alpha self.event = event self.count = 1 self.init = 0.0 self.pid = -1 def __str__(self): return '(%d,%d)' % (self.alpha, self.event) def get_span(s_list): t_min = sys.float_info.max; t_max = 0.0 for s in s_list: if t_min > s.init: t_min = s.init if t_max < s.init: t_max = s.init return (t_max - t_min) def nest_advanced(autos): qlist = [(q.init, q.event) for q in autos] qlist.sort() flist = []; eps_list = [qlist[0]] flist.append(eps_list) for i in xrange(1, len(qlist)): if eps_list[-1][0] == qlist[i][0]: eps_list.append(qlist[i]) else: eps_list = [qlist[i]] flist.append(eps_list) qtuple = [] for eps_list in flist: if len(eps_list) > 1: temp_list = [rec[1] for rec in eps_list] temp_list.sort() qtuple.append(tuple(temp_list)) else: qtuple.append(eps_list[0][1]) qtuple = tuple(qtuple) return qtuple, None def nest_simple(autos): qlist = [(q.init, q.event) for q in autos] qlist.sort() #qtuple = tuple([event for (_, event) in qlist]) ttuple, qtuple = zip(*qlist) t_ivl = tuple(diff(ttuple)) return qtuple, t_ivl nest = nest_simple def track_candidates(stream, candidates, level, expiry): pcount = 0 n = len(candidates) counts = [0 for _ in xrange(n)] counter = [0 for _ in xrange(n)] autos = [list() for _ in xrange(n)] span = [0.0 for _ in xrange(n)] order = [defaultdict(int) for _ in xrange(n)] waits = defaultdict(list) t_ivl_s = [defaultdict(lambda: [0.0] * (level-1)) for _ in xrange(n)] t_ivl_ss = [defaultdict(lambda: [0.0] * (level-1)) for _ in xrange(n)] if candidates: for alpha, candidate in enumerate(candidates): for event in candidate: s = S(alpha, event) waits[event].append(s) autos[alpha].append(s) prev_pid = -1 for (pid, event, med_type, t) in stream: if med_type == 'PX': continue if pid != prev_pid: pcount += 1 prev_pid = pid #if pcount > 100: break for s in waits[event]: alpha = s.alpha if s.count == 1: s.count = 0 counter[alpha] += 1 s.init = t s.pid = pid #Expiry check if counter[alpha] == level: for q in autos[alpha]: #print expiry, t, q.init, pid, q.pid, event if (t - q.init) > expiry or (pid != q.pid): counter[alpha] -= 1 q.count += 1 #Update episode count if counter[alpha] == level: # Update episode counters counts[alpha] += 1 span[alpha] += get_span(autos[alpha]) # Reset automaton counters counter[alpha] = 0 qtuple, t_ivl = nest(autos[alpha]) vect_s = t_ivl_s[alpha][qtuple] vect_ss = t_ivl_ss[alpha][qtuple] for i in xrange(len(t_ivl)): vect_s[i] = vect_s[i] + t_ivl[i] vect_ss[i] = vect_ss[i] + (t_ivl[i] * t_ivl[i]) order[alpha][qtuple] += 1 for q in autos[alpha]: q.count = 1 for alpha in xrange(len(candidates)): if counts[alpha] > 0: span[alpha] /= float(counts[alpha]) return counts, span, pcount, order, t_ivl_s, t_ivl_ss from emr_mine import emr_all_data if __name__ == "__main__": # stream_file = '../../emrdata/Pts_1_to_150000.txt.cleaned' # episodes_folder = "../../emr_results/Pts_1_to_150000" levels = [7]# [3, 4, 5, 6, 7] stream_generator = lambda: emr_all_data('../../emrdata') #episodes_folder = "../../emr_results/all-data-lift-10" episodes_folder = "../../emr_results/all-data-lift-5" n = 1620552 #1.6 million settings = { 'expiry' : 200, #in days (see episode_miner) 'support' : 0.0001 } i = 0 for level in levels: print 'Loading episodes from:', episodes_folder frequent, level, settings = load_episodes(episodes_folder, settings, n, level) expiry = settings['expiry'] support = settings['support'] print 'Loaded %d-size episodes: %d' % (level, len(frequent)) print 'Counting %d %d-size candidate episodes...' % (len(frequent), level) t1 = time.clock() counts, spans, n_new, order, t_ivl_s, t_ivl_ss = track_candidates(stream_generator(), frequent, level, expiry) t2 = time.clock() print 'Time taken = %.2f sec' % (t2-t1) print 'n = %d, n_new = %d' % (n, n_new) fepisodes = episodes_folder + "/emr-episode-set-%d.txt" % level fout = open(fepisodes, "w") if level == levels[0]: print >> fout, "#Parallel episodes mined with support = %.4f and expiry constraint = %d days." % (settings['support'], settings['expiry']) print >> fout, "#Tot. no. of patients rec. sequences = %d." % n print 'Writing partial-orders data to file:', fepisodes for episode, count, span, serial_map, map_s, map_ss in izip(frequent, counts, spans, order, t_ivl_s, t_ivl_ss): print >> fout, "%d,%d,%d" % (i+1, len(serial_map), count) print >> fout, "|".join(episode) #print episode, count, span serial_episodes = serial_map.items() serial_episodes.sort(key=lambda rec: rec[1], reverse=True) cum_sum = 0; flag = 1 for serial_episode, serial_count in serial_episodes: vect_s = map_s[serial_episode] vect_ss = map_ss[serial_episode] mean_vect = []; sd_vect = [] for ls, ss in izip(vect_s, vect_ss): mean_t = float(ls)/float(serial_count) mean_vect.append("%.2f" % mean_t) try: sd_vect.append("%.2f" % (sqrt(float(ss - mean_t**2)/float(serial_count)))) except Exception, e: print "ls = %f, ss = %f, serial_count = %d" % (ls, ss, serial_count) print "vect_s =", vect_s print "vect_ss =", vect_ss raise e str_mean_vect = "|".join(mean_vect) str_sd_vect = "|".join(sd_vect) str_serial_episode = "|".join(serial_episode) print >> fout, "%s:%d:%d:%s:%s" % (str_serial_episode, serial_count, flag, str_mean_vect, str_sd_vect) cum_sum += serial_count if cum_sum >= 0.75 * count: flag = 0 i += 1 print "###", cum_sum, count, cum_sum == count fout.close()
nilq/baby-python
python
#!/usr/bin/env python """ Copyright (C) 2018 Intel Corporation ? Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at ? http://www.apache.org/licenses/LICENSE-2.0 ? Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ? SPDX-License-Identifier: Apache-2.0 """ from testlib.scripts.android.ui.automotive_O import ui_utils as parent_ui_utils from testlib.base.abstract.abstract_step import inherite @inherite(parent_ui_utils.click_apps_entry) def click_apps_entry(): """ description: performs click on an application from Apps page with auto scroll support if <app> = False it will search through widget pages usage: ui_utils.click_apps_entry(app = True, **self.view_to_find) tags: ui, android, click, app, scroll """ pass @inherite(parent_ui_utils.dict_element_of_list) def dict_element_of_list(): """ description: Check if <dict> is part of dict list <my_dict_list> usage: ui_utils.dict_element_of_list(my_dict_list, dict) tags: ui, android, helper, dict, list """ pass @inherite(parent_ui_utils.count_apps_pages) def count_apps_pages(): """ description: return the number of Apps pages (not Widgets) you must be in first page of All Apps (this is true after ui_steps.press_all_apps) usage: ui_utils.count_apps_pages() tags: ui, android, swipe, apps """ pass @inherite(parent_ui_utils.is_switch_on) def is_switch_on(): """ description: return true if the switch in "ON" usage: ui_utils.is_switch_on(view_to_find = {"resourceId": "com.intel.TelemetrySetup:id/text", "instance":"1"}) tags: ui, android, switch, enabled, disabled """ pass @inherite(parent_ui_utils.is_text_visible) def is_text_visible(): """ description: return true if text is visible on screen If it's a list on screen, it also scrolls through it. usage: ui_utils.is_text_visible("text_to_find") tags: ui, android, text, visible """ pass @inherite(parent_ui_utils.is_view_visible) def is_view_visible(): """ description: return true if <view_to_find> is visible on screen. if <click> is True, it will click on the view before return. If it's a list on screen, it also scrolls through it. usage: ui_utils.is_text_visible("text_to_find") tags: ui, android, view, visible """ pass @inherite(parent_ui_utils.is_view_visible_scroll_left) def is_view_visible_scroll_left(): """ description: return true if view is visible on screen. If <click> is True, it will click on the view before return. If there are multiple pages, it will scroll to them to the left. usage: ui_utils.is_text_visible_scroll_left("text_to_find") tags: ui, android , view, visible, swipe, scroll """ pass @inherite(parent_ui_utils.is_text_visible_scroll_left) def is_text_visible_scroll_left(): """ description: return true if the view with given text is visible on screen. If there are multiple pages, it will scroll to them to the left. usage: ui_utils.is_text_visible_scroll_left("App") tags: ui, android , text, visible, swipe, scroll """ pass @inherite(parent_ui_utils.is_enabled) def is_enabled(): """ description: return true if element is enabled, false if disabled (grayed out in UI). Ignore 'enabled' parameter if you only want to check status. Use 'enabled' (True, False) to state the expected status usage: ui_utils.is_enabled(view_to_find = {"resourceId": "com.intel.TelemetrySetup:id/text"}, enabled = True) tags: ui, android, view, enabled, disabled """ pass @inherite(parent_ui_utils.is_radio_button_enabled) def is_radio_button_enabled(): """ description: Check the actual state of a radio button. Return True if radio button checked or false if unchecked usage: ui_utils.is_radio_button_enabled(instance = 0) tags: ui, android, radio, enabled, disabled """ pass @inherite(parent_ui_utils.is_checkbox_checked) def is_checkbox_checked(): """ description: check the actual state of a checkbox usage: ui_utils.is_checkbox_checked(view_to_find = {"text":"view_text"}) tags: ui, android, check, enabled, disabled """ pass @inherite(parent_ui_utils.move_slider) def move_slider(): """ description: move the slider to position which is a percentage the percentage is not very precise due to slider borders position = 100 means move slider to 100% x_min_delta, x_max_delta are offset for finding actual slider position usage: ui_utils.move_slider(view_to_find = { "className":'android.widget.SeekBar', "instance":0}, position = 30) tags: ui, android, slider, move """ pass @inherite(parent_ui_utils.get_resolution) def get_resolution(): """ description: Gets the resolution of the screen usage: ui_utils.get_resolution() tags: ui, android, resolution """ pass @inherite(parent_ui_utils.is_developer_options_enabled) def is_developer_options_enabled(): """ description: Check if developer options is enabled usage: ui_utils.is_developer_options_enabled() tags: ui, android, settings, developer """ pass @inherite(parent_ui_utils.get_view_middle_coords) def get_view_middle_coords(): """ description: Return the coordinates for the middle of the view usage: ui_utils.get_view_middle_coords() tags: ui, android, view, center """ pass @inherite(parent_ui_utils.is_device_locked) def is_device_locked(): """ description: Check if the device is locked usage: ui_utils.is_device_locked() tags: ui, android, lock """ pass @inherite(parent_ui_utils.bxtp_car_locked) def bxtp_car_locked(): pass @inherite(parent_ui_utils.is_device_pin_locked) def is_device_pin_locked(): """ description: Check if the device is locked with pin usage: ui_utils.is_device_pin_locked() tags: ui, android, lock, pin """ pass @inherite(parent_ui_utils.is_view_displayed) def is_view_displayed(): """ description: Return True if <view_to_find> is visible on screen. usage: ui_utils.is_view_displayed(view_to_find = {"Text": "text"}) tags: ui, android, view, displayed """ pass @inherite(parent_ui_utils.check_google_account) def check_google_account(): """ description: Check if a Google account is configured on the device usage: ui_utils.check_google_account() tags: ui, android, account, google """ pass @inherite(parent_ui_utils.google_account_exists) def google_account_exists(): """ description: Check if a Google account is configured on the device from DB usage: ui_utils.google_account_exists() tags: ui, android, account, google, sqlite, db """ pass @inherite(parent_ui_utils.get_view_text) def get_view_text(): """ description: Get text information from a view. If view cannot be found, return False usage: ui_utils.get_view_text(view_to_find = {"resourceId": "android:id/hours"}) tags: ui, android, view, text """ pass @inherite(parent_ui_utils.view_exists) def view_exists(): """ description: Check if view exists usage: ui_utils.view_exists(view_to_find = {"resourceId": "android:id/hours"}) tags: ui, android, view """ pass @inherite(parent_ui_utils.wait_for_view) def wait_for_view(): """ description: Wait for specified view, <wait_time> miliseconds. Return False if view does not exist after <wait_time> ms. usage: ui_utils.wait_for_view(view_to_find = {"resourceId": "android:id/hours"}) tags: ui, android, view, wait, exists """ pass @inherite(parent_ui_utils.is_homescreen) def is_homescreen(): """ description: Check homescreen is displayed usage: ui_utils.is_homescreen() tags: ui, android, homescreen """ pass @inherite(parent_ui_utils.is_display_direction_landscape) def is_display_direction_landscape(): pass @inherite(parent_ui_utils.swipe_to_app_from_recent) def swipe_to_app_from_recent(): """ description: Swipe to the desired app from recent apps menu. usage: ui_utils.swipte_to_app_from_recent(view_to_find= {"text": "YouTube"}) tags: ui, android, scroll,recent apps, swipe """ pass @inherite(parent_ui_utils.search_object_in_direction) def search_object_in_direction(): """ description: Searches a text in a direction (up, down, left or right) usage: ui_utils.search_object_in_direction() tags: ui, android """ pass
nilq/baby-python
python
import hashlib from pyxbincodec import CodecUtils from pyxbincodec import PixBlockDecoder class PixBinDecoder: """docstring for """ def __init__(self): self.MAGIC_NUMBER = "PIXPIPE_PIXBIN" self._verifyChecksum = False self._input = None self._output = None self._binMeta = None self._parsingInfo = { "offsetToReachFirstBlock": -1, "isLittleEndian": -1, } self._decodedBlocks = {} self._isValid = False """ reset I/O and data to query """ def reset(self): self._verifyChecksum = False self._isValid = False self._input = None self._output = None self._binMeta = None self._parsingInfo = { "offsetToReachFirstBlock": -1, "isLittleEndian": -1, } self._decodedBlocks = {} """ Specify an input @param {ArrayBuffer} buff - the input """ def setInput(self, buff ): self.reset() if( type(buff) is not bytes ): print("The input mus be of type 'bytes'.") return; self._input = buff self._isValid = self._parseIndex() def _parseIndex(self): inputData = self._input if( inputData is None ): print("Input cannot be None") return False inputByteLength = len(inputData) magicNumberToExpect = self.MAGIC_NUMBER # control 1: the file must be large enough if( inputByteLength < (len(magicNumberToExpect) + 5) ): print("This buffer does not match a PixBin file.") return False movingByteOffset = 0 magicNumber = CodecUtils.buffToAsciiString(inputData, movingByteOffset, len(magicNumberToExpect) ) # control 2: the magic number if( magicNumber != magicNumberToExpect): print("This file is not of PixBin type. (wrong magic number)") return False movingByteOffset = len(magicNumberToExpect) isLittleEndian = CodecUtils.getUint8(inputData, movingByteOffset ) # control 3: the endianess must be 0 or 1 if(isLittleEndian != 0 and isLittleEndian != 1): print("This file is not of PixBin type. (wrong endianess code)") return False movingByteOffset += 1 pixBinIndexBinaryStringByteLength = CodecUtils.getUint32(inputData, movingByteOffset ) movingByteOffset += 4 pixBinIndexDict = CodecUtils.buffToDict(inputData, movingByteOffset, pixBinIndexBinaryStringByteLength) movingByteOffset += pixBinIndexBinaryStringByteLength self._parsingInfo["offsetToReachFirstBlock"] = movingByteOffset self._parsingInfo["isLittleEndian"] = isLittleEndian self._binMeta = pixBinIndexDict return True; def isValid(self): return self._isValid def getOutput(self): return self._output def getNumberOfBlocks(self): return len(self._binMeta["pixblocksInfo"]) def getBinCreationDate(self): return self._binMeta["date"]; def getBinDescription(self): return self._binMeta["description"] def getBlockDescription( self, n ): if( n<0 or n >= self.getNumberOfBlocks() ): print("The block index is out of range.") return None return self._binMeta["pixblocksInfo"][n]["description"] def getBlockType(self, n ): if( n<0 or n >= self.getNumberOfBlocks() ): print("The block index is out of range.") return None return self._binMeta["pixblocksInfo"][n]["type"] def enableBlockVerification(self, b ): self._verifyChecksum = b; def getBinUserObject(self): return self._binMeta["userObject"]; def fetchBlock(self, n , forceDecoding=False ): nbBlocks = self.getNumberOfBlocks() if( n<0 or n >= nbBlocks ): print("The block index is out of range."); return None; if( n in self._decodedBlocks and (not forceDecoding)): return self._decodedBlocks[ n ]; offset = self._parsingInfo["offsetToReachFirstBlock"]; for i in range(0, n): offset += self._binMeta["pixblocksInfo"][i]["byteLength"]; blockInfo = self._binMeta["pixblocksInfo"][n]; #pixBlockBuff = self._input.slice(offset, offset + blockInfo.byteLength); pixBlockBuff = self._input[ offset : offset + blockInfo["byteLength"] ] if( self._verifyChecksum): md5Comp = hashlib.md5() md5Comp.update(pixBlockBuff) checksum = md5Comp.hexdigest() if( checksum != blockInfo["checksum"] ): print("The block #" + n + " is corrupted."); return None; blockDecoder = PixBlockDecoder(); blockDecoder.setInput( pixBlockBuff ) blockDecoder.run(); decodedBlock = blockDecoder.getOutput(); if( decodedBlock is None ): print("The block #" + str(n) + " could not be decoded."); return None; self._decodedBlocks[ n ] = decodedBlock; return decodedBlock;
nilq/baby-python
python
from xsbs.events import registerServerEventHandler from xsbs.players import player import logging event_handlers = ( ('player_connect', lambda x: logging.info( 'connect: %s (%i)' % (player(x).name(), x)) ), ('player_disconnect', lambda x: logging.info( 'disconnect: %s (%i)' % (player(x).name(), x)) ), ('player_message', lambda x, y: logging.info( 'message: %s: %s' % (player(x).name(), y)) ), ('player_message_team', lambda x, y: logging.info( 'message (team): %s: %s' % (player(x).name(), y)) ) ) for ev_h in event_handlers: registerServerEventHandler(ev_h[0], ev_h[1])
nilq/baby-python
python
import setuptools with open('README.md') as readme_file: long_description = readme_file.read() setuptools.setup( name='aioevproc', version='0.1.0', author='Anton Bryzgalov', author_email='tony.bryzgaloff@gmail.com', description='Minimal async/sync event processing framework on pure Python', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/bryzgaloff/aioevproc', packages=['aioevproc'], classifiers=[ 'Programming Language :: Python :: 3.8', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], python_requires='>=3.8', )
nilq/baby-python
python
from flask import Flask, request import os import json import socket app = Flask(__name__) @app.route('/dostep/<time>&<inputnames>&<inputvalues>&<outputnames>') def step(time, inputnames, inputvalues, outputnames): data = _parse_url(time, inputnames, inputvalues, outputnames) outputs = [data['input1'] * data['time'] for i in range(0, len(data['outputnames']))] return ','.join([str(output) for output in outputs]) def _parse_url(time, inputnames, inputvalues, outputnames): """ Ensure that inputs has the right type """ data = {str(key):float(value) for key, value in zip(inputnames.split(','), inputvalues.split(','))} data['time'] = float(time) data['outputnames'] = outputnames.split(',') return data @app.route('/shutdown') def shutdown(): func = request.environ.get('werkzeug.server.shutdown') if func is None: raise RuntimeError('Not running with the Werkzeug Server') func() return 'Server shutting down...' @app.errorhandler(Exception) def handle_error(e): """ Handle error message back to the FMU """ return 'ERROR: ' + str(e) if __name__ == '__main__': # Open the right port sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) address = 'localhost' sock.bind(('localhost', 0)) # Get a free port at random with '0' port = sock.getsockname()[1] # Retrieve the port and address sock.close() # Close the socket and use the port with Flask # Write a file with port and address path_to_server = os.path.dirname(__file__) with open(os.path.join(path_to_server, "server_config.txt"), "w") as config: config.write('address:' + address + ':port:' + str(port) + ':') # Start the server app.run(port=port, debug=True, use_reloader=False)
nilq/baby-python
python
import pygame import sys import random from ..env_var.env_var import * from pygame.locals import * from ..geometry import vector class Ball (object): def __init__(self): random.seed() self.text = chr(random.randrange(ord('A'), ord('Z'))) pygame.init() self.color = ball_color self.font = pygame.font.SysFont('Arial', text_size) def randomize_step(self, speed): move_vector = vector.vector(randspeed=speed) self.step = move_vector def rebound(self, screen): h, w = screen.get_height(), screen.get_width() if self.pos.x >= w + rebound_range or self.pos.x <= -rebound_range or self.pos.y >= h + rebound_range or self.pos.y <= -rebound_range: self.pos = vector.vector(w // 2, h // 2) def move(self, screen): self.pos += self.step self.rebound (screen) pygame.draw.circle(screen, self.color, self.pos.getpos(), radius) text_box = self.font.render(self.text, True, text_color) tw, th = text_box.get_size() cx, cy = self.pos.getpos() screen.blit(text_box, (cx - tw // 2, cy - th // 2)) pygame.display.update() test = self.hit_the_wall(screen) x, y = self.step.getpos() if test != 'none': if test == 'hit_both': self.step = vector.vector(-y, -x) elif test == 'hit_w': self.step = vector.vector(-x, y) elif test == 'hit_h': self.step = vector.vector(x, -y) def create(self, screen, x=-1, y=-1, step=vector.vector(0, 0)): random.seed() h, w = screen.get_height(), screen.get_width() if x == -1: x = random.randrange(radius + 1, w - radius) if y == -1: y = random.randrange(radius + 1, h - radius) self.pos = vector.point(x, y) self.step = vector.vector(0, 0) self.move(screen) self.step = step def hit_the_wall(self, screen): w, h = screen.get_width(), screen.get_height() x, y = self.pos.getpos() hit_h, hit_w = False, False if x <= radius + 2 or x >= w - radius - 2: hit_w = True if y <= radius + 2 or y >= h - radius - 2: hit_h = True if hit_h and hit_w: return 'hit_both' elif hit_h: return 'hit_h' elif hit_w: return 'hit_w' else: return 'none'
nilq/baby-python
python
import pandas as pd import re import os def _export(data_dir): file = "State Exports by NAICS Commodities.csv" t = pd.read_csv(os.path.join(data_dir, file), skiprows=3, engine="c") t.dropna(how="all", axis=1, inplace=True) # rename in order to aid in joining with import data later t.rename(columns={"Total Exports Value ($US)": "value"}, inplace=True) # convert values to numeric t["value"] = t["value"].replace({",": ""}, regex=True) t["value"] = t["value"].map(float) # pull NAICS code out to new column t["NAICS"] = t["Commodity"].str.split(" ").str[0] t["NAICS"] = t["NAICS"].map(str) # pull NAICS description out t["Commodity Description"] = [ t.loc[i, "Commodity"].split(str(t.loc[i, "NAICS"]) + " ")[1] for i in t.index ] # add units label t["units"] = "us dollars (USD)" t["flow"] = "exports" # typing t["State"] = t["State"].map(str) t["Commodity"] = t["Commodity"].map(str) t["Country"] = t["Country"].map(str) t["Time"] = t["Time"].map(str) t["value"] = t["value"].map(float) t["NAICS"] = t["NAICS"].map(str) t["Commodity Description"] = t["Commodity Description"].map(str) t["units"] = t["units"].map(str) t["flow"] = t["flow"].map(str) return t def _import(data_dir): file = "State Imports by NAICS Commodities.csv" t = pd.read_csv(os.path.join(data_dir, file), skiprows=3, engine="c") t.dropna(how="all", axis=1, inplace=True) # rename in order to aid in joining with export data later t.rename(columns={"Customs Value (Gen) ($US)": "value"}, inplace=True) # convert values to numeric t["value"] = t["value"].replace({",": ""}, regex=True) t["value"] = t["value"].map(float) # pull NAICS code out to new column t["NAICS"] = t["Commodity"].str.split(" ").str[0] t["NAICS"] = t["NAICS"].map(str) # pull NAICS description out t["Commodity Description"] = [ t.loc[i, "Commodity"].split(str(t.loc[i, "NAICS"]) + " ")[1] for i in t.index ] # add units label t["units"] = "us dollars (USD)" t["flow"] = "imports" # typing t["State"] = t["State"].map(str) t["Commodity"] = t["Commodity"].map(str) t["Country"] = t["Country"].map(str) t["Time"] = t["Time"].map(str) t["value"] = t["value"].map(float) t["NAICS"] = t["NAICS"].map(str) t["Commodity Description"] = t["Commodity Description"].map(str) t["units"] = t["units"].map(str) t["flow"] = t["flow"].map(str) return t
nilq/baby-python
python
# -*- coding: utf-8 -*- # vispy: testskip (KNOWNFAIL) # Copyright (c) 2015, Felix Schill. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ Simple demonstration of mouse drawing and editing of a line plot. This demo extends the Line visual from scene adding mouse events that allow modification and creation of line points with the mouse. Vispy takes care of coordinate transforms from screen to ViewBox - the demo works on different zoom levels. """ import numpy as np from vispy import app, scene class EditLineVisual(scene.visuals.Line): """ Mouse editing extension to the Line visual. This class adds mouse picking for line points, mouse_move handling for dragging existing points, and adding new points when clicking into empty space. """ def __init__(self, *args, **kwargs): scene.visuals.Line.__init__(self, *args, **kwargs) # initialize point markers self.markers = scene.visuals.Markers() self.marker_colors = np.ones((len(self.pos), 4), dtype=np.float32) self.markers.set_data(pos=self.pos, symbol="s", edge_color="red", size=6) self.selected_point = None self.selected_index = -1 # snap grid size self.gridsize = 10 def draw(self, transforms): # draw line and markers scene.visuals.Line.draw(self, transforms) self.markers.draw(transforms) def print_mouse_event(self, event, what): """ print mouse events for debugging purposes """ print('%s - pos: %r, button: %s, delta: %r' % (what, event.pos, event.button, event.delta)) def select_point(self, event, radius=5): """ Get line point close to mouse pointer and its index Parameters ---------- event : the mouse event being processed radius : scalar max. distance in pixels between mouse and line point to be accepted return: (numpy.array, int) picked point and index of the point in the pos array """ # position in scene/document coordinates pos_scene = event.pos[:3] # project mouse radius from screen coordinates to document coordinates mouse_radius = \ (event.visual_to_canvas.imap(np.array([radius, radius, radius])) - event.visual_to_canvas.imap(np.array([0, 0, 0])))[0] # print("Mouse radius in document units: ", mouse_radius) # find first point within mouse_radius index = 0 for p in self.pos: if np.linalg.norm(pos_scene - p) < mouse_radius: # print p, index # point found, return point and its index return p, index index += 1 # no point found, return None return None, -1 def update_markers(self, selected_index=-1, highlight_color=(1, 0, 0, 1)): """ update marker colors, and highlight a marker with a given color """ self.marker_colors.fill(1) # default shape (non-highlighted) shape = "o" size = 6 if 0 <= selected_index < len(self.marker_colors): self.marker_colors[selected_index] = highlight_color # if there is a highlighted marker, # change all marker shapes to a square shape = "s" size = 8 self.markers.set_data(pos=self.pos, symbol=shape, edge_color='red', size=size, face_color=self.marker_colors) def on_mouse_press(self, event): self.print_mouse_event(event, 'Mouse press') pos_scene = event.pos[:3] # find closest point to mouse and select it self.selected_point, self.selected_index = self.select_point(event) # if no point was clicked add a new one if self.selected_point is None: print("adding point", len(self.pos)) self._pos = np.append(self.pos, [pos_scene], axis=0) self.set_data(pos=self.pos) self.marker_colors = np.ones((len(self.pos), 4), dtype=np.float32) self.selected_point = self.pos[-1] self.selected_index = len(self.pos) - 1 # update markers and highlights self.update_markers(self.selected_index) def on_mouse_release(self, event): self.print_mouse_event(event, 'Mouse release') self.selected_point = None self.update_markers() def on_mouse_move(self, event): # left mouse button if event.button == 1: # self.print_mouse_event(event, 'Mouse drag') if self.selected_point is not None: pos_scene = event.pos # update selected point to new position given by mouse self.selected_point[0] = round(pos_scene[0] / self.gridsize) \ * self.gridsize self.selected_point[1] = round(pos_scene[1] / self.gridsize) \ * self.gridsize self.set_data(pos=self.pos) self.update_markers(self.selected_index) else: # if no button is pressed, just highlight the marker that would be # selected on click hl_point, hl_index = self.select_point(event) self.update_markers(hl_index, highlight_color=(0.5, 0.5, 1.0, 1.0)) self.update() class Canvas(scene.SceneCanvas): """ A simple test canvas for testing the EditLineVisual """ def __init__(self): scene.SceneCanvas.__init__(self, keys='interactive', size=(800, 800)) # Create some initial points n = 7 self.pos = np.zeros((n, 3), dtype=np.float32) self.pos[:, 0] = np.linspace(-50, 50, n) self.pos[:, 1] = np.random.normal(size=n, scale=10, loc=0) # create new editable line self.line = EditLineVisual(pos=self.pos, color='w', width=3, antialias=True, method='gl') self.view = self.central_widget.add_view() self.view.camera = scene.PanZoomCamera(rect=(-100, -100, 200, 200), aspect=1.0) # the left mouse button pan has to be disabled in the camera, as it # interferes with dragging line points # Proposed change in camera: make mouse buttons configurable self.view.camera._viewbox.events.mouse_move.disconnect( self.view.camera.viewbox_mouse_event) self.view.add(self.line) self.show() self.selected_point = None scene.visuals.GridLines(parent=self.view.scene) if __name__ == '__main__': win = Canvas() app.run()
nilq/baby-python
python
#!/usr/bin/env python f = open('new.txt') lines = f.readlines() for line in lines: print(line.split()[8])
nilq/baby-python
python
import NsgaII import random # Non-dominated Ranking Genetic Algorithm (NRGA) class Ngra(NsgaII.NsgaII): # Initializes genetic algorithm def __init__(self, configuration, numberOfCrossoverPoints=2, mutationSize=2, crossoverProbability=80, mutationProbability=3): NsgaII.NsgaII.__init__(self, configuration, numberOfCrossoverPoints, mutationSize, crossoverProbability, mutationProbability) # get the cumulative sum of a list @staticmethod def __cumulative(lists): cu_list = [] length = len(lists) cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)] return cu_list[1:] # ranked based roulette wheel function def replacement(self, population): populationSize = self._populationSize numberOfCrossoverPoints = self._numberOfCrossoverPoints crossoverProbability = self._crossoverProbability obj = {m: population[m].fitness for m in range(populationSize)} sortedIndices = list(reversed(sorted(obj, key=obj.get))) totalFitness = (populationSize + 1) * populationSize / 2 probSelection = [i / totalFitness for i in range(populationSize)] cumProb = self.__cumulative(probSelection) selectIndices = [random.random() for i in range(populationSize)] parent = 2 * [None] parentIndex = 0 offspring = [] for i in range(populationSize): selected = False for j in range(populationSize - 1): if cumProb[j] < selectIndices[i] and cumProb[j + 1] >= selectIndices[i]: parent[parentIndex % 2] = population[sortedIndices[j + 1]] parentIndex += 1 selected = True break if not selected: parent[parentIndex % 2] = population[sortedIndices[i]] parentIndex += 1 if parentIndex % 2 == 0: child0 = parent[0].crossover(parent[1], numberOfCrossoverPoints, crossoverProbability) child1 = parent[1].crossover(parent[0], numberOfCrossoverPoints, crossoverProbability) # append child chromosome to offspring list offspring.extend((child0, child1)) return offspring def initialize(self, population): super().initialize(population) offspring = self.replacement(population) population.clear() population.extend(offspring) def __str__(self): return "Non-dominated Ranking Genetic Algorithm (NRGA)"
nilq/baby-python
python
import torch from torch import nn from allennlp.modules.span_extractors import SelfAttentiveSpanExtractor class SpanClassifierModule(nn.Module): def _make_span_extractor(self): return SelfAttentiveSpanExtractor(self.proj_dim) def _make_cnn_layer(self, d_inp): """ Make a CNN layer as a projection of local context. CNN maps [batch_size, max_len, d_inp] to [batch_size, max_len, proj_dim] with no change in length. """ k = 1 + 2 * self.cnn_context padding = self.cnn_context return nn.Conv1d( d_inp, self.proj_dim, kernel_size=k, stride=1, padding=padding, dilation=1, groups=1, bias=True, ) def __init__( self, d_inp=1024, proj_dim=512, num_spans=2, cnn_context=0, n_classes=2, dropout=0.1, ): super().__init__() self.cnn_context = cnn_context self.num_spans = num_spans self.proj_dim = proj_dim self.dropout = nn.Dropout(dropout) self.projs = torch.nn.ModuleList() for i in range(num_spans): # create a word-level pooling layer operator proj = self._make_cnn_layer(d_inp) self.projs.append(proj) self.span_extractors = torch.nn.ModuleList() # Lee's self-pooling operator (https://arxiv.org/abs/1812.10860) for i in range(num_spans): span_extractor = self._make_span_extractor() self.span_extractors.append(span_extractor) # Classifier gets concatenated projections of spans. clf_input_dim = self.span_extractors[1].get_output_dim() * num_spans self.classifier = nn.Linear(clf_input_dim, n_classes) def forward(self, feature, span1_idxs, span2_idxs, mask): # Apply projection CNN layer for each span of the input sentence sent_embs_t = self.dropout(feature[-1]).transpose(1, 2) # needed for CNN layer se_projs = [] for i in range(self.num_spans): se_proj = self.projs[i](sent_embs_t).transpose(2, 1).contiguous() se_projs.append(se_proj) span_embs = None _kw = dict(sequence_mask=mask.unsqueeze(2).long()) span_idxs = [span1_idxs.unsqueeze(1), span2_idxs.unsqueeze(1)] for i in range(self.num_spans): # spans are [batch_size, num_targets, span_modules] span_emb = self.span_extractors[i](se_projs[i], span_idxs[i], **_kw) if span_embs is None: span_embs = span_emb else: span_embs = torch.cat([span_embs, span_emb], dim=2) # [batch_size, num_targets, n_classes] logits = self.classifier(span_embs).squeeze(1) return logits
nilq/baby-python
python
# run some simple select tests import psycopg2 as psy import simplejson as json import argparse import setup_db def find_all_studies(cursor,config_obj): STUDYTABLE = config_obj.get('database_tables','studytable') sqlstring = "SELECT id FROM {t};".format(t=STUDYTABLE) cursor.execute(sqlstring) print "returned",cursor.rowcount,"studies" def find_all_trees(cursor,config_obj): TREETABLE = config_obj.get('database_tables','treetable') sqlstring = "SELECT tree_id FROM {t};".format(t=TREETABLE) cursor.execute(sqlstring) print "returned",cursor.rowcount,"trees" def find_all_curators(cursor,config_obj): CURATORTABLE = config_obj.get('database_tables','curatortable') sqlstring = "SELECT * FROM {t};".format(t=CURATORTABLE) cursor.execute(sqlstring) print "returned",cursor.rowcount,"curators" def find_all_taxa(cursor,config_obj): TAXONOMYTABLE = config_obj.get('database_tables','otttable') sqlstring = "SELECT * FROM {t};".format(t=TAXONOMYTABLE) cursor.execute(sqlstring) print "returned",cursor.rowcount,"taxa" def find_properties(cursor,config_obj): PROPERTYTABLE = config_obj.get('database_tables','propertytable') sqlstring = "SELECT * FROM {t} where type='study';".format(t=PROPERTYTABLE) cursor.execute(sqlstring) print "returned",cursor.rowcount,"study properties" sqlstring = "SELECT * FROM {t} where type='tree';".format(t=PROPERTYTABLE) cursor.execute(sqlstring) print "returned",cursor.rowcount,"tree properties" def connect(config_obj): conn = cursor = None # not sure of exception intent try: DBNAME = config_obj.get('connection_info','dbname') USER = config_obj.get('connection_info','dbuser') connectionstring=("dbname={dbname} " "user={dbuser}" .format(dbname=DBNAME,dbuser=USER) ) conn = psy.connect(connectionstring) cursor = conn.cursor() except KeyboardInterrupt: print "Shutdown requested because could not connect to DB" except psy.Error as e: print e # print e.pgerror return (conn,cursor) if __name__ == "__main__": print "testing DB selects" parser = argparse.ArgumentParser(description='simple DB select tests') parser.add_argument('configfile', help='path to the development.ini file' ) args = parser.parse_args() # read config variables config_obj = setup_db.read_config(args.configfile) connection, cursor = setup_db.connect(config_obj) try: find_all_studies(cursor,config_obj) find_all_trees(cursor,config_obj) find_all_curators(cursor,config_obj) find_all_taxa(cursor,config_obj) find_properties(cursor,config_obj) except psy.Error as e: print e.pgerror connection.close()
nilq/baby-python
python
#!/usr/bin/env python3 try: from flask import Flask except ImportError: print ("\n[X] Please install Flask:") print (" $ pip install flask\n") exit() from wordpot import app, pm, parse_options, check_options from wordpot.logger import * import os check_options() if __name__ == '__main__': parse_options() LOGGER.info('Checking command line options') check_options() LOGGER.info('Honeypot started on %s:%s', app.config['HOST'], app.config['PORT']) app.run(debug=app.debug, host=app.config['HOST'], port=int(app.config['PORT']))
nilq/baby-python
python
import pyglet from pyglet.gl import * class Camera: def __init__(self, width: float, height: float, position: list, zoom: float): self.width = float(width) self.height = float(height) self.position = list(position) self.zoom = float(zoom) def left(self): return self.position[0] - self.width / 2 / self.zoom def right(self): return self.position[0] + self.width / 2 / self.zoom def bottom(self): return self.position[1] - self.height / 2 / self.zoom def top(self): return self.position[1] + self.height / 2 / self.zoom def begin(self): glMatrixMode(GL_PROJECTION) glLoadIdentity() glPushMatrix() left = self.left() right = self.right() bottom = self.bottom() top = self.top() glOrtho(left, right, bottom, top, +1, -1) def end(self): glPopMatrix()
nilq/baby-python
python
from nnf import Var from lib204 import Encoding import geopy import geopy.distance from geopy.geocoders import Nominatim import pyproj #factors that might affect the trips virus = Var('virus') # 🦠 documents = Var('documents') # document international = Var('international') # crossing the border toll_money = Var('money for tolls') # toll money afford_plane = Var('can afford plane ticket(s)') # plane ticket is affordable holiday = Var('holiday') # holiday more_than_five = Var('more than five people') # travelling with more than 5 people urgent_trip = Var('trip is urgent') # trip is urgent #for each factor variables, we're storing them in dictionaries because when asking the users for their inputs, #there might be multiple stops along the trip, therefore we would need propositions for each stop along the way. sunny = {} rainy = {} snowstorm = {} roadwork = {} accident = {} toll = {} drive = {} transit = {} plane = {} #stop_info is a (global) list of dictionaries, where each entry contains the starting #and ending location for each stop in user's chosen stops, and the distance between the two. #(in short it contains all the relevant info for the stops the user will take). stop_info = [] def set_up_props(): """Initializes the propositions to be used by the model""" #loop through all stops for i in range(len(stop_info)): #set up propositions for travel location = stop_info[i]["location"] drive[location] = Var('drive from ' + location) transit[location] = Var('take transit from ' + location) plane[location] = Var('take a plane from ' + location) #set up other delay propositions roadwork[location]= Var('roadwork happening on the path from ' + location) accident[location] = Var('accident on the path from ' + location) toll[location] = Var('tolls on the path from ' + location) #set up weather propositions sunny[location]= Var('sunny from ' + location) rainy[location] = Var('rainy from ' + location) snowstorm[location] = Var('snowstorm from ' + location) def read_files(country, filename): """read in a database of cities from a specific country and write it to a list of dictionaries""" file1 = open(filename, "r") country = [] line = "." while(line != ""): line = file1.readline() if(line == ""): break line = line.strip("\ufeff") splitline = line.split(",") city = splitline[0] province = splitline[1] latitude = splitline[2] longitude = splitline[3] timezone = splitline[4].strip("\n") entry = {} entry["city"] = city entry["province/state"] = province entry["latitude"] = latitude entry["longitude"] = longitude entry["timezone"] = timezone country.append(entry) file1.close() return country def calc_distance(coord1, coord2): """calculate the distance between two locations using latitudes and longtitudes""" return geopy.distance.distance(coord1, coord2).km def get_international(start_country, end_country): """checking if the trip is international or not (from Canada to USA and vice versa)""" return start_country != end_country def get_urgency(): """ask if the trip is urgent or not""" choice = input("Is the trip urgent? (Y \ N)") choice = choice.upper() while(choice != "Y" and choice != "N"): choice = input("Please enter a valid option.") choice = choice.upper() if(choice.upper() == "Y"): is_urgent = True else: is_urgent = False return is_urgent def is_test(): """ask if the current run is a test or not""" choice = input("Do you want to run this in test mode where you can add extra constraints? (Y \ N)") choice = choice.upper() while(choice != "Y" and choice != "N"): choice = input("Please enter a valid option.") choice = choice.upper() if(choice.upper() == "Y"): print("Running in test mode...\n") test = True else: print("Running normally...\n") test = False return test def decide_test(): """Get any extra constraints from the user if they are running a test.""" print("What would you like to test? Type 'w' to test weather.\nType 'a' to test affordability.\nType 't' to test travel.") print("Please note that you must enter cities that cross a federal border for 'a'" + " or you will get 0 solutions.") user_input = input() while(user_input.lower() not in ["w", "a", "t"]): user_input = input("Please enter valid input.") return user_input.lower() def calc_time(distance, mode): """calculates the amount of time a trip would take given the mode of transportation. note that speed estimates are used for each mode.""" if(mode == "drive"): speed = 80.0 elif(mode == "transit"): speed = 200.0 elif(mode == "plane"): speed = 850.0 return distance / speed def determine_travel_modes(drive_time, transit_time, plane_time): """based on the time it would take to travel from one spot to another with each mode of transportation, only add reasonable modes of transportation to the travel dictionary.""" travel = {} if(drive_time < 24): travel["drive"] = drive_time if(transit_time < 10): travel["transit"] = transit_time if(plane_time > 2): travel["plane"] = plane_time return travel def raw_location_input(canada_cities, america_cities): """gets input of the starting city/country and ending city/country from the user""" start = "" end = "" inputOK = False # loop until the cities entered are valid and ready to be used for calculation while(not inputOK): print("When entering your cities, you can only travel to and from Canada and the United States.") while (not inputOK): start = input("Please enter your starting city, and country, separated by (just) a comma:") if ("," in start): break while (not inputOK): end = input("Please enter your ending city, and country, separated by a comma:") if ("," in end): break start_city = start.split(",")[0].lower() start_country = start.split(",")[1].lower() end_city = end.split(",")[0].lower() end_country = end.split(",")[1].lower() if(start_city == end_city and start_country == end_country): print("Your starting and ending city can't be the same.") elif((start_city not in canada_cities and start_city not in america_cities) or (end_city not in canada_cities and end_city not in america_cities)): print("You must start and end in a city in Canada or the United States.") elif(start_country not in ["canada", "united states"] or end_country not in ["canada", "united states"]): print("The country you enter must be in Canada or the United States.") else: inputOK = True return {"starting city":start_city, "starting country": start_country, "ending city": end_city, "ending country": end_country} def clarify_duplicates(canada, america, raw_location): """This function asks the user to clarify their chosen city if duplicates exist.""" duplicates_start = [] duplicates_end = [] inputOK = False raw_start_city = raw_location["starting city"] raw_start_country = raw_location["starting country"] raw_end_city = raw_location["ending city"] raw_end_country = raw_location["ending country"] #if their city is in canada, search through all the cities in canada and #add all the duplicates to a list if(raw_start_country == "canada"): for entry in canada: if(entry["city"].lower() == raw_start_city): duplicates_start.append(entry) #do the same but for american cities if their city was in the US else: for entry in america: if(entry["city"].lower() == raw_start_city): duplicates_start.append(entry) #repeat for the destination city if(raw_end_country == "united states"): for entry in america: if(entry["city"].lower() == raw_end_city): duplicates_end.append(entry) else: for entry in canada: if(entry["city"].lower() == raw_end_city): duplicates_end.append(entry) #if there are NO duplicates, the starting city is the first (original) city if(len(duplicates_start) == 1): start_city = duplicates_start[0] #otherwise, allow the user to pick the city they want else: print("Please enter the number beside the starting city you are referring to.") for i in range(len(duplicates_start)): print(i) for value in duplicates_start[i].values(): print(value) print("\n") while(not inputOK): choice = int(input("Enter your choice:")) if(choice > -1 and choice < len(duplicates_start)): inputOK = True start_city = duplicates_start[choice] #reset flag inputOK = False #do the same for the destination city if(len(duplicates_end) == 1): end_city = duplicates_end[0] else: print("Please enter the number beside the destination city you are referring to.") for i in range(len(duplicates_end)): print(i) for value in duplicates_end[i].values(): print(value) print("\n") while(not inputOK): choice = int(input("Enter your choice:")) if(choice > -1 and choice < len(duplicates_end)): inputOK = True end_city = duplicates_end[choice] return start_city, end_city def example_theory(): E = Encoding() set_up_props() #loop through each stop and set appropriate constraints #note: we don't necessarily set it that proposition to true unless we know 100% #it is true because it could still be set false by other constraints. #(just because something is false in one scenario, doesn't mean it's true in the # opposite). for entry in stop_info: location = entry["location"] #if a given mode of transportation is not feasible for that trip, set the #constraint that it can't be true if "drive" not in entry["travel"].keys(): E.add_constraint(~drive[location]) #if it would take more than 3 hours to drive to/from this trip/the trip is international, tolls #will be there else: if(entry["travel"]["drive"] > 3): E.add_constraint(toll[location]) #cannot cross a toll if you have no toll money E.add_constraint(((toll[location] & ~toll_money) & drive[location]).negate()) if "transit" not in entry["travel"].keys(): E.add_constraint(~transit[location]) if "plane" not in entry["travel"].keys(): E.add_constraint(~plane[location]) E.add_constraint(~international | toll[location]) #at least one weather mode has to be true E.add_constraint(sunny[location] | rainy[location] | snowstorm[location]) #only one form of weather can be true at once E.add_constraint(~sunny[location] | (~snowstorm[location] & ~rainy[location])) E.add_constraint(~rainy[location] | (~snowstorm[location] & ~sunny[location])) E.add_constraint(~snowstorm[location] | (~sunny[location] & ~rainy[location])) #good weather and holiday implies tickets will be sold out and you have to drive E.add_constraint((sunny[location] & holiday).negate() | (transit[location] | plane[location]).negate()) #rainy or snowstorm increases the likelihood of accidents E.add_constraint((rainy[location] | snowstorm[location]).negate() | accident[location]) #snowstorm implies that transit and planes will be shut down E.add_constraint(~snowstorm[location] | (transit[location] | plane[location]).negate()) #driving constraints (come into play if they are driving): #bad weather and roadwork implies unfeasible trip E.add_constraint((((rainy[location] | snowstorm[location]) & roadwork[location]) & drive[location]).negate()) #bad weather and holiday implies unfeasible trip E.add_constraint((((rainy[location] | snowstorm[location]) & holiday) & drive[location]).negate()) #roadwork and holiday implies unfeasible trip E.add_constraint(((roadwork[location] & holiday) & drive[location]).negate()) #roadwork and accident implies unfeasible trip E.add_constraint(((roadwork[location] & accident[location]) & drive[location]).negate()) #holiday and accident implies unfeasible trip E.add_constraint(((holiday & accident[location]) & drive[location]).negate()) #you must have at least one form of travel E.add_constraint(plane[location] | transit[location] | drive[location]) #only one form of travel can be true at once E.add_constraint(~drive[location] | (~transit[location] & ~plane[location])) E.add_constraint(~transit[location] | (~drive[location] & ~plane[location])) E.add_constraint(~plane[location] | (~transit[location] & ~drive[location])) #you cannot drive anywhere if you have more than 5 people E.add_constraint(~more_than_five | ~drive[location]) #you cannot take a plane if you don't have money for a ticket E.add_constraint(afford_plane | ~plane[location]) #if you are taking an urgent trip, only the fastest trip (determined earlier) is possible if "drive" in entry["urgent"].keys(): E.add_constraint(~urgent_trip | (~transit[location] & ~plane[location])) elif "transit" in entry["urgent"].keys(): E.add_constraint(~urgent_trip | (~drive[location] & ~plane[location])) elif "plane" in entry["urgent"].keys(): E.add_constraint(~urgent_trip | (~transit[location] & ~drive[location])) #if you have the virus, you ain't flying nowhere E.add_constraint(~plane[location] | (~virus & documents)) #if you don't have documents, you ain't flying nowhere E.add_constraint(documents | ~plane[location]) #only relevant if travel is international #if you have tested positive for the virus/been in contact, you can't cross the border E.add_constraint(~international | (~virus & documents)) #no documents means you can't cross the border E.add_constraint((international & documents) | ~international) return E def test_weather(stop_info): """Tests weather constraints by adding more weather constraints to the list of extra test constraints to be used with this run.""" extra_con = [] set_up_props() for entry in stop_info: location = entry["location"] #ensure that it is not a snowstorm so transit could always happen extra_con.append(~snowstorm[location]) #ensure that a holiday and taking the train means that it is NOT sunny extra_con.append(transit[location] & holiday) #the above two implies it will be rainy, which will imply accidents #should fail the model due to a contradiction extra_con.append(~accident[location]) return extra_con def test_affordability(): """Tests affordability constraints.""" extra_con = [] set_up_props() for entry in stop_info: location = entry["location"] #force international to be true so there will be toll money extra_con.append(international) #force plane to be false extra_con.append(~afford_plane) #forced the driver to have no toll money extra_con.append(~toll_money) #(either transit will always be true or the model will fail). The below will fail the model. extra_con.append(~transit[location]) return extra_con def test_travel(): """Tests travel constraints.""" extra_con = [] set_up_props() for entry in stop_info: location = entry["location"] #force more than five people to take the trip (negates driving) extra_con.append(more_than_five) #force one of them to have COVID (cannot take a plane/travel internationally) #if the user enters an international trip there should be 0 solutions. #in other words, their only option in this scenario is to take transit domestically. #negating transit gives us 0 solutions then, of course. extra_con.append(virus) extra_con.append(~transit[location]) return extra_con def solve(border, is_urgent, test, extra_con=[]): """Sets up and uses the SAT solver.""" #set up the solver T = example_theory() #account for international status/urgency if(border): T.add_constraint(international) print("This trip is international...") else: T.add_constraint(~international) print("This trip is not international...") #add more constraints if the trip is urgent if(is_urgent): T.add_constraint(urgent_trip) else: T.add_constraint(~urgent_trip) if test: #add any extra constraints if extra_con != []: for constraint in extra_con: T.add_constraint(constraint) print("\nSatisfiable: %s" % T.is_satisfiable()) print("# Solutions: %d" % T.count_solutions()) print(" Solution: %s" % T.solve()) def main(): """Runs the program.""" #ask the user if a test is being run test = is_test() #if it is a test, get any extra constraints from the user if test: type_of_test = decide_test() #will store extra constraints if a test is being run extra_con = [] #read in the databases (each database contains the city name and its #longitude/latitude coordinate). canada = read_files("canada", "Canada Cities.csv") america = read_files("america", "US Cities.csv") # create a list for canadian and american cities canada_cities = [] america_cities = [] for entry in canada: canada_cities.append(entry["city"].lower()) for entry in america: america_cities.append(entry["city"].lower()) #get the raw location from the user and clarify any duplicates to get the #starting and ending city (the countries will of course remain the same) raw_location = raw_location_input(canada_cities,america_cities) start_city, end_city = clarify_duplicates(canada, america, raw_location) start_country = raw_location["starting country"] end_country = raw_location["ending country"] is_urgent = get_urgency() #calculate the total distance between the starting and ending city start_coord = (start_city["latitude"], start_city["longitude"]) end_coord = (end_city["latitude"], end_city["longitude"]) total_dist = calc_distance(start_coord, end_coord) print(str(start_coord) + " " + str(end_coord)) #tell the user the total number of km print("A trip from " + start_city["city"] + ", " + start_city["province/state"] + " to " + end_city["city"] + ", " + end_city["province/state"] + " is " + str(total_dist)+ " km long.") #calculate 1/tenth of the distance from the start to the end #the user will be given 10 choices of evenly spaced cities to stop at along the way #they can stop at 0, 1, or multiple; their choice next_dist = total_dist/10 geodesic = pyproj.Geod(ellps='WGS84') #calculates the initial bearing (fwd_azimuth) and the final bearing fwd_azimuth,back_azimuth,distance = geodesic.inv(start_city["longitude"], start_city["latitude"], end_city["longitude"], end_city["latitude"]) final_bearing = back_azimuth - 180 #Define the starting and ending points. temp_start = geopy.Point(start_city["latitude"], start_city["longitude"]) end = geopy.Point(end_city["latitude"], end_city["longitude"]) start = temp_start #Define a general distance object, initialized with a distance of the stop distance (in km). d = geopy.distance.distance(kilometers=next_dist) #lists that will hold all the stops and the stops that the user chooses, respectively all_stops = [] chosen_stops = [] #define the geolocator geolocator = Nominatim(user_agent="Bing") #loop 10 times (for 10 stops) for i in range(10): # Use the destination method with our starting point and initial bearing # in order to go from our starting point to the next city in the line of stops. #finds the next point from the starting point given the bearing #if we are closer to the start, use our initial bearing; otherwise, use the final bearing if(i < 5): final = d.destination(point=temp_start, bearing=fwd_azimuth) else: final = d.destination(point=temp_start, bearing=final_bearing) #finds the location location = geolocator.reverse(str(final)) print(str(i) + ": " + str(location)) #add it to the list of all stops all_stops.append({"location":str(location),"coord":final}) #reset the next starting point temp_start = final #add the starting location to the chosen stops chosen_stops.append({"location": start_city["city"], "coord": start}) user_input = -2 #initizalize #get the user input for the stops they would like and store it in chosen_stops print("Please enter which stops you would like to take along the way." + "If you are done entering stops, please enter '-1'. If you don't want to take any stops," + " enter -1 right away.") while(user_input != -1): user_input = int(input("Enter your next stop: ")) if (user_input < -1 or user_input > 9): print("Wrong input! Please try again!") else: if (user_input != -1): chosen_stops.append(all_stops[user_input]) #add the ending location to the chosen stops #chosen_stops is now a list of all stops including the start and end chosen_stops.append({"location": end_city["city"], "coord": end}) for i in range(len(chosen_stops) - 1): #calculate the distance between each stop distance = calc_distance(chosen_stops[i]["coord"], chosen_stops[i + 1]["coord"]) print("The distance between " + str(chosen_stops[i]["location"]) + " and " + str(chosen_stops[i + 1]["location"]) + " is " + str(distance) + " km. ") dict_string = str(chosen_stops[i]["location"]) + " to " + str(chosen_stops[i+1]["location"]) #set up the dictionary and append it to the list entry = {"location": dict_string, "distance" : distance} stop_info.append(entry) #loop through every stop for i in range(len(stop_info)): #now that we know the distance, we can calculate the time needed to travel #between each stop with each mode of transportation distance = stop_info[i]["distance"] drive_time = calc_time(distance, "drive") transit_time = calc_time(distance, "transit") plane_time = calc_time(distance, "plane") travel = determine_travel_modes(drive_time, transit_time, plane_time) for mode in travel: print(mode + " from " + stop_info[i]["location"] + ":" + str(travel[mode]) + " hours.") all_modes = [] urgent = {} #determine the FASTEST mode of travel if travel != {}: if "drive" in travel.keys(): all_modes.append(travel["drive"]) if "transit" in travel.keys(): all_modes.append(travel["transit"]) if "plane" in travel.keys(): all_modes.append(travel["plane"]) fastest = min(all_modes) for mode in travel: if travel[mode] <= fastest: urgent[mode] = travel[mode] #add a new key, the dictionary of available travel modes, to the list stop_info[i]["travel"] = travel #do the same with the urgent travel mode stop_info[i]["urgent"] = urgent #reset the travel modes travel = {} urgent = {} #determine if the travel is international or not and set the appropriate constraint border = get_international(start_country, end_country) #add constraints for the appropriate test, if it is a test if test: if type_of_test == "w": extra_con = test_weather(stop_info) elif type_of_test == "a": extra_con = test_affordability() elif type_of_test == "t": extra_con = test_travel() #solve! solve(border, is_urgent, test, extra_con) main() #if __name__ == "__main__":
nilq/baby-python
python
""" .. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de> """ import numpy as np import pytest from .. import PolarGrid, SphericalGrid from ..boundaries.local import NeumannBC @pytest.mark.parametrize("grid_class", [PolarGrid, SphericalGrid]) def test_spherical_base_bcs(grid_class): """ test setting boundary conditions on spherical grids """ grid = grid_class(2, 3) domain1 = grid.get_boundary_conditions(["derivative", {"type": "value"}]) domain2 = grid.get_boundary_conditions({"type": "value"}) assert domain1 == domain2 # test boundary conditions for simulations with holes grid = grid_class((1, 2), 3) grid.get_boundary_conditions(["derivative", {"type": "value"}]) domain1 = grid.get_boundary_conditions({"type": "value"}) domain2 = grid.get_boundary_conditions(["value", "value"]) assert domain1 == domain2 def test_polar_grid(): """ test simple polar grid """ grid = PolarGrid(4, 8) assert grid.dim == 2 assert grid.numba_type == "f8[:]" assert grid.shape == (8,) assert not grid.has_hole assert grid.discretization[0] == pytest.approx(0.5) assert not grid.uniform_cell_volumes np.testing.assert_array_equal(grid.discretization, np.array([0.5])) assert grid.volume == pytest.approx(np.pi * 4 ** 2) assert grid.volume == pytest.approx(grid.integrate(1)) np.testing.assert_allclose(grid.axes_coords[0], np.linspace(0.25, 3.75, 8)) a = grid.get_operator("laplace", "natural")(np.random.random(8)) assert a.shape == (8,) assert np.all(np.isfinite(a)) # random points c = np.random.randint(8, size=(6, 1)) p = grid.cell_to_point(c) np.testing.assert_array_equal(c, grid.point_to_cell(p)) assert grid.contains_point(grid.get_random_point()) assert grid.contains_point(grid.get_random_point(3.99)) assert "laplace" in grid.operators def test_polar_annulus(): """ test simple polar grid with a hole """ grid = PolarGrid((2, 4), 8) assert grid.dim == 2 assert grid.numba_type == "f8[:]" assert grid.shape == (8,) assert grid.has_hole assert grid.discretization[0] == pytest.approx(0.25) assert not grid.uniform_cell_volumes np.testing.assert_array_equal(grid.discretization, np.array([0.25])) assert grid.volume == pytest.approx(np.pi * (4 ** 2 - 2 ** 2)) assert grid.volume == pytest.approx(grid.integrate(1)) assert grid.radius == (2, 4) np.testing.assert_allclose(grid.axes_coords[0], np.linspace(2.125, 3.875, 8)) a = grid.get_operator("laplace", "natural")(np.random.random(8)) assert a.shape == (8,) assert np.all(np.isfinite(a)) # random points c = np.random.randint(8, size=(6, 1)) p = grid.cell_to_point(c) np.testing.assert_array_equal(c, grid.point_to_cell(p)) assert grid.contains_point(grid.get_random_point()) assert grid.contains_point(grid.get_random_point(1.99)) # test boundary points np.testing.assert_equal(grid._boundary_coordinates(0, False), np.array([2])) np.testing.assert_equal(grid._boundary_coordinates(0, True), np.array([4])) def test_polar_to_cartesian(): """ test conversion of polar grid to Cartesian """ from ...fields import ScalarField from .. import CartesianGrid expr_pol = "1 / (1 + r**2)" expr_cart = expr_pol.replace("r**2", "(x**2 + y**2)") grid_pol = PolarGrid(7, 16) pf_pol = ScalarField.from_expression(grid_pol, expression=expr_pol) grid_cart = CartesianGrid([[-4, 4], [-3.9, 4.1]], [16, 16]) pf_cart1 = pf_pol.interpolate_to_grid(grid_cart) pf_cart2 = ScalarField.from_expression(grid_cart, expression=expr_cart) np.testing.assert_allclose(pf_cart1.data, pf_cart2.data, atol=0.1) def test_spherical_grid(): """ test simple spherical grid """ grid = SphericalGrid(4, 8) assert grid.dim == 3 assert grid.numba_type == "f8[:]" assert grid.shape == (8,) assert not grid.has_hole assert grid.discretization[0] == pytest.approx(0.5) assert not grid.uniform_cell_volumes np.testing.assert_array_equal(grid.discretization, np.array([0.5])) assert grid.volume == pytest.approx(4 / 3 * np.pi * 4 ** 3) assert grid.volume == pytest.approx(grid.integrate(1)) np.testing.assert_allclose(grid.axes_coords[0], np.linspace(0.25, 3.75, 8)) a = grid.get_operator("laplace", "natural")(np.random.random(8)) assert a.shape == (8,) assert np.all(np.isfinite(a)) # random points c = np.random.randint(8, size=(6, 1)) p = grid.cell_to_point(c) np.testing.assert_array_equal(c, grid.point_to_cell(p)) assert grid.contains_point(grid.get_random_point()) assert grid.contains_point(grid.get_random_point(3.99)) assert "laplace" in grid.operators def test_spherical_annulus(): """ test simple spherical grid with a hole """ grid = SphericalGrid((2, 4), 8) assert grid.dim == 3 assert grid.numba_type == "f8[:]" assert grid.shape == (8,) assert grid.has_hole assert grid.discretization[0] == pytest.approx(0.25) assert not grid.uniform_cell_volumes np.testing.assert_array_equal(grid.discretization, np.array([0.25])) assert grid.volume == pytest.approx(4 / 3 * np.pi * (4 ** 3 - 2 ** 3)) assert grid.volume == pytest.approx(grid.integrate(1)) assert grid.radius == (2, 4) np.testing.assert_allclose(grid.axes_coords[0], np.linspace(2.125, 3.875, 8)) a = grid.get_operator("laplace", "natural")(np.random.random(8)) assert a.shape == (8,) assert np.all(np.isfinite(a)) # random points c = np.random.randint(8, size=(6, 1)) p = grid.cell_to_point(c) assert all(grid.contains_point(r) for r in p) np.testing.assert_array_equal(c, grid.point_to_cell(p)) assert grid.contains_point(grid.get_random_point()) assert grid.contains_point(grid.get_random_point(1.99)) # test boundary points np.testing.assert_equal(grid._boundary_coordinates(0, False), np.array([2])) np.testing.assert_equal(grid._boundary_coordinates(0, True), np.array([4])) def test_spherical_to_cartesian(): """ test conversion of spherical grid to cartesian """ from ...fields import ScalarField from .. import CartesianGrid expr_sph = "1 / (1 + r**2)" expr_cart = expr_sph.replace("r**2", "(x**2 + y**2 + z**2)") grid_sph = SphericalGrid(7, 16) pf_sph = ScalarField.from_expression(grid_sph, expression=expr_sph) grid_cart = CartesianGrid([[-4, 4], [-3.9, 4.1], [-4.1, 3.9]], [16] * 3) pf_cart1 = pf_sph.interpolate_to_grid(grid_cart) pf_cart2 = ScalarField.from_expression(grid_cart, expression=expr_cart) np.testing.assert_allclose(pf_cart1.data, pf_cart2.data, atol=0.1) @pytest.mark.parametrize("grid_class", [PolarGrid, SphericalGrid]) def test_setting_boundary_conditions(grid_class): """ test setting some boundary conditions """ grid = grid_class([0, 1], 3) b_inner = NeumannBC(grid, 0, upper=False) assert grid.get_boundary_conditions("natural")[0].low == b_inner assert grid.get_boundary_conditions({"value": 2})[0].low == b_inner bcs = grid.get_boundary_conditions(["value", "value"]) assert bcs[0].low != b_inner grid = grid_class([1, 2], 3) bcs = grid.get_boundary_conditions(["value", "value"]) assert bcs[0].low != b_inner
nilq/baby-python
python
# Copyright (c) 2008-2012 by Enthought, Inc. # All rights reserved. import sys from setuptools import setup setup_data = {} execfile('setup_data.py', setup_data) INFO = setup_data['INFO'] if 'develop' in sys.argv: INFO['install_requires'] = [] # The actual setup call. setup( name = 'ets', version = INFO['version'], author = 'Enthought, Inc.', download_url = ('http://www.enthought.com/repo/ets/ets-%s.tar.gz' % INFO['version']), author_email = 'info@enthought.com', classifiers = [c.strip() for c in """\ Development Status :: 4 - Beta Intended Audience :: Developers Intended Audience :: Science/Research License :: OSI Approved :: BSD License Operating System :: MacOS Operating System :: Microsoft :: Windows Operating System :: OS Independent Operating System :: POSIX Operating System :: Unix Programming Language :: Python Topic :: Scientific/Engineering Topic :: Software Development Topic :: Software Development :: Libraries """.splitlines() if len(c.strip()) > 0], description = 'Enthought Tool Suite meta-project', long_description = open('README.rst').read(), install_requires = INFO['install_requires'], license = 'BSD', maintainer = 'ETS Developers', maintainer_email = 'enthought-dev@enthought.com', py_modules = ["ets", "ets_docs"], entry_points = dict(console_scripts=[ "ets = ets:main", "ets-docs = ets_docs:main", ]), platforms = ["Windows", "Linux", "Mac OS-X", "Unix", "Solaris"], url = 'http://code.enthought.com/projects/tool-suite.php', )
nilq/baby-python
python
def dobro(n): d = n * 2 return d def metade(n): d = n / 2 return d def aumento(n): d = n + n * 10 / 100 return d def reduzir(n): d = n - (n * 13 / 100) return d
nilq/baby-python
python
# -*- coding: utf-8 -*- import unittest import numpy as np import turret import turret.layers as L from util import execute_inference class BasicMathTest(unittest.TestCase): def test_sum_ternary(self): N, C, H, W = 3, 5, 7, 11 input0 = np.random.rand(N, C, H, W).astype(np.float32) input1 = np.random.rand(N, C, H, W).astype(np.float32) input2 = np.random.rand(N, C, H, W).astype(np.float32) def build_network(network): h0 = network.add_input("input0", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h1 = network.add_input("input1", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h2 = network.add_input("input2", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h = L.sum(h0, h1, h2) network.mark_output("output", h) actual = execute_inference( {"input0": input0, "input1": input1, "input2": input2}, build_network) expect = input0 + input1 + input2 self.assertEqual(expect.shape, actual.shape) self.assertTrue(np.allclose(expect, actual)) def test_prod_ternary(self): N, C, H, W = 3, 5, 7, 11 input0 = np.random.rand(N, C, H, W).astype(np.float32) input1 = np.random.rand(N, C, H, W).astype(np.float32) input2 = np.random.rand(N, C, H, W).astype(np.float32) def build_network(network): h0 = network.add_input("input0", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h1 = network.add_input("input1", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h2 = network.add_input("input2", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h = L.prod(h0, h1, h2) network.mark_output("output", h) actual = execute_inference( {"input0": input0, "input1": input1, "input2": input2}, build_network) expect = input0 * input1 * input2 self.assertEqual(expect.shape, actual.shape) self.assertTrue(np.allclose(expect, actual)) def test_max_ternary(self): N, C, H, W = 3, 5, 7, 11 input0 = np.random.rand(N, C, H, W).astype(np.float32) input1 = np.random.rand(N, C, H, W).astype(np.float32) input2 = np.random.rand(N, C, H, W).astype(np.float32) def build_network(network): h0 = network.add_input("input0", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h1 = network.add_input("input1", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h2 = network.add_input("input2", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h = L.max(h0, h1, h2) network.mark_output("output", h) actual = execute_inference( {"input0": input0, "input1": input1, "input2": input2}, build_network) expect = np.maximum(np.maximum(input0, input1), input2) self.assertEqual(expect.shape, actual.shape) self.assertTrue(np.allclose(expect, actual)) def test_min_ternary(self): N, C, H, W = 3, 5, 7, 11 input0 = np.random.rand(N, C, H, W).astype(np.float32) input1 = np.random.rand(N, C, H, W).astype(np.float32) input2 = np.random.rand(N, C, H, W).astype(np.float32) def build_network(network): h0 = network.add_input("input0", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h1 = network.add_input("input1", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h2 = network.add_input("input2", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h = L.min(h0, h1, h2) network.mark_output("output", h) actual = execute_inference( {"input0": input0, "input1": input1, "input2": input2}, build_network) expect = np.minimum(np.minimum(input0, input1), input2) self.assertEqual(expect.shape, actual.shape) self.assertTrue(np.allclose(expect, actual)) def test_sub(self): N, C, H, W = 3, 5, 7, 11 input0 = np.random.rand(N, C, H, W).astype(np.float32) input1 = np.random.rand(N, C, H, W).astype(np.float32) input2 = np.random.rand(N, C, H, W).astype(np.float32) def build_network(network): h0 = network.add_input("input0", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h1 = network.add_input("input1", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h = L.sub(h0, h1) network.mark_output("output", h) actual = execute_inference( {"input0": input0, "input1": input1}, build_network) expect = input0 - input1 self.assertEqual(expect.shape, actual.shape) self.assertTrue(np.allclose(expect, actual)) def test_div(self): N, C, H, W = 3, 5, 7, 11 input0 = np.random.rand(N, C, H, W).astype(np.float32) input1 = np.random.rand(N, C, H, W).astype(np.float32) + 0.5 def build_network(network): h0 = network.add_input("input0", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h1 = network.add_input("input1", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h = L.div(h0, h1) network.mark_output("output", h) actual = execute_inference( {"input0": input0, "input1": input1}, build_network) expect = input0 / input1 self.assertEqual(expect.shape, actual.shape) self.assertTrue(np.allclose(expect, actual)) def test_pow(self): N, C, H, W = 3, 5, 7, 11 input0 = np.random.rand(N, C, H, W).astype(np.float32) input1 = np.random.rand(N, C, H, W).astype(np.float32) def build_network(network): h0 = network.add_input("input0", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h1 = network.add_input("input1", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h = L.pow(h0, h1) network.mark_output("output", h) actual = execute_inference( {"input0": input0, "input1": input1}, build_network) expect = np.power(input0, input1) self.assertEqual(expect.shape, actual.shape) self.assertTrue(np.allclose(expect, actual)) def test_exp(self): N, C, H, W = 3, 5, 7, 11 input0 = np.random.rand(N, C, H, W).astype(np.float32) def build_network(network): h = network.add_input("input0", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h = L.exp(h) network.mark_output("output", h) actual = execute_inference( {"input0": input0}, build_network) expect = np.exp(input0) self.assertEqual(expect.shape, actual.shape) self.assertTrue(np.allclose(expect, actual)) def test_log(self): N, C, H, W = 3, 5, 7, 11 input0 = np.random.rand(N, C, H, W).astype(np.float32) + 0.5 def build_network(network): h = network.add_input("input0", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h = L.log(h) network.mark_output("output", h) actual = execute_inference( {"input0": input0}, build_network) expect = np.log(input0) self.assertEqual(expect.shape, actual.shape) self.assertTrue(np.allclose(expect, actual, atol=1e-7)) def test_sqrt(self): N, C, H, W = 3, 5, 7, 11 input0 = np.random.rand(N, C, H, W).astype(np.float32) def build_network(network): h = network.add_input("input0", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h = L.sqrt(h) network.mark_output("output", h) actual = execute_inference( {"input0": input0}, build_network) expect = np.sqrt(input0) self.assertEqual(expect.shape, actual.shape) self.assertTrue(np.allclose(expect, actual)) def test_recip(self): N, C, H, W = 3, 5, 7, 11 input0 = np.random.rand(N, C, H, W).astype(np.float32) + 0.5 def build_network(network): h = network.add_input("input0", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h = L.recip(h) network.mark_output("output", h) actual = execute_inference( {"input0": input0}, build_network) expect = 1.0 / input0 self.assertEqual(expect.shape, actual.shape) self.assertTrue(np.allclose(expect, actual)) def test_abs(self): N, C, H, W = 3, 5, 7, 11 input0 = np.random.rand(N, C, H, W).astype(np.float32) def build_network(network): h = network.add_input("input0", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h = L.abs(h) network.mark_output("output", h) actual = execute_inference( {"input0": input0}, build_network) expect = np.abs(input0) self.assertEqual(expect.shape, actual.shape) self.assertTrue(np.allclose(expect, actual)) def test_neg(self): N, C, H, W = 3, 5, 7, 11 input0 = np.random.rand(N, C, H, W).astype(np.float32) def build_network(network): h = network.add_input("input0", turret.DataType.FLOAT, turret.Dimensions.CHW(C, H, W)) h = L.neg(h) network.mark_output("output", h) actual = execute_inference( {"input0": input0}, build_network) expect = -input0 self.assertEqual(expect.shape, actual.shape) self.assertTrue(np.allclose(expect, actual))
nilq/baby-python
python
from fastatomography.util import * from scipy.io import loadmat, savemat # %% path = '/home/philipp/projects2/tomo/2019-03-18_Pd_loop/' # path = '/home/philipp/projects2/tomo/2018-07-03-Pdcoating_few_proj/sample synthesis date 20180615-Pd coating/' # path = '/home/philipp/projects2/tomo/2019-04-17-Pd_helix/philipp/' fn = 'reco_blur.npy' fn = 'thresh_res.mat' # path = '/home/philipp/projects2/tomo/2019-04-17-Pd_helix/philipp/' # fn = 'RecFISTA_reg5.npy' # rec = np.load(path + fn) #%% rec = loadmat(path + fn)['r'] # rec = np.transpose(rec, (1,0,2)) # mask = np.load(path + 'mask.npy') # # # %% # blur1 = blur.copy() # # blur1[:,:60,:] = 0 # # blur1[:,380:,:] = 0 # # # plot(blur1[:, :, 100]) # # plot(blur1[:, :, 200]) # # plot(blur1[:, :, 300]) # # plot(blur1[:, :, 400]) # # for i in range(20): # plot(blur1[i * 20, :, :]) # # plot(blur1[:, 200, :]) # # # # %% # # plot(blur1[:, 200, :]) # from skimage import io # # im = io.imread('/home/philipp/projects2/tomo/2019-03-18_Pd_loop/rec0.tiff') # print(im.shape) # # im = np.transpose(im, (2, 1, 0)) # io.imsave('/home/philipp/projects2/tomo/2019-03-18_Pd_loop/rec0T.tiff', im) # %% # # from skimage import io # # im = io.imread('/home/philipp/projects2/tomo/2019-03-18_Pd_loop/reco_blurbin.tiff') # print(im.shape) # # %% # im = np.transpose(im, (1, 2, 0)) # print(im.shape) # %% # io.imsave('/home/philipp/projects2/tomo/2019-03-18_Pd_loop/reco_blurbinT.tiff', im) rec = np.transpose(rec,(1,0,2)) # %% # mask = (im < 1.1e-16).astype(np.float) # mask = np.transpose(mask, [2, 1, 0]) # # %% # # ms = np.sum(mask, (1, 2)) # # drawn = ms > 38000 # # # drawn2 = np.logical_and(np.arange(len(ms))>100,ms > 20000) # # # drawn3 = np.logical_or(drawn,drawn2) # # f, a = plt.subplots() # a.plot(np.arange((len(ms))), ms) # # a.plot(np.arange((len(ms))),drawn3.astype(np.float)*4e4) # a.plot(np.arange((len(ms))), drawn.astype(np.float) * 3.8e4) # # a.plot(np.arange((len(ms))),drawn2.astype(np.float)*3e4) # plt.show() # # # %% # from tqdm import trange # # mask2 = mask.copy() # for i in trange(len(ms)): # if not drawn[i]: # for j in range(i): # if drawn[i - j]: # mask2[i] = mask[i - j] # break # %% # for i in trange(100): # plot(mask2[i]) # %% # mask2 = np.transpose(mask2, [2, 1, 0]) # %% # io.imsave('/home/philipp/projects2/tomo/2019-03-18_Pd_loop/rec0TmaskT2.tiff', mask2) # %% # np.save('/home/philipp/projects2/tomo/2019-03-18_Pd_loop/rec0TmaskT2.npy', mask2) # %% from collections import deque import matplotlib.pyplot as plt import numpy as np class InteractiveDataPrep(object): def __init__(self, data, mask, r=50, action_sequence=None): if action_sequence is None: action_sequence = [ ( 'Now move with the arrow keys and select the position of the same feature again. ENTER', 'enter', 'pos', np.ones(3)), ('Closing', 'close', 'pos', np.ones(3)) ] fig, (ax, ax1) = plt.subplots(1, 2, figsize=(10, 10)) self.current_action = None self.fig = fig self.data = data self.current_mask = mask self.actions = deque(action_sequence) fig.canvas.mpl_connect('motion_notify_event', self.mouse_move) fig.canvas.mpl_connect('scroll_event', self.scroll) fig.canvas.mpl_connect('key_press_event', self.key_press_event) fig.canvas.mpl_connect('button_press_event', self.button_press_event) fig.canvas.mpl_connect('button_release_event', self.button_release_event) self.pos = [0, 0] self.ax = ax self.r = r self.holding_button1 = False self.holding_button3 = False self.circle1 = plt.Circle((0, 0), self.r, color='r', fill=None) ax.add_artist(self.circle1) # text location in axes coords self.txt = ax.text(0.9, 2, '', transform=ax.transAxes) self.data_index = 0 self.imax = ax.imshow(data[self.data_index], cmap=plt.cm.get_cmap('viridis')) self.imax1 = ax1.imshow(self.current_mask[self.data_index], interpolation='nearest', cmap=plt.cm.get_cmap('hot')) self.next_action() plt.grid(False) plt.show() def next_action(self): self.current_action = self.actions.popleft() print(self.current_action[0]) self.ax.set_title(self.current_action[0]) self.fig.canvas.draw() if self.current_action[1] == 'close': self.fig = None plt.clf() plt.cla() plt.close() def button_release_event(self, event): x, y = int(event.xdata), int(event.ydata) self.pos = [y, x] # print self.pos print event.button if self.holding_button1 and event.button == 1: self.holding_button1 = False elif self.holding_button3 and event.button == 3: self.holding_button3 = False def refresh_display(self): self.imax.set_data(self.data[self.data_index]) self.imax.set_clim(vmin=self.data[self.data_index].min(), vmax=self.data[self.data_index].max()) self.imax1.set_data(self.current_mask[self.data_index]) self.imax1.set_clim(vmin=self.current_mask[self.data_index].min(), vmax=self.current_mask[self.data_index].max()) plt.draw() def button_press_event(self, event): x, y = int(event.xdata), int(event.ydata) self.pos = [y, x] if event.button == 1: self.current_mask[self.data_index][ sector_mask(self.current_mask[self.data_index].shape, self.pos, self.r, (0, 360))] = 1 self.holding_button1 = True elif event.button == 3: self.current_mask[self.data_index][ sector_mask(self.current_mask[self.data_index].shape, self.pos, self.r, (0, 360))] = 0 self.holding_button3 = True # plot(sector_mask(self.current_mask[self.data_index].shape, self.pos, self.r, (0, 360)).astype(np.float)) self.refresh_display() def mouse_move(self, event): if not event.inaxes: return x, y = event.xdata, event.ydata self.pos = [y, x] # update the line positions self.circle1.center = (x, y) self.txt.set_text('x=%1.2f, y=%1.2f index=%d' % (self.pos[0], self.pos[1], self.data_index)) plt.draw() if self.holding_button1: self.current_mask[self.data_index][ sector_mask(self.current_mask[self.data_index].shape, self.pos, self.r, (0, 360))] = 1 self.refresh_display() elif self.holding_button3: self.current_mask[self.data_index][ sector_mask(self.current_mask[self.data_index].shape, self.pos, self.r, (0, 360))] = 0 self.refresh_display() def scroll(self, event): if not event.inaxes: return if event.button == 'up': self.r += 1 else: self.r -= 1 x, y = event.xdata, event.ydata # update the line positions self.circle1.radius = self.r plt.draw() def key_press_event(self, event): # print(event.key) if event.key == 'enter' and self.current_action[1] == 'enter': self.current_action[3][:] = [self.data_index, self.pos[0], self.pos[1]] self.next_action() elif event.key == 'control' and self.current_action[1] == 'control': self.current_action[3][:] = [self.r] self.next_action() elif event.key == 'control' and self.current_action[1] == 'center_radius_control': self.current_action[4][:] = [self.r] self.current_action[3][:] = [self.pos[0], self.pos[1]] self.next_action() elif event.key == 'left': self.data_index -= 1 if self.holding_button1: self.current_mask[self.data_index][ sector_mask(self.current_mask[self.data_index].shape, self.pos, self.r, (0, 360))] = 1 elif self.holding_button3: self.current_mask[self.data_index][ sector_mask(self.current_mask[self.data_index].shape, self.pos, self.r, (0, 360))] = 0 self.txt.set_text('x=%1.2f, y=%1.2f index=%d' % (self.pos[0], self.pos[1], self.data_index)) self.refresh_display() elif event.key == 'right': self.data_index += 1 if self.holding_button1: self.current_mask[self.data_index][ sector_mask(self.current_mask[self.data_index].shape, self.pos, self.r, (0, 360))] = 1 elif self.holding_button3: self.current_mask[self.data_index][ sector_mask(self.current_mask[self.data_index].shape, self.pos, self.r, (0, 360))] = 0 self.txt.set_text('x=%1.2f, y=%1.2f index=%d' % (self.pos[0], self.pos[1], self.data_index)) self.refresh_display() # %%loop_genfire_blur mask = np.zeros_like(rec) # mask = loadmat('/home/philipp/projects2/tomo/2019-03-18_Pd_loop/mask_0p7.mat')['m'] # mask = np.transpose(mask,(1,0,2)) d = InteractiveDataPrep(rec, mask, r=50) mask = np.transpose(mask,(1,0,2)) savemat(path+'thresh_mask.mat',{'d':mask}) # mask = np.transpose(mask,(2,1,0)) # np.save(path+'bin2_threshold_mask.npy',mask) #%% # io.imsave(path+'mask.tiff', mask)
nilq/baby-python
python
# Copyright 2021 University of Manchester # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from array import * import fileinput import sys, getopt import csv def main(argv): NumberOfRows = 16; NumberOfCols = 19; FrameBitsPerRow = 32; MaxFramesPerCol = 20; desync_flag = 20; FrameSelectWidth = 5; RowSelectWidth = 5; #print("hello") try: opts, args = getopt.getopt(argv,"hr:c:b:f:d:",["NumberOfRows=","NumberOfCols=","FrameBitsPerRow=","MaxFramesPerCol=","desync_flag="]) except getopt.GetoptError: print ('top_wrapper_generator.py -r <NumberOfRows> -c <NumberOfCols> -b <FrameBitsPerRow> -f <MaxFramesPerCol> -d <desync_flag>') sys.exit(2) for opt, arg in opts: if opt == '-h': print ('top_wrapper_generator.py -r <NumberOfRows> -c <NumberOfCols> -b <FrameBitsPerRow> -f <MaxFramesPerCol> -d <desync_flag>') sys.exit() elif opt in ("-r", "--NumberOfRows"): NumberOfRows = int(arg) elif opt in ("-c", "--NumberOfCols"): NumberOfCols = int(arg) elif opt in ("-b", "--FrameBitsPerRow"): FrameBitsPerRow = int(arg) elif opt in ("-f", "--MaxFramesPerCol"): MaxFramesPerCol = int(arg) elif opt in ("-d", "--desync_flag"): desync_flag = int(arg) print ('NumberOfRows is "', NumberOfRows) print ('NumberOfCols is "', NumberOfCols) print ('FrameBitsPerRow is "', FrameBitsPerRow) print ('MaxFramesPerCol is "', MaxFramesPerCol) print ('desync_flag is "', desync_flag) print ('FrameSelectWidth is "', FrameSelectWidth) print ('RowSelectWidth is "', RowSelectWidth) wrapper_top_str = "" config_str = "" configfsm_str = "" data_reg_modules = "" strobe_reg_modules = "" testbench_str = "" with open("./template_files/eFPGA_top_sky130_template.v", 'r') as file : wrapper_top_str = file.read() with open("./template_files/Config_template.v", 'r') as file : config_str = file.read() with open("./template_files/ConfigFSM_template.v", 'r') as file : configfsm_str = file.read() with open("./template_files/tb_bitbang_template.vhd", 'r') as file : testbench_str = file.read() wrapper_top_str = wrapper_top_str.replace("[32-1:0] I_top", '['+str(NumberOfRows*2)+'-1:0] I_top') wrapper_top_str = wrapper_top_str.replace("[32-1:0] T_top", '['+str(NumberOfRows*2)+'-1:0] T_top') wrapper_top_str = wrapper_top_str.replace("[32-1:0] O_top", '['+str(NumberOfRows*2)+'-1:0] O_top') wrapper_top_str = wrapper_top_str.replace("[64-1:0] OPA", '['+str(NumberOfRows*4)+'-1:0] OPA') wrapper_top_str = wrapper_top_str.replace("[64-1:0] OPB", '['+str(NumberOfRows*4)+'-1:0] OPB') wrapper_top_str = wrapper_top_str.replace("[64-1:0] RES0", '['+str(NumberOfRows*4)+'-1:0] RES0') wrapper_top_str = wrapper_top_str.replace("[64-1:0] RES1", '['+str(NumberOfRows*4)+'-1:0] RES1') wrapper_top_str = wrapper_top_str.replace("[64-1:0] RES2", '['+str(NumberOfRows*4)+'-1:0] RES2') wrapper_top_str = wrapper_top_str.replace("parameter NumberOfRows = 16", "parameter NumberOfRows = "+str(NumberOfRows)) wrapper_top_str = wrapper_top_str.replace("parameter NumberOfCols = 19", "parameter NumberOfCols = "+str(NumberOfCols)) config_str = config_str.replace("parameter RowSelectWidth = 5", "parameter RowSelectWidth = "+str(RowSelectWidth)) config_str = config_str.replace("parameter FrameBitsPerRow = 32", "parameter FrameBitsPerRow = "+str(FrameBitsPerRow)) configfsm_str = configfsm_str.replace("parameter NumberOfRows = 16", "parameter NumberOfRows = "+str(NumberOfRows)) configfsm_str = configfsm_str.replace("parameter RowSelectWidth = 5", "parameter RowSelectWidth = "+str(RowSelectWidth)) configfsm_str = configfsm_str.replace("parameter FrameBitsPerRow = 32", "parameter FrameBitsPerRow = "+str(FrameBitsPerRow)) configfsm_str = configfsm_str.replace("parameter desync_flag = 20", "parameter desync_flag = "+str(desync_flag)) testbench_str = testbench_str.replace(" STD_LOGIC_VECTOR (32 -1 downto 0)", " STD_LOGIC_VECTOR ("+str(NumberOfRows*2)+" -1 downto 0)") testbench_str = testbench_str.replace("STD_LOGIC_VECTOR (64 -1 downto 0)", "STD_LOGIC_VECTOR ("+str(NumberOfRows*4)+" -1 downto 0)") for row in range(NumberOfRows): data_reg_module_temp ="" data_reg_name = 'Frame_Data_Reg_'+str(row) wrapper_top_str+='\t'+data_reg_name+' Inst_'+data_reg_name+' (\n' wrapper_top_str+='\t.FrameData_I(LocalWriteData),\n' wrapper_top_str+='\t.FrameData_O(FrameRegister['+str(row)+'*FrameBitsPerRow+:FrameBitsPerRow]),\n' wrapper_top_str+='\t.RowSelect(RowSelect),\n' wrapper_top_str+='\t.CLK(CLK)\n' wrapper_top_str+='\t);\n\n' with open("./template_files/Frame_Data_Reg_template.v", 'r') as file : data_reg_module_temp = file.read() data_reg_module_temp=data_reg_module_temp.replace("Frame_Data_Reg", data_reg_name) data_reg_module_temp=data_reg_module_temp.replace("parameter FrameBitsPerRow = 32", "parameter FrameBitsPerRow = "+str(FrameBitsPerRow)) data_reg_module_temp=data_reg_module_temp.replace("parameter RowSelectWidth = 5", "parameter RowSelectWidth = "+str(RowSelectWidth)) data_reg_module_temp=data_reg_module_temp.replace("parameter Row = 1", "parameter Row = "+str(row+1)) data_reg_modules += data_reg_module_temp+'\n\n' for col in range(NumberOfCols): strobe_reg_module_temp ="" strobe_reg_name = 'Frame_Select_'+str(col) wrapper_top_str+='\t'+strobe_reg_name+' Inst_'+strobe_reg_name+' (\n' wrapper_top_str+='\t.FrameStrobe_I(FrameAddressRegister[MaxFramesPerCol-1:0]),\n' wrapper_top_str+='\t.FrameStrobe_O(FrameSelect['+str(col)+'*MaxFramesPerCol +: MaxFramesPerCol]),\n' wrapper_top_str+='\t.FrameSelect(FrameAddressRegister[FrameBitsPerRow-1:FrameBitsPerRow-(FrameSelectWidth)]),\n' wrapper_top_str+='\t.FrameStrobe(LongFrameStrobe)\n' wrapper_top_str+='\t);\n\n' with open("./template_files/Frame_Select_template.v", 'r') as file : strobe_reg_module_temp = file.read() strobe_reg_module_temp=strobe_reg_module_temp.replace("Frame_Select", strobe_reg_name) strobe_reg_module_temp=strobe_reg_module_temp.replace("parameter MaxFramesPerCol = 20", "parameter MaxFramesPerCol = "+str(MaxFramesPerCol)) strobe_reg_module_temp=strobe_reg_module_temp.replace("parameter FrameSelectWidth = 5", "parameter FrameSelectWidth = "+str(FrameSelectWidth)) strobe_reg_module_temp=strobe_reg_module_temp.replace("parameter Col = 18", "parameter Col = "+str(col)) strobe_reg_modules += strobe_reg_module_temp+'\n\n' wrapper_top_str+='\teFPGA Inst_eFPGA(\n' I_top_str ="" T_top_str = "" O_top_str = "" count = 0 for i in range(NumberOfRows*2-1,-1,-2): count += 1 I_top_str+='\t.Tile_X0Y'+str(count)+'_A_I_top(I_top['+str(i)+']),\n' I_top_str+='\t.Tile_X0Y'+str(count)+'_B_I_top(I_top['+str(i-1)+']),\n' T_top_str+='\t.Tile_X0Y'+str(count)+'_A_T_top(T_top['+str(i)+']),\n' T_top_str+='\t.Tile_X0Y'+str(count)+'_B_T_top(T_top['+str(i-1)+']),\n' O_top_str+='\t.Tile_X0Y'+str(count)+'_A_O_top(O_top['+str(i)+']),\n' O_top_str+='\t.Tile_X0Y'+str(count)+'_B_O_top(O_top['+str(i-1)+']),\n' OPA_str ="" OPB_str = "" RES0_str = "" RES1_str = "" RES2_str = "" count = 0 for i in range(NumberOfRows*4-1,-1,-4): count += 1 OPA_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_OPA_I0(OPA['+str(i)+']),\n' OPA_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_OPA_I1(OPA['+str(i-1)+']),\n' OPA_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_OPA_I2(OPA['+str(i-2)+']),\n' OPA_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_OPA_I3(OPA['+str(i-3)+']),\n' OPB_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_OPB_I0(OPB['+str(i)+']),\n' OPB_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_OPB_I1(OPB['+str(i-1)+']),\n' OPB_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_OPB_I2(OPB['+str(i-2)+']),\n' OPB_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_OPB_I3(OPB['+str(i-3)+']),\n' RES0_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_RES0_O0(RES0['+str(i)+']),\n' RES0_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_RES0_O1(RES0['+str(i-1)+']),\n' RES0_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_RES0_O2(RES0['+str(i-2)+']),\n' RES0_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_RES0_O3(RES0['+str(i-3)+']),\n' RES1_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_RES1_O0(RES1['+str(i)+']),\n' RES1_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_RES1_O1(RES1['+str(i-1)+']),\n' RES1_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_RES1_O2(RES1['+str(i-2)+']),\n' RES1_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_RES1_O3(RES1['+str(i-3)+']),\n' RES2_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_RES2_O0(RES2['+str(i)+']),\n' RES2_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_RES2_O1(RES2['+str(i-1)+']),\n' RES2_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_RES2_O2(RES2['+str(i-2)+']),\n' RES2_str+='\t.Tile_X'+str(NumberOfCols-1)+'Y'+str(count)+'_RES2_O3(RES2['+str(i-3)+']),\n' wrapper_top_str+=I_top_str+'\n' wrapper_top_str+=T_top_str+'\n' wrapper_top_str+=O_top_str+'\n' wrapper_top_str+=OPA_str+'\n' wrapper_top_str+=OPB_str+'\n' wrapper_top_str+=RES0_str+'\n' wrapper_top_str+=RES1_str+'\n' wrapper_top_str+=RES2_str+'\n' wrapper_top_str+='\t//declarations\n' wrapper_top_str+='\t.UserCLK(CLK),\n' wrapper_top_str+='\t.FrameData(FrameData),\n' wrapper_top_str+='\t.FrameStrobe(FrameSelect)\n' wrapper_top_str+='\t);\n' wrapper_top_str+="\tassign FrameData = {32'h12345678,FrameRegister,32'h12345678};\n\n" wrapper_top_str+='endmodule\n\n' with open("./eFPGA_top_sky130.v", 'w') as file: file.write(wrapper_top_str) with open("./Frame_Data_Reg_Pack.v", 'w') as file: file.write(data_reg_modules) with open("./Frame_Select_Pack.v", 'w') as file: file.write(strobe_reg_modules) with open("./Config.v", 'w') as file: file.write(config_str) with open("./ConfigFSM.v", 'w') as file: file.write(configfsm_str) with open("./tb_bitbang.vhd", 'w') as file: file.write(testbench_str) #print("Finish") if __name__ == "__main__": main(sys.argv[1:])
nilq/baby-python
python
__all__ = ["Process", "ProcessError"] import os import sys import shlex import queue import select import logging import subprocess import collections import threading from itertools import chain from dataclasses import dataclass from typing import Sequence, Mapping def poll(fd: int, stop_event: threading.Event, ret_queue: queue.Queue, out_stream=None): poller = select.poll() poller.register(fd, select.POLLIN) ret = None stop = False while not stop: events = poller.poll(100) if not events and stop_event.is_set(): break for poll_fd, poll_event in events: if poll_fd != fd: continue data = os.read(poll_fd, 65536).decode() if not data: if stop_event.is_set(): stop = True break else: continue if out_stream is not None: out_stream.write(data) if ret is None: ret = data else: ret += data ret_queue.put(ret) Pipe = collections.namedtuple("Pipe", ("read", "write")) class ProcessError(Exception): pass @dataclass class Process: args: Sequence[str] cwd: str = "/" inherit_env: bool = True aux_env: Mapping[str, str] = None aux_paths: Sequence[str] = None print_stdout: bool = False print_stderr: bool = False _logger: logging.Logger = None def __post_init__(self): self._logger = logging.getLogger(self.__class__.__name__) self.args = list(map(str, self.args)) def create_env(self) -> Mapping[str, str]: env = dict() if self.inherit_env: env.update(os.environ.copy()) env["PATH"] = ":".join((":".join(sys.path), env["PATH"])) if self.aux_env is not None: env.update(self.aux_env) if self.aux_paths is not None: env["PATH"] = ":".join(chain(self.aux_paths, [env["PATH"]])) return env def run(self, timeout=None): self._logger.info(f"running '{' '.join(map(shlex.quote, self.args))}'") stdout, stderr = Pipe(*os.pipe()), Pipe(*os.pipe()) process = subprocess.Popen( self.args, bufsize=0, env=self.create_env(), cwd=self.cwd, stdout=os.fdopen(stdout.write, "w"), stderr=os.fdopen(stderr.write, "w") ) stop_event = threading.Event() stdout_queue, stderr_queue = queue.Queue(), queue.Queue() stdout_thread = threading.Thread( name="stdout_thread", target=poll, kwargs=dict( fd=stdout.read, stop_event=stop_event, ret_queue=stdout_queue, out_stream=None if not self.print_stdout else sys.stdout ) ) stdout_thread.start() stderr_thread = threading.Thread( name="stdout_thread", target=poll, kwargs=dict( fd=stderr.read, stop_event=stop_event, ret_queue=stderr_queue, out_stream=None if not self.print_stderr else sys.stderr ) ) stderr_thread.start() ret = process.wait(timeout) stop_event.set() stdout_thread.join() stderr_thread.join() return ret, stdout_queue.get(), stderr_queue.get()
nilq/baby-python
python
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== r"""Train a ConvNet on MNIST using K-FAC. Multi tower training mode. See `convnet.train_mnist_multitower` for details. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags import tensorflow as tf from tensorflow.contrib.kfac.examples import convnet FLAGS = flags.FLAGS flags.DEFINE_string("data_dir", "/tmp/multitower_1/mnist", "local mnist dir") flags.DEFINE_integer("num_towers", 2, "Number of towers for multi tower training.") def main(unused_argv): _ = unused_argv assert FLAGS.num_towers > 1 devices = ["/gpu:{}".format(tower_id) for tower_id in range(FLAGS.num_towers)] convnet.train_mnist_multitower( FLAGS.data_dir, num_epochs=200, num_towers=FLAGS.num_towers, devices=devices) if __name__ == "__main__": tf.app.run(main=main)
nilq/baby-python
python
from pymongo import MongoClient from pymongo.database import Database import json import os from asset_manager.models.models import Asset, License def connect_db(connection_string: str, database_name: str) -> Database: client = MongoClient(connection_string) return client.get_database(database_name) def initialize(db: Database) -> None: data = json.load( open(os.getcwd() + "/src/asset_manager/data/fixtures.json") )["catalog"] if "initialized" in db.list_collection_names(): return db.get_collection("initialized").insert_one({"data": "initialized"}) assets = [Asset(**asset) for asset in data["assets"]] licenses = [License(**asset) for asset in data["licences"]] db.get_collection("assets").insert_many(map(dict, assets)) db.get_collection("licenses").insert_many(map(dict, licenses))
nilq/baby-python
python
from __future__ import annotations import csv import gzip import json import os import shutil import time from typing import Iterator from decouple import config from light_controller.const import MODE_BRIGHTNESS, MODE_COLOR_TEMP, MODE_HS from light_controller.controller import LightController from light_controller.hass import HassLightController from light_controller.hue import HueLightController from powermeter.errors import OutdatedMeasurementError, PowerMeterError from powermeter.hass import HassPowerMeter from powermeter.kasa import KasaPowerMeter from powermeter.powermeter import PowerMeter from powermeter.shelly import ShellyPowerMeter from powermeter.tasmota import TasmotaPowerMeter from powermeter.tuya import TuyaPowerMeter from PyInquirer import prompt CSV_HEADERS = { MODE_HS: ["bri", "hue", "sat", "watt"], MODE_COLOR_TEMP: ["bri", "mired", "watt"], MODE_BRIGHTNESS: ["bri", "watt"], } MAX_BRIGHTNESS = 255 MAX_SAT = 254 MAX_HUE = 65535 POWER_METER_HASS = "hass" POWER_METER_KASA = "kasa" POWER_METER_SHELLY = "shelly" POWER_METER_TASMOTA = "tasmota" POWER_METER_TUYA = "tuya" POWER_METERS = [ POWER_METER_HASS, POWER_METER_KASA, POWER_METER_SHELLY, POWER_METER_TASMOTA, POWER_METER_TUYA, ] SELECTED_POWER_METER = config("POWER_METER") LIGHT_CONTROLLER_HUE = "hue" LIGHT_CONTROLLER_HASS = "hass" LIGHT_CONTROLLERS = [LIGHT_CONTROLLER_HUE, LIGHT_CONTROLLER_HASS] SELECTED_LIGHT_CONTROLLER = config("LIGHT_CONTROLLER") SLEEP_TIME = config("SLEEP_TIME", default=2, cast=int) SLEEP_TIME_HUE = config("SLEEP_TIME_HUE", default=5, cast=int) SLEEP_TIME_SAT = config("SLEEP_TIME_SAT", default=10, cast=int) START_BRIGHTNESS = config("START_BRIGHTNESS", default=1, cast=int) MAX_RETRIES = config("MAX_RETRIES", default=5, cast=int) SAMPLE_COUNT = config("SAMPLE_COUNT", default=1, cast=int) SHELLY_IP = config("SHELLY_IP") TUYA_DEVICE_ID = config("TUYA_DEVICE_ID") TUYA_DEVICE_IP = config("TUYA_DEVICE_IP") TUYA_DEVICE_KEY = config("TUYA_DEVICE_KEY") TUYA_DEVICE_VERSION = config("EMAIL_PORT", default="3.3") HUE_BRIDGE_IP = config("HUE_BRIDGE_IP") HASS_URL = config("HASS_URL") HASS_TOKEN = config("HASS_TOKEN") TASMOTA_DEVICE_IP = config("TASMOTA_DEVICE_IP") KASA_DEVICE_IP = config("KASA_DEVICE_IP") class Measure: def __init__(self, light_controller: LightController, power_meter: PowerMeter): self.light_controller = light_controller self.power_meter = power_meter def start(self): answers = prompt(self.get_questions()) self.light_controller.process_answers(answers) self.power_meter.process_answers(answers) self.light_info = self.light_controller.get_light_info() color_mode = answers["color_mode"] export_directory = os.path.join( os.path.dirname(__file__), "export", self.light_info.model_id ) if not os.path.exists(export_directory): os.makedirs(export_directory) if answers["generate_model_json"]: standby_usage = self.measure_standby_usage() self.write_model_json( directory=export_directory, standby_usage=standby_usage, name=answers["model_name"], measure_device=answers["measure_device"], ) csv_file_path = f"{export_directory}/{color_mode}.csv" with open(csv_file_path, "w", newline="") as csv_file: csv_writer = csv.writer(csv_file) self.light_controller.change_light_state(MODE_BRIGHTNESS, on=True, bri=1) # Initially wait longer so the smartplug can settle print("Start taking measurements for color mode: ", color_mode) print("Waiting 10 seconds...") time.sleep(10) csv_writer.writerow(CSV_HEADERS[color_mode]) for count, variation in enumerate(self.get_variations(color_mode)): print("Changing light to: ", variation) variation_start_time = time.time() self.light_controller.change_light_state( color_mode, on=True, **variation ) time.sleep(SLEEP_TIME) power = self.take_power_measurement(variation_start_time) print("Measured power: ", power) print() row = list(variation.values()) row.append(power) csv_writer.writerow(row) if count % 100 == 0: csv_file.flush() csv_file.close() if answers["gzip"] or True: self.gzip_csv(csv_file_path) def take_power_measurement(self, start_timestamp: float, retry_count=0) -> float: measurements = [] # Take multiple samples to reduce noise for i in range(SAMPLE_COUNT): print("Taking sample", i) try: measurement = self.power_meter.get_power() except PowerMeterError as err: if retry_count == MAX_RETRIES: raise err retry_count += 1 self.take_power_measurement(start_timestamp, retry_count) # Check if measurement is not outdated if measurement.updated < start_timestamp: # Prevent endless recursion and raise exception if retry_count == MAX_RETRIES: raise OutdatedMeasurementError( "Power measurement is outdated. Aborting after {} retries".format( MAX_RETRIES ) ) retry_count += 1 time.sleep(1) self.take_power_measurement(start_timestamp, retry_count) measurements.append(measurement.power) time.sleep(0.5) avg = sum(measurements) / len(measurements) return round(avg, 2) def gzip_csv(self, csv_file_path: str): with open(csv_file_path, "rb") as csv_file: with gzip.open(f"{csv_file_path}.gz", "wb") as gzip_file: shutil.copyfileobj(csv_file, gzip_file) def measure_standby_usage(self) -> float: self.light_controller.change_light_state(MODE_BRIGHTNESS, on=False) start_time = time.time() print("Measuring standby usage. Waiting for 5 seconds...") time.sleep(5) return self.take_power_measurement(start_time) def get_variations(self, color_mode: str): if color_mode == MODE_HS: yield from self.get_hs_variations() elif color_mode == MODE_COLOR_TEMP: yield from self.get_ct_variations() else: yield from self.get_brightness_variations() def get_ct_variations(self) -> Iterator[dict]: min_mired = self.light_info.min_mired max_mired = self.light_info.max_mired for bri in self.inclusive_range(START_BRIGHTNESS, MAX_BRIGHTNESS, 5): for mired in self.inclusive_range(min_mired, max_mired, 10): yield {"bri": bri, "ct": mired} def get_hs_variations(self) -> Iterator[dict]: for bri in self.inclusive_range(START_BRIGHTNESS, MAX_BRIGHTNESS, 10): for sat in self.inclusive_range(1, MAX_SAT, 10): time.sleep(SLEEP_TIME_SAT) for hue in self.inclusive_range(1, MAX_HUE, 2000): time.sleep(SLEEP_TIME_HUE) yield {"bri": bri, "hue": hue, "sat": sat} def get_brightness_variations(self) -> Iterator[dict]: for bri in self.inclusive_range(START_BRIGHTNESS, MAX_BRIGHTNESS, 1): yield {"bri": bri} def inclusive_range(self, start: int, end: int, step: int) -> Iterator[int]: i = start while i < end: yield i i += step yield end def write_model_json( self, directory: str, standby_usage: float, name: str, measure_device: str ): json_data = json.dumps( { "measure_device": measure_device, "measure_method": "script", "name": name, "standby_usage": standby_usage, "supported_modes": ["lut"], }, indent=4, sort_keys=True, ) json_file = open(os.path.join(directory, "model.json"), "w") json_file.write(json_data) json_file.close() def get_questions(self) -> list[dict]: return ( [ { "type": "list", "name": "color_mode", "message": "Select the color mode?", "default": MODE_HS, "choices": [MODE_HS, MODE_COLOR_TEMP, MODE_BRIGHTNESS], }, { "type": "confirm", "message": "Do you want to generate model.json?", "name": "generate_model_json", "default": True, }, { "type": "input", "name": "model_name", "message": "Specify the full light model name", "when": lambda answers: answers["generate_model_json"], }, { "type": "input", "name": "measure_device", "message": "Which device (manufacturer, model) do you use to take the measurement?", "when": lambda answers: answers["generate_model_json"], }, { "type": "confirm", "message": "Do you want to gzip CSV files?", "name": "gzip", "default": True, }, ] + self.light_controller.get_questions() + self.power_meter.get_questions() ) class LightControllerFactory: def hass(self): return HassLightController(HASS_URL, HASS_TOKEN) def hue(self): return HueLightController(HUE_BRIDGE_IP) def create(self) -> LightController: factories = {LIGHT_CONTROLLER_HUE: self.hue, LIGHT_CONTROLLER_HASS: self.hass} factory = factories.get(SELECTED_LIGHT_CONTROLLER) if factory is None: print("factory not found") # todo exception print("light controller", SELECTED_LIGHT_CONTROLLER) return factory() class PowerMeterFactory: def hass(self): return HassPowerMeter(HASS_URL, HASS_TOKEN) def kasa(self): return KasaPowerMeter(KASA_DEVICE_IP) def shelly(self): return ShellyPowerMeter(SHELLY_IP) def tasmota(self): return TasmotaPowerMeter(TASMOTA_DEVICE_IP) def tuya(self): return TuyaPowerMeter( TUYA_DEVICE_ID, TUYA_DEVICE_IP, TUYA_DEVICE_KEY, TUYA_DEVICE_VERSION ) def create(self) -> PowerMeter: factories = { POWER_METER_HASS: self.hass, POWER_METER_KASA: self.kasa, POWER_METER_SHELLY: self.shelly, POWER_METER_TASMOTA: self.tasmota, POWER_METER_TUYA: self.tuya, } factory = factories.get(SELECTED_POWER_METER) if factory is None: print("factory not found") # todo exception print("powermeter", SELECTED_POWER_METER) return factory() light_controller_factory = LightControllerFactory() power_meter_factory = PowerMeterFactory() measure = Measure(light_controller_factory.create(), power_meter_factory.create()) measure.start()
nilq/baby-python
python
#!/usr/bin/python """ Euclid covariance matrices, taken from arXiv:1206.1225 """ import numpy as np def covmat_for_fom(sig_x, sig_y, fom, sgn=1.): """ Return covariance matrix, given sigma_x, sigma_y, and a FOM. Diagonal elements are unique up to a sign (which must be input manually). (N.B. In figures, if ellipse leans to the left, sgn=-1., otherwise +1.) """ sig_xy = sgn * np.sqrt((sig_x*sig_y)**2. - 1./fom**2.) cov = np.array( [[sig_x**2., sig_xy], [sig_xy, sig_y**2.]] ) return cov def add_planck_prior(F, lbls, info=False): """ Add Planck prior to a given Fisher matrix. """ print("WARNING: add_planck_prior() is obsolete.") #lbls_planck = ['omegak', 'omegaDE', 'w0', 'wa'] lbls_planck = ['w0', 'wa', 'omegaDE', 'omegak', 'w_m', 'w_b', 'n_s'] Fpl = F.copy() for ii in range(len(lbls_planck)): if lbls_planck[ii] in lbls: for jj in range(len(lbls_planck)): if lbls_planck[jj] in lbls: _i = lbls.index(lbls_planck[ii]) _j = lbls.index(lbls_planck[jj]) Fpl[_i,_j] += planck_prior_full[ii,jj] if info: print(lbls[_i], lbls_planck[ii], "//", lbls[_j], lbls_planck[jj]) if lbls_planck[ii] not in lbls: if info: print("Planck prior:", lbls_planck[ii], "not found in Fisher matrix.") return Fpl def add_detf_planck_prior(F, lbls, info=False): """ Add Planck prior from DETF. See process_detf_planck_fisher.py for details of its construction. """ F_planck = np.genfromtxt("fisher_detf_planck.dat") lbls_planck = ['n_s', 'omegaM', 'omegab', 'omegak', 'omegaDE', 'h', 'w0', 'wa', 'logA_S'] # FIXME: Should add nuisance parameters to Fisher matrix. print("FIXME: add_detf_planck_prior() should add nuisance parameters too.") # Add prior Fpl = F.copy() for ii in range(len(lbls_planck)): if lbls_planck[ii] in lbls: for jj in range(len(lbls_planck)): if lbls_planck[jj] in lbls: _i = lbls.index(lbls_planck[ii]) _j = lbls.index(lbls_planck[jj]) Fpl[_i,_j] += F_planck[ii,jj] if info: print(lbls[_i], lbls_planck[ii], "//", lbls[_j], lbls_planck[jj]) if lbls_planck[ii] not in lbls: if info: print("Planck prior:", lbls_planck[ii], "not found in Fisher matrix.") return Fpl def euclid_to_rf(F, cosmo): """ Transform Planck prior from Euclid science review, Amendola (et al. 2012), Table 1.17, to our set of parameters. Fisher matrix available from Mukherjee et al., arXiv:0803.1616v1. Euclid: {w0, wa, omega_DE, omega_k, w_m, w_b, n_s} Old BAOFisher: {n_s, w0, wa, omega_b, omega_k, omega_DE, h} New BAOFisher: {n_s, w0, wa, w_b, omega_k, omega_DE, h} """ # Fiducial parameters from Mukherjee et al. h = 0.73; w_m = 0.127; w_b = 0.022 ok = 0.; w0 = -1.; wa = 0.; n_s = 0.9602 h2 = h**2. om = w_m / h2; ob = w_b / h2 ode = 1. - om - ok # Our fiducial values _om = cosmo['omega_M_0']; _ob = cosmo['omega_b_0'] _ode = cosmo['omega_lambda_0']; _h = cosmo['h']; _ns = cosmo['ns'] _ok = 1. - _om - _ode; _wb = _ob*_h**2.; _w0 = -1.; _wa = 0. # Construct transformation matrix from derivatives dw0_dp = [0., 1., 0., 0., 0., 0., 0.] dwa_dp = [0., 0., 1., 0., 0., 0., 0.] doDE_dp = [0., 0., 0., 0., 0., 1., 0.] dok_dp = [0., 0., 0., 0., 1., 0., 0.] dwm_dp = [0., 0., 0., 0., -h2, -h2, 2.*h*om] dwb_dp = [0., 0., 0., h2, 0., 0., 2.*h*ob] #dwb_dp = [0., 0., 0., 1., 0., 0., 0.] dns_dp = [1., 0., 0., 0., 0., 0., 0.] M = [dw0_dp, dwa_dp, doDE_dp, dok_dp, dwm_dp, dwb_dp, dns_dp] M = np.array(M).T # Re-scale to our fiducial values M[0,:] *= n_s / _ns M[1,:] *= w0 / _w0 M[3,:] *= ob / _ob #M[3,:] *= w_b / _wb M[5,:] *= ode / _ode M[6,:] *= h / _h # Transform into new set of parameters Fnew = np.dot(M, np.dot(F, M.T)) return Fnew def camb_to_baofisher(F, cosmo): """ Transform Fisher matrix in CAMB parameters to our parameters (assumes the same fiducial values) CAMB: {n_s, w0, wa, w_b, omega_k, w_cdm, h} BAOFisher: {n_s, w0, wa, omega_b, omega_k, omega_DE, h} """ h = cosmo['h']; h2 = cosmo['h']**2. om = cosmo['omega_M_0']; ob = cosmo['omega_b_0'] ode = cosmo['omega_lambda_0'] ok = 1. - om - ode # Construct transformation matrix from derivatives dns_dp = [1., 0., 0., 0., 0., 0., 0.] dw0_dp = [0., 1., 0., 0., 0., 0., 0.] dwa_dp = [0., 0., 1., 0., 0., 0., 0.] dwb_dp = [0., 0., 0., h2, 0., 0., 2.*h*ob] dok_dp = [0., 0., 0., 0., 1., 0., 0.] dwc_dp = [0., 0., 0., -h2, -h2, -h2, 2.*h*(1.-ok-ode-ob)] dh_dp = [0., 0., 0., 0., 0., 0., 1.] M = [dns_dp, dw0_dp, dwa_dp, dwb_dp, dok_dp, dwc_dp, dh_dp] M = np.array(M).T # Transform into new set of parameters Fnew = np.dot(M, np.dot(F, M.T)) return Fnew def detf_to_rf(fname, cosmo, omegab=False): """ Transform Planck prior from DETF to our set of parameters. DETF Fisher matrix can be obtained from: http://c3.lbl.gov:8000/Trac.Cosmology/browser/Programs/FoMSWG/tags/original/DATA/PLANCK.dat?rev=842 DETF: {n_s, w_m, w_b, w_k, w_DE, deltaGamma, M, logG0, log A_S, {w_i}} BAOFisher: {n_s, w0, wa, w_b, omega_k, omega_DE, h, sigma_8} If omegab = True, use Omega_b as a parameter instead of w_b = Omega_b h^2. DETF fiducial parameters are taken from the FoMSWG Technical Report (p8). """ # Load DETF Planck Fisher matrix (indexes start from 0) dat = np.genfromtxt(fname).T N = np.max(dat[0]) + 1 F = np.zeros((N,N)) for k in range(dat.shape[1]): i = dat[0,k] j = dat[1,k] F[i,j] = dat[2,k] # DETF fiducial values (from p8 of arXiv:0901.0721) n_s = 0.963; w_m = 0.1326; w_b = 0.0227; w_k = 0.; w_DE = 0.3844; h = 0.719 w0 = -1.; wa = 0.; h2 = h**2.; sig8 = 0.798 om = w_m / h2; ob = w_b / h2; ok = w_k / h2; ode = w_DE / h2 # Our fiducial values _om = cosmo['omega_M_0']; _ob = cosmo['omega_b_0'] _ode = cosmo['omega_lambda_0']; _h = cosmo['h']; _ns = cosmo['ns'] _sig8 = cosmo['sigma_8'] _ok = 1. - _om - _ode; _wb = _ob * _h**2.; _w0 = -1.; _wa = 0. a0 = 0.1; da = 0.025 # Scale-factor binning # Define transformation matrix (derivatives) M = np.zeros((8, N)) # d(DETF)/d(n_s) M[0,0] = 1. * (n_s/_ns) # d(DETF)/d(w0), d(DETF)/d(wa) for i in range(36): aa = 1. - (float(i) + 0.5)*da # Centroid of 'a' bin (p8 of arXiv:0901.0721) M[1, 9+i] = 1. * (w0/_w0) # d(w_i)/d(w0) M[2, 9+i] = 1. - aa # d(w_i)/d(wa) # d(DETF)/d(omega_b) if omegab: M[3,2] = h2 * (ob/_ob) # d(w_b)/d(omega_b) else: M[3,2] = 1. * (w_b/_wb) # d(w_b)/d(w_b) # d(DETF)/d(omega_k) M[4,1] = -h2 # d(w_m)/d(omega_k) M[4,3] = h2 # d(w_k)/d(omega_k) # d(DETF)/d(omega_DE) M[5,1] = -h2 * (ode/_ode) # d(w_m)/d(omega_DE) M[5,4] = h2 * (ode/_ode) # d(w_DE)/d(omega_DE) # d(DETF)/d(h) if omegab: M[6,2] = 2.*h*ob * (h/_h) # d(w_b)/d(h) else: M[6,2] = 0. # d(w_b)/d(h), since w_b is indep. parameter M[6,1] = 2.*h*om * (h/_h) # d(w_m)/d(h) M[6,3] = 2.*h*ok * (h/_h) # d(w_k)/d(h) M[6,4] = 2.*h*ode * (h/_h) # d(w_DE)/d(h) # d(DETF)/d(sigma_8) M[7,8] = 2. / sig8 * (sig8/_sig8) # dlog(A_s)/d(sigma_8) == dlog(Delta^2)/d(sigma_8) # Transform into new set of parameters M = np.array(M) Fnew = np.dot(M, np.dot(F, M.T)) return Fnew # gamma, w0 (for fixed omega_k=0, wa=0) [Tbl 1.5, Fig 1.16] cov_gamma_w_ref = covmat_for_fom(0.02, 0.017, 3052, sgn=-1.) # Reference cov_gamma_w_opt = covmat_for_fom(0.02, 0.016, 3509, sgn=-1.) # Optimistic cov_gamma_w_pes = covmat_for_fom(0.026, 0.02, 2106, sgn=-1.) # Pessimistic # gamma, w0 (for fixed wa=0, but omega_k marginalised over) [Tbl 1.6, Fig 1.17] cov_gamma_w_okmarg_ref = covmat_for_fom(0.03, 0.04, 1342, sgn=-1.) cov_gamma_w_okmarg_opt = covmat_for_fom(0.03, 0.03, 1589, sgn=-1.) cov_gamma_w_okmarg_pes = covmat_for_fom(0.04, 0.05, 864, sgn=-1.) # w0, w1 (for fixed gamma) [Tbl 1.11, Fig 1.20] # (w0, w1 are the same as w0 and wa) cov_w0_wa_fixed_gamma_ok_ref = covmat_for_fom(0.05, 0.16, 430, sgn=-1.) cov_w0_wa_fixed_gamma_ref = covmat_for_fom(0.06, 0.26, 148, sgn=-1.) # (z, f_g, sigma_f [ref]) [Tbl 1.4] # Seems that omega_k, w_0, w_a are all marginalised over (but no gamma parameter) sigma_f = np.array([ [0.7, 0.76, 0.011], [0.8, 0.80, 0.010], [0.9, 0.82, 0.009], [1.0, 0.84, 0.009], [1.1, 0.86, 0.009], [1.2, 0.87, 0.009], [1.3, 0.88, 0.010], [1.4, 0.89, 0.010], [1.5, 0.91, 0.011], [1.6, 0.91, 0.012], [1.7, 0.92, 0.014], [1.8, 0.93, 0.014], [1.9, 0.93, 0.017], [2.0, 0.94, 0.023] ] ).T # D_A(z) and H(z) constraints for Euclid (unofficial, optimistic?) # (z, y, sigma_y, y', sigma_y') [Tbl 1, arXiv:1311.6817] # y \propto r(z), y' \propto 1 / H(z) # => sig_DA/DA = sig_y / y # => sig_H/H = - sig_y' / y' bao_scales = np.array([ [0.1, 2.758, 0.616, 27.153, 3.676], [0.25, 6.742, 0.250, 25.449, 1.477], [0.35, 9.214, 0.200, 24.877, 0.892], [0.45, 11.578, 0.180, 23.147, 0.617], [0.55, 13.904, 0.169, 22.347, 0.462], [0.65, 16.107, 0.162, 20.915, 0.364], [0.75, 18.105, 0.158, 19.681, 0.299], [0.85, 19.938, 0.156, 18.496, 0.252], [0.95, 21.699, 0.156, 17.347, 0.218], [1.05, 23.341, 0.157, 16.583, 0.191], [1.15, 25.138, 0.158, 15.434, 0.171], [1.25, 26.481, 0.160, 14.744, 0.154], [1.35, 27.515, 0.169, 13.815, 0.147], [1.45, 29.381, 0.185, 13.207, 0.145], [1.55, 30.963, 0.209, 12.481, 0.149], [1.65, 31.371, 0.240, 11.904, 0.156], [1.75, 32.904, 0.281, 11.217, 0.168], [1.85, 34.028, 0.338, 10.899, 0.186], [1.95, 34.790, 0.417, 10.294, 0.212], [2.05, 35.645, 0.529, 9.752, 0.250], [2.15, 37.341, 0.693, 9.344, 0.303] ]).T # Massive neutrino constraints (unmarginalised, so v. optimistic) # Euclid + Boss (Mnu = 0.125eV, normal hierarchy) [Tbls 1+3, arXiv:1012.2868] # (Mnu, n_s), sigma(Mnu) = 0.1795, sigma(n_s) = 0.0314, corr = 0.717 cov_mnu_ns_euclid_boss = np.array([ [0.1795**2., 0.717 * (0.1795 * 0.0314)], [0.717 * (0.1795 * 0.0314), 0.0314**2.] ]) # Euclid + BOSS + Planck (Mnu = 0.125eV, normal hierarchy) [Tbls 1+3, arXiv:1012.2868] # (Mnu, n_s), sigma(Mnu) = 0.0311, sigma(n_s) = 0.0022, corr = -0.034 cov_mnu_ns_euclid_boss_planck = np.array( [ [0.0311**2., -0.034 * (0.0311 * 0.0022)], [-0.034 * (0.0311 * 0.0022), 0.0022**2.] ]) # Planck prior # w0, wa, omega_DE, omega_k, w_m, w_b, n_s # From Euclid science review, Amendola (et al. 2012), Table 1.17 planck_prior_full = np.array([ [0.172276e6, 0.490320e5, 0.674392e6, -0.208974e7, 0.325219e7, -0.790504e7, -0.549427e5], [0.490320e5, 0.139551e5, 0.191940e6, -0.594767e6, 0.925615e6, -0.224987e7, -0.156374e5], [0.674392e6, 0.191940e6, 0.263997e7, -0.818048e7, 0.127310e8, -0.309450e8, -0.215078e6], [-0.208974e7, -0.594767e6, -0.818048e7, 0.253489e8, -0.394501e8, 0.958892e8, 0.666335e6], [0.325219e7, 0.925615e6, 0.127310e8, -0.394501e8, 0.633564e8, -0.147973e9, -0.501247e6], [-0.790504e7, -0.224987e7, -0.309450e8, 0.958892e8, -0.147973e9, 0.405079e9, 0.219009e7], [-0.549427e5, -0.156374e5, -0.215078e6, 0.666335e6, -0.501247e6, 0.219009e7, 0.242767e6] ]).T planck_prior = np.zeros((4,4)) # Order: omega_k, omega_DE, w0, wa _old_idxs = [3, 2, 0, 1] for i in range(4): for j in range(4): planck_prior[i,j] = planck_prior_full[_old_idxs[i],_old_idxs[j]]
nilq/baby-python
python
from spotcli.configuration.configuration import load __all__ = ["load"]
nilq/baby-python
python
from mathutils import Vector, Matrix, Euler, Quaternion from typing import List def convert_source_rotation(rot: List[float]): qrot = Quaternion([rot[0], rot[1], -rot[3], rot[2]]) # qrot.rotate(Euler([0, 0, 90])) return qrot def convert_source_position(pos: List[float]): pos = Vector([pos[0], pos[2], -pos[1]]) # pos.rotate(Euler([0, -90, 0])) return pos def convert_source_animset_rotation(rot: List[float]): return convert_source_rotation(rot) def convert_source_animset_position(pos: List[float]): pos = Vector([pos[0], -pos[2], pos[1]]) return pos
nilq/baby-python
python
# from vocab import Vocab # from tr_embed import TREmbed
nilq/baby-python
python
def hidden_layer_backpropagate(layer, prev_outputs, outputs, next_weights_totlin, rate): tot_lin = [] weights = [] i = 0 for (n, o) in zip(layer, outputs): op_lin = n.activation_d(o) total_op = 0 for w, tl in zip(next_weights_totlin["w"], next_weights_totlin["tl"]): total_op = total_op + tl * w[i] grad = [] for pl_o in prev_outputs: lin_w = pl_o g_w = total_op * op_lin * lin_w grad.append(g_w) g_b = total_op * op_lin tot_lin.append(total_op * op_lin) weights.append(n.weights) n.adjust_weights(grad, rate) n.adjust_bias(g_b, rate) i = i + 1 return {'w':weights, 'tl':tot_lin} def output_layer_backpropagate(layer, outputs, targets, inputs, rate): tot_lin = [] weights = [] for (n, o, t) in zip(layer, outputs, targets): grad = [] total_op = layer.loss_d(t, o) op_lin = n.activation_d(o) for inp in inputs: lin_w = inp g_w = total_op * op_lin * lin_w grad.append(g_w) g_b = total_op * op_lin tot_lin.append(total_op * op_lin) weights.append(n.weights) n.adjust_weights(grad, rate) n.adjust_bias(g_b, rate) return {'w':weights, 'tl':tot_lin}
nilq/baby-python
python
#!/usr/bin/python # code from https://www.raspberrypi.org/forums/viewtopic.php?t=220247#p1352169 # pip3 install pigpio # git clone https://github.com/stripcode/pigpio-stepper-motor ''' # connection to adafruit TB6612 # motor: SY28STH32-0674A Vcmotor --> 12V 5A power supply VM --> floating Vcc --> 3V3 Pin 17 GND --> GND Pin 06 PwmA --> 3V3 Pin 01 AIN2 --> Pin 15 - BCM 22 AIN1 --> Pin 11 - BCM 17 STBY --> Pin 13 - BCM 27 BIN1 --> Pin 16 - BCM 23 BIN2 --> Pin 18 - BCM 24 PwmB --> Pin 32 - BCM MotorA --> Red (A+) and Green (A-) wires MotorB --> Blue (B+) and Black (B-) wires GND of Power supply --> Pin 39 (gnd) Raspberry Pi ''' import pigpio, time from PigpioStepperMotor import StepperMotor import argparse #move 180 is 60ul using 10ml syringe parser=argparse.ArgumentParser() parser.add_argument('move', type=int) args=parser.parse_args() move=args.move pi = pigpio.pi() motor = StepperMotor(pi, 17, 23, 22, 24) pwma = pigpio.pi() pwma.write(18,1) pwmb = pigpio.pi() pwmb.write(12,1) stby = pigpio.pi() stby.write(27,0) if move>0: for i in range(move): stby.write(27,1) motor.doClockwiseStep() else: for i in range(-1*move): stby.write(27,1) motor.doCounterclockwiseStep()
nilq/baby-python
python
import unittest from linkml.generators.markdowngen import MarkdownGenerator from linkml.utils.schemaloader import SchemaLoader from linkml.utils.yamlutils import as_yaml from tests.utils.test_environment import TestEnvironmentTestCase from tests.test_issues.environment import env class Issue63TestCase(TestEnvironmentTestCase): env = env def test_issue_63(self): """ We should get an error from this -- we have a list as an object """ with self.assertRaises(ValueError) as error: SchemaLoader(env.input_path('issue_63.yaml')) self.assertEqual("['s3'] is not a valid URI or CURIE", str(error.exception)) if __name__ == '__main__': unittest.main()
nilq/baby-python
python
# import gevent.monkey;gevent.monkey.patch_all() import time from funboost import boost, BrokerEnum,run_consumer_with_multi_process,ConcurrentModeEnum import nb_log logger = nb_log.get_logger('sdsda',is_add_stream_handler=False,log_filename='xxx.log') @boost('20000', broker_kind=BrokerEnum.REDIS, concurrent_num=2, log_level=20, qps=0, concurrent_mode=ConcurrentModeEnum.SINGLE_THREAD, ) def f_test_speed(x): pass # logger.debug(x) # f_test_speed2.push(x * 10) print(x) # time.sleep(20) # @boost('speed_test_queue2', broker_kind=BrokerEnum.REDIS, log_level=20, qps=2) # def f_test_speed2(y): # pass # print(y) if __name__ == '__main__': # f_test_speed.clear() # for i in range(1000000): # f_test_speed.push(i) # f_test_speed.consume() run_consumer_with_multi_process(f_test_speed,1) # # f_test_speed2.consume()
nilq/baby-python
python
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from datetime import datetime, timedelta from openerp.osv import fields, osv from openerp.tools.translate import _ from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT class sale_order_dates(osv.osv): """Add several date fields to Sale Orders, computed or user-entered""" _inherit = 'sale.order' def _get_date_planned(self, cr, uid, order, line, start_date, context=None): """Compute the expected date from the requested date, not the order date""" if order and order.requested_date: date_planned = datetime.strptime(order.requested_date, DEFAULT_SERVER_DATETIME_FORMAT) date_planned -= timedelta(days=order.company_id.security_lead) return date_planned.strftime(DEFAULT_SERVER_DATETIME_FORMAT) return super(sale_order_dates, self)._get_date_planned( cr, uid, order, line, start_date, context=context) def _get_effective_date(self, cr, uid, ids, name, arg, context=None): """Read the shipping date from the related packings""" # TODO: would be better if it returned the date the picking was processed? res = {} dates_list = [] for order in self.browse(cr, uid, ids, context=context): dates_list = [] for pick in order.picking_ids: dates_list.append(pick.date) if dates_list: res[order.id] = min(dates_list) else: res[order.id] = False return res def _get_commitment_date(self, cr, uid, ids, name, arg, context=None): """Compute the commitment date""" res = {} dates_list = [] for order in self.browse(cr, uid, ids, context=context): dates_list = [] order_datetime = datetime.strptime(order.date_order, DEFAULT_SERVER_DATETIME_FORMAT) for line in order.order_line: if line.state == 'cancel': continue dt = order_datetime + timedelta(days=line.delay or 0.0) dt_s = dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT) dates_list.append(dt_s) if dates_list: res[order.id] = min(dates_list) return res def onchange_requested_date(self, cr, uid, ids, requested_date, commitment_date, context=None): """Warn if the requested dates is sooner than the commitment date""" if (requested_date and commitment_date and requested_date < commitment_date): return {'warning': { 'title': _('Requested date is too soon!'), 'message': _("The date requested by the customer is " "sooner than the commitment date. You may be " "unable to honor the customer's request.") } } return {} _columns = { 'commitment_date': fields.function(_get_commitment_date, store=True, type='datetime', string='Commitment Date', help="Date by which the products are sure to be delivered. This is " "a date that you can promise to the customer, based on the " "Product Lead Times."), 'requested_date': fields.datetime('Requested Date', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, copy=False, help="Date by which the customer has requested the items to be " "delivered.\n" "When this Order gets confirmed, the Delivery Order's " "expected date will be computed based on this date and the " "Company's Security Delay.\n" "Leave this field empty if you want the Delivery Order to be " "processed as soon as possible. In that case the expected " "date will be computed using the default method: based on " "the Product Lead Times and the Company's Security Delay."), 'effective_date': fields.function(_get_effective_date, type='date', store=True, string='Effective Date', help="Date on which the first Delivery Order was created."), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
nilq/baby-python
python
__all__ = ['MASKED', 'NOMASK'] MASKED = object() NOMASK = object()
nilq/baby-python
python
from torchreid import metrics from torchreid.utils import re_ranking import numpy as np import torch from torch.nn import functional as F if __name__ == '__main__': ff = torch.load('train_avg_feature.pt') f_pids = np.load('train_pids.npy') f_camids = np.load('train_camids.npy') # eval_index = 50 # ef = ff[eval_index].unsqueeze(0).clone() # e_pids = f_pids[eval_index].reshape((1,)) # e_camids = f_camids[eval_index].reshape((1,)) ef = ff.clone() dist_metric='euclidean' print( 'Computing distance matrix with metric={} ...'.format(dist_metric) ) # normalize feature # print('Normalizing feature ...') # qf = F.normalize(qf, p=2, dim=1) # gf = F.normalize(gf, p=2, dim=1) distmat = metrics.compute_distance_matrix(ff, ef, dist_metric) distmat = distmat.numpy() # print('Applying person re-ranking ...') # distmat_qq = metrics.compute_distance_matrix(qf, qf, dist_metric) # distmat_gg = metrics.compute_distance_matrix(gf, gf, dist_metric) # distmat = re_ranking(distmat, distmat_qq, distmat_gg) print('Computing CMC and mAP ...') cmc, mAP = metrics.evaluate_rank( distmat, f_pids, f_pids, f_camids, f_camids, ) ranks=[1, 5, 10, 20] print('** Results **') print('mAP: {:.1%}'.format(mAP)) print('CMC curve') for r in ranks: print('Rank-{:<3}: {:.1%}'.format(r, cmc[r - 1])) ef = torch.zeros_like(ff) distmat = metrics.compute_distance_matrix(ff, ef, dist_metric) distmat = distmat.numpy() # print('Applying person re-ranking ...') # distmat_qq = metrics.compute_distance_matrix(qf, qf, dist_metric) # distmat_gg = metrics.compute_distance_matrix(gf, gf, dist_metric) # distmat = re_ranking(distmat, distmat_qq, distmat_gg) print('Computing CMC and mAP ...') zcmc, zmAP = metrics.evaluate_rank( distmat, f_pids, f_pids, f_camids, f_camids, ) ranks=[1, 5, 10, 20] print('** Results **') print('mAP: {:.1%}'.format(zmAP)) print('CMC curve') for r in ranks: print('Rank-{:<3}: {:.1%}'.format(r, zcmc[r - 1])) print(zmAP - mAP) print(sum(zcmc[:20] - cmc[:20])+ (zmAP - mAP))
nilq/baby-python
python
# General imports import os, json, logging, yaml, sys import click from luna.common.custom_logger import init_logger init_logger() logger = logging.getLogger('generate_tiles') from luna.common.utils import cli_runner _params_ = [('input_slide_image', str), ('output_dir', str), ('tile_size', int), ('batch_size', int), ('requested_magnification', float), ('num_cores', int)] @click.command() @click.argument('input_slide_image', nargs=1) @click.option('-o', '--output_dir', required=False, help='path to output directory to save results') @click.option('-nc', '--num_cores', required=False, help="Number of cores to use", default=4) @click.option('-rts', '--tile_size', required=False, help="Number of cores to use") @click.option('-rmg', '--requested_magnification', required=False, help="Number of cores to use") @click.option('-bx', '--batch_size', required=False, help="batch size used for inference speedup", default=64) @click.option('-m', '--method_param_path', required=False, help='path to a metadata json/yaml file with method parameters to reproduce results') def cli(**cli_kwargs): """Rasterize a slide into smaller tiles Tiles are saved in the whole-slide tiles binary format (tiles.pil), and the corresponding manifest/header file (tiles.csv) is also generated Neccessary data for the manifest file are: address, x_coord, y_coord, full_resolution_tile_size, tile_image_binary, tile_image_length, tile_image_size_xy, and tile_image_mode \b Inputs: input_slide_image: slide image (virtual slide formats compatible with openslide, .svs, .tif, .scn, ...) Outputs: slide_tiles \b Example: generate_tiles 10001.svs -nc 8 -rts 244 -rmg 10 -bx 200 -o 10001/tiles """ cli_runner( cli_kwargs, _params_, generate_tiles) import pandas as pd from tqdm import tqdm import openslide import itertools from pathlib import Path from concurrent.futures import ProcessPoolExecutor, as_completed from luna.pathology.common.utils import get_tile_bytes, get_scale_factor_at_magnfication, get_full_resolution_generator, coord_to_address from luna.common.utils import grouper def generate_tiles(input_slide_image, tile_size, requested_magnification, output_dir, num_cores, batch_size): """Rasterize a slide into smaller tiles Tiles are saved in the whole-slide tiles binary format (tiles.pil), and the corresponding manifest/header file (tiles.csv) is also generated Neccessary data for the manifest file are: address, x_coord, y_coord, full_resolution_tile_size, tile_image_binary, tile_image_length, tile_image_size_xy, and tile_image_mode Args: input_slide_image (str): path to slide image (virtual slide formats compatible with openslide, .svs, .tif, .scn, ...) tile_size (int): size of tiles to use (at the requested magnification) num_cores (int): Number of cores to use for CPU parallelization requested_magnification (float): Magnification scale at which to perform computation output_dir (str): output/working directory batch_size (int): size in batch dimension to chuck jobs Returns: dict: metadata about function call """ slide_name = Path(input_slide_image).stem slide = openslide.OpenSlide(str(input_slide_image)) logger.info("Slide size = [%s,%s]", slide.dimensions[0], slide.dimensions[1]) to_mag_scale_factor = get_scale_factor_at_magnfication (slide, requested_magnification=requested_magnification) if not to_mag_scale_factor % 1 == 0: raise ValueError("You chose a combination of requested tile sizes and magnification that resulted in non-integer tile sizes at different scales") full_resolution_tile_size = tile_size * to_mag_scale_factor logger.info("Normalized magnification scale factor for %sx is %s", requested_magnification, to_mag_scale_factor) logger.info("Requested tile size=%s, tile size at full magnficiation=%s", tile_size, full_resolution_tile_size) # get DeepZoomGenerator, level full_generator, full_level = get_full_resolution_generator(slide, tile_size=full_resolution_tile_size) tile_x_count, tile_y_count = full_generator.level_tiles[full_level] logger.info("tiles x %s, tiles y %s", tile_x_count, tile_y_count) # populate address, coordinates address_raster = [{ "address": coord_to_address(address, requested_magnification), "x_coord": (address[0]) * full_resolution_tile_size, "y_coord": (address[1]) * full_resolution_tile_size} for address in itertools.product(range(1, tile_x_count-1), range(1, tile_y_count-1))] logger.info("Number of tiles in raster: %s", len(address_raster)) df = pd.DataFrame(address_raster).set_index("address") output_binary_file = f"{output_dir}/{slide_name}.tiles.pil" output_header_file = f"{output_dir}/{slide_name}.tiles.csv" fp = open(output_binary_file, 'wb') offset = 0 counter = 0 logger.info(f"Now generating tiles with num_cores={num_cores} and batch_size={batch_size}!") address_offset = [] with ProcessPoolExecutor(num_cores) as executor: out = [executor.submit(get_tile_bytes, index, input_slide_image, full_resolution_tile_size, tile_size ) for index in grouper(df.index, batch_size)] for future in tqdm(as_completed(out), file=sys.stdout, total=len(out)): for index, tile in future.result(): fp.write( tile ) address_offset.append ((index, int(offset))) offset += len(tile) counter+=1 fp.close() df = df.join(pd.DataFrame(address_offset, columns=['address', 'tile_image_offset']).set_index('address')) df.loc[:, 'full_resolution_tile_size'] = full_resolution_tile_size df.loc[:, 'tile_image_binary'] = output_binary_file df.loc[:, 'tile_image_length'] = 3 * tile_size ** 2 df.loc[:, 'tile_image_size_xy'] = tile_size df.loc[:, 'tile_image_mode'] = 'RGB' logger.info (df) df.to_csv(output_header_file) properties = { "slide_tiles": output_header_file, "total_tiles": len(df), } return properties if __name__ == "__main__": cli()
nilq/baby-python
python
""" sudoku.py -- scrape common web sources for Sudokus """ import json from datetime import datetime from dataclasses import dataclass import requests from bs4 import BeautifulSoup sudokuexchange_head = "https://sudokuexchange.com/play/?s=" @dataclass class Puzzle: name: str source_url: str sudokuexchange_url: str def __repr__(self): # format as markdown return f"**{self.name}** ([source]({self.source_url})): [SudokuExchange link]({self.sudokuexchange_url})" def get_nytimes(): """Scrape all three NY Times puzzles""" nyt_url = "https://www.nytimes.com/puzzles/sudoku/easy" text = requests.get(nyt_url).text soup = BeautifulSoup(text, features="html.parser") # find the script that starts with `window.gameData =` # usually the first but who knows for script in soup.find_all("script", type="text/javascript"): if not script.contents: continue contents = script.contents[0] start_str = "window.gameData = " if contents.startswith(start_str): contents = contents.replace(start_str, "") puzzle_info = json.loads(contents) break # now we have puzzle_info as a dict with keys easy, medium, hard # and some levels of nesting; get the puzzle information and # create the SudokuExchange link puzzles = [] for difficulty in ("easy", "medium", "hard"): digits = puzzle_info[difficulty]["puzzle_data"]["puzzle"] digits_str = "".join(str(x) for x in digits) source_url = nyt_url.replace("easy", "difficulty") se_url = f"{sudokuexchange_head}{digits_str}" puzzles.append(Puzzle(f"NY Times {difficulty}", source_url, se_url)) return puzzles def get_dailysudoku(): """Get puzzle from dailysudoku.com""" year = datetime.now().year month = datetime.now().month day = datetime.now().day url = f"http://www.dailysudoku.com/cgi-bin/sudoku/get_board.pl?year={year}&month={month}&day={day}" data = requests.get( url, headers={ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:77.0) Gecko/20100101 Firefox/77.0" }, ).json() numbers = data["numbers"].replace(".", "0") return Puzzle("DailySudoku.com", url, f"{sudokuexchange_head}{numbers}") def get_tribune(): """Get puzzle from Tribune Content Agency""" # not sure how often this expires api_key = ("b366a2d09d81e980a1e3c3eac8ddbe524a3d9a79d88d6e4e92495f8a10e3246a",) today = datetime.now().strftime(r"%m/%d/%Y") form_data = { "apiKey": api_key, "productId": "sudoku", "publicationDate": today, "ldt": today, } headers = {"Accept": "application/json, text/javascript, */*; q=0.01"} data = requests.post( "https://puzzles.tribunecontentagency.com/puzzles/pzzResource/puzzle.do", data=form_data, headers=headers, ).json() # this just handles the structure of the JSON they return numbers = [] for cell in data["puzzleDetails"]["gCells"]: # check if cell was filled out or not if cell["qcell"]: numbers.append(cell["cellVal"]) else: numbers.append("0") cell_string = "".join(numbers) return Puzzle( "Chicago Tribune", "https://www.chicagotribune.com/entertainment/games/ct-sudoku-daily-htmlstory.html", f"{sudokuexchange_head}{cell_string}", ) def get_usatoday(): """Get the puzzle from USA Today""" today = datetime.now().strftime(r"%Y-%m-%d") # not sure how long this URL is valid url = f"https://gamedata.services.amuniversal.com/c/uupuz/l/U2FsdGVkX18CR3EauHsCV8JgqcLh1ptpjBeQ%2Bnjkzhu8zNO00WYK6b%2BaiZHnKcAD%0A9vwtmWJp2uHE9XU1bRw2gA%3D%3D/g/ussud/d/{today}/data.json" data = requests.get(url).json() # this just handles the structure of the JSON they return numbers = [] lines = [f"line{i}" for i in range(1, 10)] for key in lines: numbers.append(data["Layout"][key]) numbers_string = "".join(numbers).replace("-", "0") return Puzzle( "USA Today", "https://puzzles.usatoday.com/sudoku/", f"{sudokuexchange_head}{numbers_string}", ) if __name__ == "__main__": nytimes_puzzles = get_nytimes() for puzzle in nytimes_puzzles: print(puzzle) try: dailysudoku_puzzle = get_dailysudoku() print(dailysudoku_puzzle) except: print("DailySudoku.com: failed") try: tribune_puzzle = get_tribune() print(tribune_puzzle) except: print("Chicago Tribune: failed") try: usatoday_puzzle = get_usatoday() print(usatoday_puzzle) except: print("USA Today: failed")
nilq/baby-python
python
from .BaseWriter import TensorboardWriter from .visual import *
nilq/baby-python
python
from .chat import Chat from .livestream import Livestream from .message import Message from .tiny_models import * from .user import User
nilq/baby-python
python
import click import maldnsbl from collections import Counter import json import sys # Utlity Functions def iterate_report(report,sep=': '): """Converts an iterable into a string for output Will take a list or dicitonary and convert it to a string where each item in the iterable is joined by linebreaks (\\n) Args: report (iterable): the iterable (list or dict) that is to be converted sep (str): for dicts, the seperator echoed in between the keys and values Returns: str: A string that is the report joined by linebreaks (\\n) """ if type(report) is list: return '\n'.join(report) elif type(report) is dict: return '\n'.join(key+sep+str(value) for key,value in report.iteritems()) def false_report(report): """Converts a boolean report into a string for output Only used when the --boolean option is used. Converts the boolean report into a string that is every key in the boolean report that has a False value, joined by linebreaks (\\n) Arguments: report (list): the iterable (list or dict) that is to be converted Returns: str: A string that is the report joined by linebreaks (\\n) """ return '\n'.join(key for key in report.keys() if not report[key]) def true_report(report): """Converts a boolean report into a string for output Only used when the --boolean option is used. Converts the boolean report into a string that is every key in the boolean report that has a True value, joined by linebreaks (\\n) Arguments: report (list): the iterable (list or dict) that is to be converted Returns: str: A string that is the report joined by linebreaks (\\n) """ return '\n'.join(key for key in report.keys() if report[key]) @click.command() @click.option('--input-file', '-f', help='Input file with IOCs to search (Just IPs for now), if not provided, it will attempt to read from stdin',type=click.File('rb')) @click.option('--ip',help='Single IP to search') @click.option('--output_file','-o', help='Output File to write output to',type=click.File('wb')) @click.option('--config','-c', help='Configuration (yaml) File Location, if one is not provided, the config file packaged with maldnsbl will be used',type=click.Path(exists=True)) @click.option('--boolean','report_type', flag_value='boolean',help='Report Type: Checks Blacklists for ANY response from a blacklist and returns either true or false') @click.option('--count-blocklists', 'report_type',flag_value='count_blocklists',help='Report Type: Counts the number of blocklists that return matches for each IOC') @click.option('--count-tags','report_type',flag_value='count_tags',help='Report Type: Counts the number of tags returned by the blocklists for each IOC') @click.option('--list-tags','report_type',flag_value='list_tags',help='Report Type: Will list every tag returned for each IOC') @click.option('--json','format',flag_value='json',help='Format: the output will be in json format') @click.option('--true','format',flag_value='true',help='Format: the output will be only the IOCs that returned true in a boolean report (requires --boolean)') @click.option('--false','format',flag_value='false',help='Format: the output will be only the IOCs that returned false in a boolean report (required --boolean)') @click.option('--iterate','format',flag_value='iterate',help='Format: the output will be the report line for line rather than as a pyhton object') @click.option('--csv','format',flag_value='csv',help='Format: the output will be comma seperated values') @click.option('--fraction',is_flag=True,default=False,help ='Change the format of blocklist counts to fractions of the total (requires --count-blocklists)') @click.option('--quiet','-q',count=True,help='-q will not echo results, -qq turns off progress bar but will echo the results, -qqq will echo neither (so you would need an ouput file specified') @click.option('--debug','-d',is_flag=True,default=False,help='Turn debugging on, will break the progress bar') def main(config,input_file,report_type,format,debug,fraction,quiet,output_file,ip): """Uses DNSBL to lookup reputation on IOCs""" if not input_file and not ip: input_file = [line for line in sys.stdin] if ip: input_file = [ip] if not config: config = sys.prefix + '/maldnsbl_config/maldnsbl.yaml' mdbl = maldnsbl.maldnsbl(config) if debug: mdbl.debug = True if fraction: mdbl.option_fraction = True if quiet >= 2: mdbl.quiet = True else: mdbl.quiet = False iocs = [line.strip() for line in input_file] #run the correct report type report = getattr(mdbl,report_type)(iocs) if format == 'json': output = json.dumps(report) elif format == 'true': output = true_report(report) elif format == 'false': output = false_report(report) elif format == 'iterate': output = iterate_report(report,': ') elif format == 'csv': output = iterate_report(report,',') else: output = report if output_file: output_file.write(output) if quiet == 0 or quiet ==2: click.echo(output) if __name__ == '__main__': main()
nilq/baby-python
python
from rest_framework.reverse import reverse_lazy def get_detail_url(obj, url_name, request): url_kwargs = { 'pk': obj.id, } return reverse_lazy(url_name, kwargs=url_kwargs, request=request) # def get_base_fields(): # return [ # 'unique_id', # 'integration_code' # ] # def get_three_base_fields(): # return [ # 'unique_id', # 'history', # 'integration_code' # ] def get_base_fields(): return [ 'unique_id', 'status', 'history', 'version', 'integration_code', 'code', 'slug', ]
nilq/baby-python
python
from datetime import date from email import message from vigilancia.order_screenshot import Orders from django.db.models.fields import DateField from django.http import Http404 from django.http import HttpResponse from django.template import loader from django.shortcuts import get_object_or_404, render from .models import Camera, Trap from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from .serializers import AlertSerializer, CameraOrderSerializer, CameraSerializer, MediaSerializer, TrapSerializer from rest_framework.viewsets import ViewSet from rest_framework.response import Response from .serializers import UploadSerializer from ftplib import FTP import json from vigilancia import serializers import vigilancia.services.send_email import vigilancia.services.camera_service import logging from datetime import datetime import os logger = logging.getLogger("django") @csrf_exempt def test(request): print(request) return JsonResponse({message: "test"}, status=201) @csrf_exempt def report_alert(request): if request.method == 'POST': data = JSONParser().parse(request) print(data) logger.info("Alerta detectada. Detalles: Armadilha %s, Detectado %s.", str(data['trap']), data['detected_at']) serializer = AlertSerializer(data=data) if serializer.is_valid(): serializer.save() message = 'Oi, a armadilha ' + str(data['trap']) + ' notificou movimento as ' + data['detected_at'] print(message) vigilancia.services.send_email.send_gmail_test(str(data['trap']) ) return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @csrf_exempt def camera_order(request): data = JSONParser().parse(request) serializer = CameraOrderSerializer(data=data) response = 'OK' orders_object = Orders() if serializer.is_valid(): response = serializer.data response = Orders().take_screeshot() return JsonResponse(response, safe=False) @csrf_exempt def trap_general(request): """ (GET) List all traps (POST) Create one trap """ if request.method == 'GET': allObjects = Trap.objects.all() serializer = TrapSerializer(allObjects, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = TrapSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @csrf_exempt def trap_specific(request, pk): """ (GET) Obtain the detail of one specific trap asdadas """ data = JSONParser().parse(request) serializer = CameraSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @csrf_exempt def movement_detected(request): """ (POST) Register movement detected in a trap """ try: body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) print(request) # trap = Trap.objects.get(pk=trap_pk) except Trap.DoesNotExist: return HttpResponse(status=404) # trap = Trap() # trap.last_detected_movement_date = date() # Trap.objects.update(trap) return JsonResponse({'request': body}, status=201) data = JSONParser().parse(request) serializer = TrapSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @csrf_exempt def camera_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': cameras = Camera.objects.all() serializer = CameraSerializer(cameras, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = CameraSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @csrf_exempt def take_photo(request, pk): try: camera = Camera.objects.get(pk=pk) except Camera.DoesNotExist: return HttpResponse(status=404) if request.method == 'POST': base_folder = os.path.dirname(__file__) image_path = os.path.join(base_folder, 'test.jpg') print('IMAGE PATH', image_path) file = open(image_path, 'rb') file_name = 'TRAP' + str(pk) + '-' + str(datetime.now().strftime("%Y%m%d-%H%M%S")) + '.jpg' #serializer = MediaSerializer(data={"trap": 1, "date": "2021-06-25T01:55:19"}) #if serializer.is_valid(): # serializer.save() print(file.__dict__, file_name) vigilancia.services.camera_service.CameraService().upload_photo(file, file_name) return JsonResponse({"file_name": file_name}) @csrf_exempt def camera_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: camera = Camera.objects.get(pk=pk) except Camera.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = CameraSerializer(camera) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = CameraSerializer(camera, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': camera.delete() return HttpResponse(status=204) @csrf_exempt def upload_photo(request): try: file_uploaded = request.FILES.get('file_uploaded') content_type = file_uploaded.content_type response = "POST API and you have uploaded a {} file".format(content_type) + " called {}".format(file_uploaded) response = "dir {}, dict {}, content_type {}".format(dir(file_uploaded), file_uploaded.__dict__, file_uploaded.content_type) session = FTP(host='maonamata.com.br', user='mnmdev@maonamata.com.br', passwd='mnmDev2021') # response = session.pwd() session.storbinary('STOR ' + file_uploaded._name, file_uploaded.file) #session.cwd('./../../public_html/pipe1/trapassets/trap1test/') session.quit() return HttpResponse(response) except Camera.DoesNotExist: return HttpResponse(status=404) @csrf_exempt def send_email(request): vigilancia.services.send_email.send_gmail_test(['darlinnep@gmail.com'], 'texto test') return HttpResponse('OK') class UploadViewSet(ViewSet): serializer_class = UploadSerializer def list(self, request): return Response("GET API") def create(self, request): file_uploaded = request.FILES.get('file_uploaded') content_type = file_uploaded.content_type response = "POST API and you have uploaded a {} file".format(content_type) return Response(response) #def index(request): # list = Camera.objects.order_by('-id')[:5] # context = {'list': list} # return render(request, 'cameras/index.html', context) #def detail(request, camera_id): # camera = get_object_or_404(Camera, pk=camera_id) # return render(request, 'cameras/detail.html', {'camera': camera})
nilq/baby-python
python
import os import sys sys.path.insert(1, os.path.join(sys.path[0], '..')) from .utils import * from .addons import * import qcdb _ref_h2o_pk_rhf = -76.02696997325441 _ref_ch2_pk_uhf = -38.925088643363665 _ref_ch2_pk_rohf = -38.91973113928147 @using_psi4 def test_tu1_rhf_a(): """tu1-h2o-energy/input.dat global testing """ h2o = qcdb.set_molecule(""" O H 1 1.8 H 1 1.8 2 104.5 units au """) print(h2o) print(qcdb.get_active_options().print_changed()) qcdb.set_options({'basis': 'cc-pVDZ', 'scf_type': 'pk', 'memory': '600 mb'}) qcdb.energy('p4-hf') print(qcdb.print_variables()) assert compare_values(_ref_h2o_pk_rhf, qcdb.get_variable('HF TOTAL ENERGY'), 6, sys._getframe().f_code.co_name) @using_psi4 def test_tu1_rhf_b(): """tu1-h2o-energy/input.dat local testing """ # memory 600 mb h2o = qcdb.Molecule(""" O H 1 1.8 H 1 1.8 2 104.5 units au """) qcdb.set_options({'scf_type': 'pk',}) E, jrec = qcdb.energy('p4-hf/cc-pVDZ', molecule=h2o, return_wfn=True) print(qcdb.print_variables(jrec['qcvars'])) assert compare_values(_ref_h2o_pk_rhf, jrec['qcvars']['HF TOTAL ENERGY'].data, 6, sys._getframe().f_code.co_name) @using_psi4 def test_tu2_uhf(): """tu2-ch2-energy/input.dat #! Sample UHF/6-31G** CH2 computation """ ch2 = qcdb.set_molecule(""" 0 3 C H 1 R H 1 R 2 A R = 2.05 A = 133.93 units au """) qcdb.set_options({'basis': '6-31G**', 'reference': ' uhf', 'puream': 'cart', #'psi_scf_type': 'pk'}) 'scf_type': 'pk'}) E, jrec = qcdb.energy ('p4-hf', return_wfn=True) print(qcdb.print_variables()) assert compare_values(_ref_ch2_pk_uhf, qcdb.get_variable('hf total energy'), 6, sys._getframe().f_code.co_name) @using_psi4 def test_tu2_rohf(): """tu2-ch2-energy/input.dat #! Sample ROHF/6-31G** CH2 computation """ ch2 = qcdb.set_molecule(""" 0 3 C H 1 R H 1 R 2 A R = 2.05 A = 133.93 units au """) qcdb.set_options({'basis': '6-31G**', 'reference': ' rohf', 'puream': 'cart', #'psi_scf_type': 'pk'}) 'scf_type': 'pk'}) E, jrec = qcdb.energy ('p4-hf', return_wfn=True) print(qcdb.print_variables()) assert compare_values(_ref_ch2_pk_rohf, qcdb.get_variable('hf total energy'), 6, sys._getframe().f_code.co_name) assert compare_values(_ref_ch2_pk_rohf, qcdb.get_variable('current energy'), 6, sys._getframe().f_code.co_name) assert compare_values(_ref_ch2_pk_rohf, E, 6, sys._getframe().f_code.co_name) #@using_psi4 #def test_tu2_sowreap(): # """tu2-ch2-energy/input.dat # #! Sample UHF/6-31G** CH2 computation # # """ # ans2 = -38.9253416082900827 # # # ch2 = qcdb.set_molecule(""" # 0 3 # C # H 1 R # H 1 R 2 A # # R = 1.075 # A = 133.93 #""") # # qcdb.set_options({'basis': '6-31G**', # 'reference': ' uhf', # 'puream': 'cart', # #'psi_scf_type': 'pk'}) # 'scf_type': 'pk'}) # # E, jrec = qcdb.energy ('p4-scf', return_wfn=True, probe=True) # print(qcdb.print_variables()) # # assert compare_values(ans2, qcdb.get_variable('scf total energy'), 6, sys._getframe().f_code.co_name) @using_psi4 def test_tu2_uhf_yaml(): yamlin = """ molecule: | 0 3 C H 1 R H 1 R 2 A R = 1.075 A = 133.93 driver: !!python/name:qcdb.energy method: p4-hf options: memory: 1gb basis: '6-31g**' reference: uhf puream: cart scf_type: pk """ import yaml asdf = yaml.load(yamlin) ene = asdf['driver'](asdf['method'], options=asdf['options'], molecule=qcdb.Molecule(asdf['molecule'])) assert compare_values(-38.9253416082900827, ene, 6, 'calc from yaml str') if __name__ == '__main__': test_tu1a() #test_tu1b() #test_tu2()
nilq/baby-python
python
from .naive_bayes import NaiveBayes
nilq/baby-python
python
import os import codecs import sqlite3 import re from flask import Flask, render_template, abort, request, Response, g, jsonify, redirect, url_for app = Flask(__name__) if os.getenv('FLASK_ENV', 'production') == 'production': debug = False else: debug = True app.config.update( DATADIR='pages', IMGDIR='static/images', DEBUG=debug ) IDX = 'idx.db' def striphtml(data): p = re.compile(r'<.*?>') return p.sub('', data) def get_db(): db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(IDX) return db @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if db is not None: db.close() def get_filename(page): return os.path.join(app.config['DATADIR'], page + '.html') def build_index(): with app.app_context(): cursor = get_db().execute( 'CREATE TABLE IF NOT EXISTS idx (page text CONSTRAINT utext UNIQUE ON CONFLICT REPLACE, content text)') def add_index(page): with codecs.open(get_filename(page), 'r', 'utf-8') as file: content = striphtml(file.read()) cursor.execute( 'INSERT OR REPLACE INTO idx VALUES (?, ?)', (page, content)) [add_index(page) for page in get_pages()] def update_index(page): with app.app_context(): cursor = get_db().cursor() with codecs.open(get_filename(page), 'r', 'utf-8') as file: content = striphtml(file.read()) cursor.execute( 'UPDATE idx SET content = ? WHERE page = ?', (content, page)) def remove_index(page): with app.app_context(): cursor = get_db().execute('DELETE FROM idx where page = ?', (page,)) def get_pages(): return [file[:-5] for file in sorted(os.listdir(app.config['DATADIR'])) if file.endswith('.html')] @ app.route('/', methods=['GET']) def index(): return redirect(url_for('show_page', page='Index')) @ app.route('/<page>', methods=['GET']) def show_page(page): try: content = codecs.open(get_filename(page), 'r', 'utf-8').read() except IOError: content = None return render_template('page.html', title=page, content=content, pages=get_pages()) @ app.route('/<page>', methods=['POST']) def create_page(page): file = get_filename(page) if os.path.exists(file): response = Response(status=403) response.headers['Allow'] = 'GET, PUT, DELETE, HEAD' else: with codecs.open(file, 'w', 'utf-8') as newpage: newpage.write(request.form['content'].strip()) response = Response('201 Created', status=201) response.headers['Content-Type'] = 'text/plain; charset=utf-8' response.headers['Location'] = '/' + page build_index() return response @ app.route('/<page>', methods=['PUT']) def update_page(page): file = get_filename(page) if not os.path.exists(file): abort(404) with codecs.open(file, 'w', 'utf-8') as newpage: newpage.write(request.form.get('content', '').strip()) update_index(page) return Response(status=204) @ app.route('/<page>', methods=['DELETE']) def delete_page(page): file = get_filename(page) if not os.path.exists(file): abort(404) trashdir = os.path.join(app.config['DATADIR'], '.deleted') if not os.path.exists(trashdir): os.mkdir(trashdir) os.rename(file, os.path.join( app.config['DATADIR'], '.deleted', page + '.html')) remove_index(page) return Response(status=204) @ app.route('/search/<query>', methods=['GET']) def search(query): cursor = get_db().cursor() qs = '%{}%'.format(query) pages = [row[0] for row in cursor.execute( """SELECT page FROM idx WHERE page LIKE ? OR content LIKE ?""", (qs, qs,))] return jsonify(pages=pages) @ app.route('/files', methods=['GET']) def list_files(): pages = get_pages() return jsonify(pages=pages) @app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] file.save(os.path.join(app.config['IMGDIR'], file.filename)) return Response(status=204) def create_default_page(): with codecs.open(os.path.join(app.config['DATADIR'], 'Index.html'), 'w', 'utf-8') as index: index.write("""\ <p>This is a placeholder page for your wiki. Click anywhere in the text to edit.</p> <p>This wiki <strong>does not use versioning (yet).</strong> Please use Dropbox, Time Machine or any other versioning/backup solution for valuable data.</p> <p>You can find the latest version at <a href="https://github.com/nandordevai/python-wiki">https://github.com/nandordevai/python-wiki</a>.</p> """) if __name__ == '__main__': if not get_pages(): create_default_page() build_index() app.run(host='localhost')
nilq/baby-python
python
import matplotlib.pyplot as plt plt.plot() plt.show()
nilq/baby-python
python
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import fnmatch import os import re import sys from setuptools import find_packages, setup, Command from setuptools.command.install import install as InstallCommandBase from setuptools.dist import Distribution _VERSION = '0.11.0' REQUIRED_PACKAGES = [ 'numpy >= 1.11.0', 'six >= 1.10.0', 'protobuf == 3.1.0', ] # python3 requires wheel 0.26 if sys.version_info.major == 3: REQUIRED_PACKAGES.append('wheel >= 0.26') else: REQUIRED_PACKAGES.append('wheel') # mock comes with unittest.mock for python3, need to install for python2 REQUIRED_PACKAGES.append('mock >= 2.0.0') # pylint: disable=line-too-long CONSOLE_SCRIPTS = [ 'tensorboard = tensorflow.tensorboard.tensorboard:main', ] # pylint: enable=line-too-long TEST_PACKAGES = [ 'scipy >= 0.15.1', ] class BinaryDistribution(Distribution): def has_ext_modules(self): return True class InstallCommand(InstallCommandBase): """Override the dir where the headers go.""" def finalize_options(self): ret = InstallCommandBase.finalize_options(self) self.install_headers = os.path.join(self.install_purelib, 'tensorflow', 'include') return ret class InstallHeaders(Command): """Override how headers are copied. The install_headers that comes with setuptools copies all files to the same directory. But we need the files to be in a specific directory hierarchy for -I <include_dir> to work correctly. """ description = 'install C/C++ header files' user_options = [('install-dir=', 'd', 'directory to install header files to'), ('force', 'f', 'force installation (overwrite existing files)'), ] boolean_options = ['force'] def initialize_options(self): self.install_dir = None self.force = 0 self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_headers', 'install_dir'), ('force', 'force')) def mkdir_and_copy_file(self, header): install_dir = os.path.join(self.install_dir, os.path.dirname(header)) # Get rid of some extra intervening directories so we can have fewer # directories for -I install_dir = re.sub('/google/protobuf/src', '', install_dir) # Copy eigen code into tensorflow/include. # A symlink would do, but the wheel file that gets created ignores # symlink within the directory hierarchy. # NOTE(keveman): Figure out how to customize bdist_wheel package so # we can do the symlink. if 'external/eigen_archive/' in install_dir: extra_dir = install_dir.replace('external/eigen_archive', '') if not os.path.exists(extra_dir): self.mkpath(extra_dir) self.copy_file(header, extra_dir) if not os.path.exists(install_dir): self.mkpath(install_dir) return self.copy_file(header, install_dir) def run(self): hdrs = self.distribution.headers if not hdrs: return self.mkpath(self.install_dir) for header in hdrs: (out, _) = self.mkdir_and_copy_file(header) self.outfiles.append(out) def get_inputs(self): return self.distribution.headers or [] def get_outputs(self): return self.outfiles def find_files(pattern, root): """Return all the files matching pattern below root dir.""" for path, _, files in os.walk(root): for filename in fnmatch.filter(files, pattern): yield os.path.join(path, filename) matches = ['../' + x for x in find_files('*', 'external') if '.py' not in x] if os.name == 'nt': EXTENSION_NAME = 'python/_pywrap_tensorflow.pyd' else: EXTENSION_NAME = 'python/_pywrap_tensorflow.so' headers = (list(find_files('*.h', 'tensorflow/core')) + list(find_files('*.h', 'google/protobuf/src')) + list(find_files('*', 'third_party/eigen3')) + list(find_files('*', 'external/eigen_archive'))) setup( name='tensorflow', version=_VERSION, description='TensorFlow helps the tensors flow', long_description='', url='http://tensorflow.org/', author='Google Inc.', author_email='opensource@google.com', # Contained modules and scripts. packages=find_packages(), entry_points={ 'console_scripts': CONSOLE_SCRIPTS, }, headers=headers, install_requires=REQUIRED_PACKAGES, tests_require=REQUIRED_PACKAGES + TEST_PACKAGES, # Add in any packaged data. include_package_data=True, package_data={ 'tensorflow': [EXTENSION_NAME, 'tensorboard/dist/bazel-html-imports.html', 'tensorboard/dist/index.html', 'tensorboard/dist/tf-tensorboard.html', 'tensorboard/lib/css/global.css', 'tensorboard/TAG', ] + matches, }, zip_safe=False, distclass=BinaryDistribution, cmdclass={ 'install_headers': InstallHeaders, 'install': InstallCommand, }, # PyPI package information. classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Libraries', ], license='Apache 2.0', keywords='tensorflow tensor machine learning', )
nilq/baby-python
python
#!flask/bin/python from farm import app if __name__ == "__main__": app.run(host='0.0.0.0', port=8001, debug=True)
nilq/baby-python
python
import datetime def prev_month_range(when = None): """Return (previous month's start date, previous month's end date).""" if not when: # Default to today. when = datetime.datetime.today() # Find previous month: http://stackoverflow.com/a/9725093/564514 # Find today. first = datetime.date(day=1, month=when.month, year=when.year) # Use that to find the first day of this month. prev_month_end = first - datetime.timedelta(days=1) prev_month_start = datetime.date(day=1, month= prev_month_end.month, year= prev_month_end.year) # Return previous month's start and end dates in YY-MM-DD format. return {'start': prev_month_start, 'end':prev_month_end} def prev_year_range(when = None): """Returns the previous year range from Jan 1 to Dec 31""" if not when: # Default to today. when = datetime.datetime.today() # Find today. prev_year = when.year - 1 # Use that to find the first day of this month. first_day_year = datetime.date(day=1, month=1, year=prev_year) last_day_year = datetime.date(day=31, month=12, year=prev_year) # Return previous month's start and end dates in YY-MM-DD format. return {'start': first_day_year, 'end': last_day_year} def last_30_days(): return datetime.datetime.today() + datetime.timedelta(-30)
nilq/baby-python
python
''' example code to join dataframes merge_by_FIPS doesn't need to be it's own file; it's just calling .join on two data frames ''' from deaths import death_sample from vaccines import vaccine_sample def merge_by_FIPS(desired_date): # get dataframes with FIPS as indices deaths_df = death_sample(desired_date) vaccines_df = vaccine_sample(desired_date) # how=inner specifies that only the intersection of each dataframe will be used. merged = deaths_df.join(vaccines_df, how='inner') return merged # main function is for testing only def main(): print(merge_by_FIPS('11-30-2021')) if __name__=='__main__': main()
nilq/baby-python
python
# Generated by Django 3.1.2 on 2020-11-10 14:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('userauth', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='userprofile', name='fccProfileUrl', ), migrations.RemoveField( model_name='userprofile', name='gender', ), ]
nilq/baby-python
python
import json import time, os import requests from datetime import datetime from PIL import Image from PIL.ExifTags import TAGS def download_img(url, basepath, filename): with open(f'{basepath}/{filename}.jpg', "wb") as file: res = requests.get(url) file.write(res.content) def download_movie(url, basepath, filename): with open(f'{basepath}/{filename}.mp4', "wb") as file: res = requests.get(url) file.write(res.content) def parse_datetime(report_date): short_date = report_date[:report_date.rfind(' ')] try: time_t = datetime.strptime(short_date, '%Y년 %m월 %d일') str_time = time_t.strftime('%Y_%m_%d') except: str_time = f'{short_date.split(".")[0]}_{int(short_date.split(".")[1]):02d}_{int(short_date.split(".")[2]):02d}' #print(str_time) # 2021_08_24 return str_time def get_exif_time(basepath, filename): img = Image.open(f'{basepath}/{filename}.jpg') info = img.getexif() # for tag, value in info.items(): # decoded_tag = TAGS.get(tag) # print(f'{decoded_tag} : {value}') # pass try: #print(f'{TAGS[306]} : {info[306]}') return info[306] except: #print('No Datetime at EXIF') return '' def update_file_time(basepath:str, filename:str, article_date:str): exif_time = get_exif_time(basepath, filename) tm = 0 if exif_time == '': # use article_date tm = time.mktime(datetime(*([int(x) for x in article_date.split('_')] + [12,0,0])).timetuple()) pass else: tm = time.mktime(datetime(*[int(x) for x in exif_time.replace(' ', ':').split(':')]).timetuple()) os.utime(f'{basepath}/{filename}.jpg', (tm, tm)) def update_file_time_movie(basepath:str, filename:str, article_date:str): tm = time.mktime(datetime(*([int(x) for x in article_date.split('_')] + [12,0,0])).timetuple()) os.utime(f'{basepath}/{filename}.mp4', (tm, tm)) def write_message(message, basepath, filename): with open(f'{basepath}/{filename}.json', "w", encoding='utf8') as file: only_msg = dict(message) del only_msg['images'] if 'movie' in only_msg: del only_msg['movie'] #print(only_msg) json.dump(only_msg, file, ensure_ascii=False) #file.write(only_msg) def make_filename(type, date, idx): #print(f'date[{date}] idx[{idx}]') # YYYY_MM_DD_idx.jpg return f'{type}_{date}_{idx:03d}'
nilq/baby-python
python
#! /usr/bin/env python from datetime import datetime import hb_config # import MySQLdb import pymysql.cursors import pymysql.converters as conv # import pymysql.constants as const from pymysql.constants import FIELD_TYPE import hb_output_settings as output_settings import hb_queries import hb_templates as templates import requests from requests_oauthlib import OAuth1 #TODO: add in logging again, more try statements #hb_config to config #get DB class out of profiles.py, rename def connect_to_db(hostname, dbname, defaultfile): conn = pymysql.connect( host = hostname, db = dbname, read_default_file = defaultfile, use_unicode = 1, charset="utf8", ) return conn def select_query(conn, qstring, convert_bytestrings = False): cursor = conn.cursor() cursor.execute(qstring) if convert_bytestrings: result = convert_bytes_in_results_tuple(cursor.fetchall()) else: result = list(cursor.fetchall()) return result def commit_query(conn, qstring): cursor = conn.cursor() cursor.execute(qstring) conn.commit() def insert_multiple_rows_query(conn, qstring, list_of_rows): cursor = conn.cursor() for row in rows: x = tuple(row) # qstring.format(*x) cursor.execute(qstring.format(*x)) # cursor.executemany(qstring, list_of_tuples) conn.commit() def convert_bytes_in_results_tuple(results_tuple): """ Convert the varbinaries to unicode strings, and return a list of lists. """ return [[x.decode() if type(x) == bytes else x for x in row] for row in results_tuple] if __name__ == "__main__": conn1 = connect_to_db('tools.db.svc.eqiad.wmflabs', 's51322__hostbot','/home/jmorgan/replica.my.cnf') ## VALIDATED - SELECT FROM THE TEAHOUSE INVITE DATABASE # query1 = "select * from th_up_invitees_current where sample_date = '2017-09-14 20:00:40' and sample_group = 'invalid' and user_editcount > 48;" # rows = select_query(conn1, query1, convert_bytestrings = True) # print(rows) ## VALIDATED - COMMIT TO THE TEAHOUSE INVITE DATABASE FROM ANOTHER DATABASE ON THE SAME HOST # query2 = "insert ignore into th_invite_test select * from th_up_invitees_current where sample_date = '2017-09-14 20:00:40' and sample_group = 'invalid' and user_editcount > 48;" # commit_query(conn1, query2) ## VALIDATED - CONNECT TO A DIFFERENT HOST # conn2 = connect_to_db('enwiki.labsdb', 'enwiki_p','/home/jmorgan/replica.my.cnf') # query3 = """SELECT user_id, user_name, user_registration, user_editcount, NOW(), 4 # FROM enwiki_p.user # WHERE user_registration > DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 2 DAY),'%Y%m%d%H%i%s') # AND user_editcount >=5 limit 2""" # # rows = select_query(conn2, query3) # print(rows) ## VALIDATED - SELECT FROM ENWIKI AND COMMIT TO HOSTBOT INVITE TABLE conn2 = connect_to_db('enwiki.labsdb', 'enwiki_p','/home/jmorgan/replica.my.cnf') query3 = """SELECT user_id, user_name, user_registration, user_editcount, NOW(), 4 FROM enwiki_p.user WHERE user_registration > DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 2 DAY),'%Y%m%d%H%i%s') AND user_editcount >=5 limit 2""" rows = select_query(conn2, query3, convert_bytestrings = True) for row in rows: row[4] = '{:%Y-%m-%d %H:%M:%S}'.format(row[4]) print(rows) query4 = "INSERT ignore INTO th_invite_test(user_id, user_name, user_registration, user_editcount, sample_date, sample_type) VALUES({}, '{}', '{}', {}, '{}', {})" insert_multiple_rows_query(conn1, query4, rows) # def insertInvitees(self, query_key): # """ # Insert today's potential invitees into the database # """ # query = self.queries.getQuery(query_key) # self.cursor.execute(query) # self.conn.commit() # # def updateTalkPages(self, query_key): # """ # Updates the database with user talkpage ids (if they have one) # """ # query = self.queries.getQuery(query_key) # self.cursor.execute(query) # self.conn.commit() # # def selectSample(self, query_key, sub_sample=False): # """ # Returns a list of usernames and ids of candidates for invitation # """ # sample_query = self.queries.getQuery(query_key) # self.cursor.execute(sample_query) # rows = self.cursor.fetchall() # sample_set = [[row[0],row[1], row[2]] for row in rows] # if sub_sample: # sample_set = sample_set[:5] # return sample_set # # def updateOneRow(self, query_key, qvars): # """ # Updates the database: was the user invited, or skipped? # """ # # try: # query = self.queries.getQuery(query_key, qvars) # self.cursor.execute(query) # self.conn.commit() # # except: # # print "something went wrong with this one"
nilq/baby-python
python
from accuracy2 import MyClassifier1 ob=MyClassifier1() print(ob.predict())
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Source: https://github.com/simplegadget512/Truecolor # MIT License # Copyright (c) 2017 Albert Freeman # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os if os.getenv('COLORTERM') is None: raise RuntimeError('Not a truecolor terminal - use termcolor module instead') PALETTE = { 'white': (127, 127, 127), 'grey': (64, 64, 64), 'black': (0, 0, 0), 'red': (127, 0, 0), 'green': (0, 127, 0), 'blue': (0, 0, 127), 'yellow': (127, 127, 0), 'brown': (127, 64, 0), 'purple': (32, 0, 127) } Z_FORE = 38 Z_BACK = 48 def _e(red_component, green_component, blue_component, z_level=Z_FORE): """Return escaped color sequence""" return '\x01\x1b[{};2;{};{};{}m\x02'.format( z_level, red_component, green_component, blue_component) def _f(red_component, green_component, blue_component): """Return escaped foreground color sequence""" return _e(red_component, green_component, blue_component, Z_FORE) def _b(red_component, green_component, blue_component): """Return escaped background color sequence""" return _e(red_component, green_component, blue_component, Z_BACK) def _r(): """Return reset sequence""" return '\x01\x1b[0m\x02' def _gamut(component): """keeps color components in the proper range""" return min(max(int(component), 0), 254) def bold(color): """Return a bolder version of a color tuple.""" return tuple(_gamut(i * 2) for i in color) def dim(color): """Return a dimmer version of a color tuple.""" return tuple(_gamut(i // 2) for i in color) def hex_to_rgb(hex_string): """Return a tuple of red, green and blue components for the color given as #rrggbb. """ return tuple(int(hex_string[i:i + 2], 16) for i in range(1, len(hex_string), 2)) def rgb_to_hex(red_component=None, green_component=None, blue_component=None): """Return color as #rrggbb for the given color tuple or component values. Can be called as TUPLE VERSION: rgb_to_hex(COLORS['white']) or rgb_to_hex((128, 63, 96)) COMPONENT VERSION rgb_to_hex(64, 183, 22) """ if isinstance(red_component, tuple): red_component, green_component, blue_component = red_component return '#{:02X}{:02X}{:02X}'.format( red_component, green_component, blue_component) def fore_text(txt, foreground=PALETTE['white']): """Return text string with foreground only set.""" if isinstance(foreground, str) and foreground.startswith('#'): foreground = hex_to_rgb(foreground) return '{}{}{}'.format(_f(*foreground), txt, _r()) def color_text(txt, foreground=PALETTE['white'], background=PALETTE['black']): """Return text string with foreground and background set.""" if isinstance(foreground, str) and foreground.startswith('#'): foreground = hex_to_rgb(foreground) if isinstance(background, str) and background.startswith('#'): background = hex_to_rgb(background) return '{}{}{}{}'.format(_f(*foreground), _b(*background), txt, _r()) def fore_print(txt, foreground=PALETTE['white']): """Print text string with foreground only set.""" print(fore_text(txt, foreground)) def color_print(txt, foreground=PALETTE['white'], background=PALETTE['black']): """Print text string with foreground and background set.""" print(color_text(txt, foreground, background)) if __name__ == "__main__": for color_name in PALETTE: color_print( '{} :: {} :: bright {} on dim {}'.format( rgb_to_hex(bold(PALETTE[color_name])), rgb_to_hex(dim(PALETTE[color_name])), color_name, color_name ).ljust(64, ' '), bold(PALETTE[color_name]), dim(PALETTE[color_name]) )
nilq/baby-python
python
import os from charge.repository import Repository if __name__ == '__main__': test_data_dir = os.path.realpath( os.path.join(__file__, '..', 'cross_validation_data')) out_file = 'cross_validation_repository.zip' repo = Repository.create_from(test_data_dir, min_shell=0, max_shell=3, traceable=True) repo.write(out_file)
nilq/baby-python
python
import unittest from typing import List import utils # https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 def round_up_to_power_of_2(v): v -= 1 v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v |= v >> 16 return v + 1 # O(n) space. Segment tree array. class NumArray: # O(n) time. O(1) space. def __init__(self, nums: List[int]): num_leaves = round_up_to_power_of_2(len(nums)) leaf_start = num_leaves - 1 tree = [0] * (leaf_start + num_leaves) for i, val in enumerate(nums): tree[leaf_start + i] = val for x in range(leaf_start - 1, -1, -1): tree[x] = tree[x * 2 + 1] + tree[x * 2 + 2] self.nums = nums self.num_leaves = num_leaves self.tree = tree # O(log(n)) time. O(1) space. def update(self, i: int, val: int) -> None: tree = self.tree delta = val - self.nums[i] self.nums[i] = val x = 0 lo = 0 hi = self.num_leaves - 1 while x < len(tree): tree[x] += delta mid = lo + (hi - lo) // 2 if i <= mid: x = x * 2 + 1 hi = mid else: x = x * 2 + 2 lo = mid # O(log(n)) time. O(log(n)) space. def sumRange(self, i: int, j: int) -> int: tree = self.tree def dfs(x, lo, hi): if i <= lo and hi <= j: return tree[x] s = 0 mid = lo + (hi - lo) // 2 if i <= mid: s += dfs(x * 2 + 1, lo, mid) if mid < j: s += dfs(x * 2 + 2, mid + 1, hi) return s return dfs(0, 0, self.num_leaves - 1) class Test(unittest.TestCase): def test(self): cls = NumArray cases = utils.load_test_json(__file__).test_cases for case in cases: args = str(case.args) obj = None for func, parameters, expected in zip(case.functions, case.args, case.expected): if func == cls.__name__: obj = cls(*parameters) else: actual = getattr(obj, func)(*parameters) self.assertEqual(expected, actual, msg=args) if __name__ == '__main__': unittest.main()
nilq/baby-python
python
# Generated by Django 3.0.8 on 2020-08-12 16:14 from django.db import migrations, models import utils.delete.managers import utils.postgres.managers class Migration(migrations.Migration): dependencies = [ ('definitions', '0008_auto_20200810_0520'), ] operations = [ migrations.AlterModelManagers( name='column', managers=[ ('objects', utils.delete.managers.SoftDeletionManager()), ('all_objects', utils.delete.managers.SoftDeletionManager(alive_only=False)), ], ), migrations.AlterModelManagers( name='datastore', managers=[ ('objects', utils.postgres.managers.PostgresManager()), ], ), migrations.AlterModelManagers( name='index', managers=[ ('objects', utils.postgres.managers.PostgresManager()), ], ), migrations.AlterModelManagers( name='schema', managers=[ ('objects', utils.delete.managers.SoftDeletionManager()), ('all_objects', utils.delete.managers.SoftDeletionManager(alive_only=False)), ], ), migrations.AlterModelManagers( name='table', managers=[ ('objects', utils.delete.managers.SoftDeletionManager()), ('all_objects', utils.delete.managers.SoftDeletionManager(alive_only=False)), ], ), migrations.AlterField( model_name='column', name='comment', field=models.TextField(blank=True, null=True), ), migrations.AlterField( model_name='column', name='short_desc', field=models.CharField(blank=True, max_length=50, null=True), ), migrations.AlterField( model_name='datastore', name='short_desc', field=models.CharField(blank=True, max_length=140, null=True), ), migrations.AlterField( model_name='table', name='short_desc', field=models.CharField(blank=True, max_length=140, null=True), ), ]
nilq/baby-python
python
from typing import Any, Optional from baserow.core.models import Application, TrashEntry, Group from baserow.core.registries import application_type_registry from baserow.core.signals import application_created, group_restored from baserow.core.trash.registries import TrashableItemType, trash_item_type_registry class ApplicationTrashableItemType(TrashableItemType): type = "application" model_class = Application def get_parent(self, trashed_item: Any, parent_id: int) -> Optional[Any]: return trashed_item.group def get_name(self, trashed_item: Application) -> str: return trashed_item.name def trashed_item_restored(self, trashed_item: Application, trash_entry: TrashEntry): application_created.send( self, application=trashed_item, user=None, ) def permanently_delete_item( self, trashed_item: Application, trash_item_lookup_cache=None ): """ Deletes an application and the related relations in the correct way. """ application = trashed_item.specific application_type = application_type_registry.get_by_model(application) application_type.pre_delete(application) application.delete() return application class GroupTrashableItemType(TrashableItemType): type = "group" model_class = Group def get_parent(self, trashed_item: Any, parent_id: int) -> Optional[Any]: return None def get_name(self, trashed_item: Group) -> str: return trashed_item.name def trashed_item_restored(self, trashed_item: Group, trash_entry: TrashEntry): """ Informs any clients that the group exists again. """ for group_user in trashed_item.groupuser_set.all(): group_restored.send(self, group_user=group_user, user=None) def permanently_delete_item( self, trashed_group: Group, trash_item_lookup_cache=None ): """ Deletes the provided group and all of its applications permanently. """ # Select all the applications so we can delete them via the handler which is # needed in order to call the pre_delete method for each application. applications = ( trashed_group.application_set(manager="objects_and_trash") .all() .select_related("group") ) application_trashable_type = trash_item_type_registry.get("application") for application in applications: application_trashable_type.permanently_delete_item(application) trashed_group.delete()
nilq/baby-python
python
""" NetEvo for Python ================= NetEvo is a computing framework designed to allow researchers to investigate evolutionary aspects of dynamical complex networks. It provides functionality to easily simulate dynamical networks with both nodes and edges states, and includes optimization methods to evolve the dynamics or structure of a system towards some user specified goal. NetEvo is writen in Python and makes use of the networkx, numpy, and SciPy packages. """ # NetEvo for Python # Copyright (C) 2010-2013 by # Thomas E. Gorochowski <tom@chofski.co.uk> # All rights reserved. # OSI Non-Profit Open Software License ("Non-Profit OSL") 3.0 license. import sys if sys.version_info[:2] < (2, 6): m = "Python version 2.6 or later is required for NetEvo (%d.%d detected)." raise ImportError(m % sys.version_info[:2]) del sys __author__ = 'Thomas E. Gorochowski <tom@chofski.co.uk>' __license__ = 'OSI Non-Profit OSL 3.0' __version__ = '1.0' import math import random import networkx as nx import numpy as np import scipy.integrate as integrate def simulate_euler (G, t_max, reporter=None, h=0.01): """Simulate continuous-time network dynamics using a 1st order Euler method. This method is very simple and not advised for general use. It is included for comparison and teaching purposes. The state of the simulaton is stored as a node or edge attribute with the 'state' key. Parameters ---------- G : NetworkX graph It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). t_max : float Time to simulate for. reporter : function (optional default=None) Reporting function called at each timestep, see: state_reporter(G, t). h : float (default=0.01) Timestep """ # Check which types of dynamics exist node_dyn = G.graph['node_dyn'] edge_dyn = G.graph['edge_dyn'] # Inform the reporter of the initial state if reporter != None: reporter(G, 0.0) # Cycle through all possible times t = 0.0 while t <= t_max: # Calculate new state for all nodes and edges if node_dyn: for n in G.nodes(): cur_node = G.node[n] cur_state = cur_node['state'] deriv = cur_node['dyn'](G, n, t, cur_state) cur_node['new_state'] = cur_state + (h * deriv) if edge_dyn: for e in G.edges(): cur_edge = G.edge[e[0]][e[1]] cur_state = cur_edge['state'] deriv = cur_edge['dyn'](G, e, t, cur_state) cur_edge['new_state'] = cur_state + (h * deriv) # Shift state if node_dyn: for n in G.nodes(): cur_node = G.node[n] cur_node['state'] = cur_node['new_state'] if edge_dyn: for e in G.edges(): cur_edge = G.edge[e[0]][e[1]] cur_edge['state'] = cur_edge['new_state'] # Update t (state is now at this point) t += h # Inform the reporter of the updated state if reporter != None: reporter(G, t) def simulate_midpoint (G, t_max, reporter=None, h=0.01): """Simulate continuous-time network dynamics using a 2nd order modified Euler method (mid-point). This has better handling of errors than the 1st order Euler method, but is also not advised for most systems. It is included for comparison and teaching purposes. The state of the simulaton is stored as a node or edge attribute with the 'state' key. Parameters ---------- G : NetworkX graph It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). t_max : float Time to simulate for. reporter : function (optional default=None) Reporting function called at each timestep, see: state_reporter(G, t). h : float (default=0.01) Timestep """ # Check which types of dynamics exist node_dyn = G.graph['node_dyn'] edge_dyn = G.graph['edge_dyn'] # Inform the reporter of the initial state if reporter != None: reporter(G, 0.0) # Cycle through all possible times t = 0.0 while t <= t_max: # Calculate new state for all nodes and edges if node_dyn: for n in G.nodes(): cur_node = G.node[n] cur_state = cur_node['state'] p1 = (h / 2.0) * cur_node['dyn'](G, n, t, cur_state) cur_node['new_state'] = cur_state + (h * cur_node['dyn'](G, n, t + (h / 2.0), cur_state + p1)) if edge_dyn: for e in G.edges(): cur_edge = G.edge[e[0]][e[1]] cur_state = cur_edge['state'] p1 = (h / 2.0) * cur_edge['dyn'](G, e, t, cur_state) cur_edge['new_state'] = cur_state + (h * cur_edge['dyn'](G, n, t + (h / 2.0), cur_state + p1)) # Shift state if node_dyn: for n in G.nodes(): cur_node = G.node[n] cur_node['state'] = cur_node['new_state'] if edge_dyn: for e in G.edges(): cur_edge = G.edge[e[0]][e[1]] cur_edge['state'] = cur_edge['new_state'] # Update t (state is now at this point) t += h # Inform the reporter of the updated state if reporter != None: reporter(G, t) def simulate_rk45 (G, t_max, reporter=None, h=0.01): """Simulate continuous-time network dynamics using a 4th order Runge Kutta method (Dormand-Prince). This is the recommended simulator for most cases. It is an explicit method and so is not always well suited for stiff systems, however, in most cases it is suitable with a sufficiently small timestep. The state of the simulaton is stored as a node or edge attribute with the 'state' key. Parameters ---------- G : NetworkX graph It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). t_max : float Time to simulate for. reporter : function (optional default=None) Reporting function called at each timestep, see: state_reporter(G, t). h : float (default=0.01) Timestep """ # Check which types of dynamics exist node_dyn = G.graph['node_dyn'] edge_dyn = G.graph['edge_dyn'] # Constants for the calculations a21 = (1.0/5.0) a31 = (3.0/40.0) a32 = (9.0/40.0) a41 = (44.0/45.0) a42 = (-56.0/15.0) a43 = (32.0/9.0) a51 = (19372.0/6561.0) a52 = (-25360.0/2187.0) a53 = (64448.0/6561.0) a54 = (-212.0/729.0) a61 = (9017.0/3168.0) a62 = (-355.0/33.0) a63 = (46732.0/5247.0) a64 = (49.0/176.0) a65 = (-5103.0/18656.0) a71 = (35.0/384.0) a72 = (0.0) a73 = (500.0/1113.0) a74 = (125.0/192.0) a75 = (-2187.0/6784.0) a76 = (11.0/84.0) c2 = (1.0 / 5.0) c3 = (3.0 / 10.0) c4 = (4.0 / 5.0) c5 = (8.0 / 9.0) c6 = (1.0) c7 = (1.0) b1 = (35.0/384.0) b2 = (0.0) b3 = (500.0/1113.0) b4 = (125.0/192.0) b5 = (-2187.0/6784.0) b6 = (11.0/84.0) b7 = (0.0) b1p = (5179.0/57600.0) b2p = (0.0) b3p = (7571.0/16695.0) b4p = (393.0/640.0) b5p = (-92097.0/339200.0) b6p = (187.0/2100.0) b7p = (1.0/40.0) # Inform the reporter of the initial state if reporter != None: reporter(G, 0.0) # Cycle through all possible times t = h while t <= t_max: # Calculate new state for all nodes and edges if node_dyn: for n in G.nodes(): cur_node = G.node[n] cur_state = cur_node['state'] K1 = cur_node['dyn'](G, n, t, cur_state) K2 = cur_node['dyn'](G, n, t + c2*h, cur_state+h*(a21*K1)) K3 = cur_node['dyn'](G, n, t + c3*h, cur_state+h*(a31*K1+a32* K2)) K4 = cur_node['dyn'](G, n, t + c4*h, cur_state+h*(a41*K1+a42* K2+a43*K3)) K5 = cur_node['dyn'](G, n, t + c5*h, cur_state+h*(a51*K1+a52* K2+a53*K3+a54*K4)) K6 = cur_node['dyn'](G, n, t + h, cur_state+h*(a61*K1+a62*K2+ a63*K3+a64*K4+a65*K5)) K7 = cur_node['dyn'](G, n, t + h, cur_state+h*(a71*K1+a72*K2+ a73*K3+a74*K4+a75*K5+a76*K6)) cur_node['new_state'] = cur_state + (h * (b1*K1+b3*K3+b4*K4+ b5*K5+b6*K6)) if edge_dyn: for e in G.edges(): cur_edge = G.edge[e[0]][e[1]] cur_state = cur_edge['state'] K1 = cur_edge['dyn'](G, e, t, cur_state) K2 = cur_edge['dyn'](G, e, t + c2*h, cur_state+h*(a21*K1)) K3 = cur_edge['dyn'](G, e, t + c3*h, cur_state+h*(a31*K1+a32* K2)) K4 = cur_edge['dyn'](G, e, t + c4*h, cur_state+h*(a41*K1+a42* K2+a43*K3)) K5 = cur_edge['dyn'](G, e, t + c5*h, cur_state+h*(a51*K1+a52* K2+a53*K3+a54*K4)) K6 = cur_edge['dyn'](G, e, t + h, cur_state+h*(a61*K1+a62*K2+ a63*K3+a64*K4+a65*K5)) K7 = cur_edge['dyn'](G, e, t + h, cur_state+h*(a71*K1+a72*K2+ a73*K3+a74*K4+a75*K5+a76*K6)) cur_edge['new_state'] = cur_state + (h * (b1*K1+b3*K3+b4*K4+ b5*K5+b6*K6)) # Shift state if node_dyn: for n in G.nodes(): cur_node = G.node[n] cur_node['state'] = cur_node['new_state'] if edge_dyn: for e in G.edges(): cur_edge = G.edge[e[0]][e[1]] cur_edge['state'] = cur_edge['new_state'] # Inform the reporter of the updated state if reporter != None: reporter(G, t) # Update t t += h def simulate_ode_fixed (G, ts, node_dim=1, edge_dim=1, rtol=1e-5, atol=1e-5, save_final_state=True): """Simulate continuous-time network dynamics using the SciPy odeint function (adaptive step integrator). For systems where simulation does not lead to a change in the network structure and where node and edge states maintain the same size through time, it is possible to use the built-in SciPy ode solvers. Note special dynamic functions for nodes and edges must be used. Initial condition is defined in the 'state' attribute of nodes and edges in G. Parameters ---------- G : NetworkX graph It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). ts : list(float) List of time points to output the simulation results. node_dim : int (default=1) The dimension of node states. edge_dim : int (default=1) The dimension of edge states. rtol : float (default=1e-5) Relative error tolerance to be maintained (passed to SciPy). ratol : float (default=1e-5) Absolute error tolerance to be maintained (passed to SciPy). save_final_state : boolean (default=True) Flag to choose if the final simulation state should be saved to the networks 'state' attribute for the associated nodes and edges. Returns ------- res: numpy.array Array of the simulation results. A row exists for each of the given timepoints in ts and columns represent the node and edge states. To find the approriate starting index for a particular node or edge the returned mappings must be used. nmap: dict A dictionary keyed by the node. Returns the position in the results array (res) of the first state value for that node. emap: dict A dictionary keyed by the edge. Returns the position in the results array (res) of the first state value for that edge. """ # Generate the node and edge mappings for the state vector nmap = {} emap = {} max_node_idx = 0 # Create the node mapping if G.graph['node_dyn'] == True: for idx, n in enumerate(G.nodes()): nmap[n] = idx * node_dim max_node_idx = node_dim * G.number_of_nodes() else: nmap = None node_dim = 0 # Create the edge mapping if G.graph['edge_dyn'] == True: for idx, e in enumerate(G.edges()): emap[e] = max_node_idx + (idx * edge_dim) else: emap = None edge_dim = 0 # Generate the initial conditions (from G 'state') f0 = np.zeros(max_node_idx + (G.number_of_edges() * edge_dim)) if nmap != None: for n in G.nodes(): state = G.node[n]['state'] f0[nmap[n]:(nmap[n] + node_dim)] = state if emap != None: for e in G.edges(): state = G.edge[e[0]][e[1]]['state'] f0[emap[e]:(emap[e] + edge_dim)] = state # Simulate the system res = integrate.odeint(simulate_ode_fixed_fn, f0, ts, args=(G, nmap, emap), rtol=rtol, atol=atol) # Save the final state to G if save_final_state: if nmap != None: for n in G.nodes(): G.node[n]['state'] = res[:][-1][nmap[n]:(nmap[n] + node_dim)] if emap != None: for e in G.edges(): G.edge[e[0]][e[1]]['state'] = res[:][-1][emap[e]:(emap[e] + edge_dim)] # Return the full simulation array return res, nmap, emap def simulate_ode_fixed_fn (y, t, G, nmap, emap): # Internal function for calculating network derivitive dy = np.zeros(len(y)) if nmap != None: # Call all the node update functions for n in G.nodes(): G.node[n]['dyn'](G, n, t, y, dy, nmap, emap) if emap != None: # Call all the edge update functions for e in G.edges(): G.edge[e[0]][e[1]]['dyn'](G, e, t, y, dy, nmap, emap) return dy def simulate_steps (G, t_max, reporter=None): """Simulate discrete-time network dynamics. This is the recommended simulator for most cases. The state of the simulaton is stored as a node or edge attribute with the 'state' key. Parameters ---------- G : NetworkX graph It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). t_max : float Time to simulate for. reporter : function (optional default=None) Reporting function called at each timestep, see: state_reporter(G, t). """ # Check which types of dynamics exist node_dyn = G.graph['node_dyn'] edge_dyn = G.graph['edge_dyn'] # Inform the reporter of the initial state if reporter != None: reporter(G, 0) # Cycle through the steps required for t in range(1, t_max+1): # Calculate new state for all nodes and edges if node_dyn: for n in G.nodes(): cur_node = G.node[n] cur_node['new_state'] = cur_node['dyn'](G, n, t, cur_node['state']) if edge_dyn: for e in G.edges(): cur_edge = G.edge[e[0]][e[1]] cur_edge['new_state'] = cur_edge['dyn'](G, e, t, cur_node['state']) # Shift state if node_dyn: for n in G.nodes(): cur_node = G.node[n] cur_node['state'] = cur_node['new_state'] if edge_dyn: for e in G.edges(): cur_edge = G.edge[e[0]][e[1]] cur_edge['state'] = cur_edge['new_state'] # Inform the reporter of the updated state if reporter != None: reporter(G, t) def simulate_steps_fixed (G, ts, node_dim=1, edge_dim=1, save_final_state=True): """Simulate discrete-time network dynamics. For systems where simulation does not lead to a change in the network structure and where node and edge states maintain the same size through time. Note special dynamic functions for nodes and edges must be used. Initial condition is defined in the 'state' attribute of nodes and edges in G. Parameters ---------- G : NetworkX graph It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). ts : list(float) List of time points to output the simulation results. node_dim : int (default=1) The dimension of node states. edge_dim : int (default=1) The dimension of edge states. save_final_state : boolean (default=True) Flag to choose if the final simulation state should be saved to the networks 'state' attribute for the associated nodes and edges. Returns ------- res: numpy.array Array of the simulation results. A row exists for each of the given timepoints in ts and columns represent the node and edge states. To find the approriate starting index for a particular node or edge the returned mappings must be used. nmap: dict A dictionary keyed by the node. Returns the position in the results array (res) of the first state value for that node. emap: dict A dictionary keyed by the edge. Returns the position in the results array (res) of the first state value for that edge. """ # Check which types of dynamics exist node_dyn = G.graph['node_dyn'] edge_dyn = G.graph['edge_dyn'] # Variable to hold the results res = [] # Generate the node and edge mappings for the state vector nmap = {} emap = {} max_node_idx = 0 # Create the node mapping if G.graph['node_dyn'] == True: for idx, n in enumerate(G.nodes()): nmap[n] = idx * node_dim max_node_idx = node_dim * G.number_of_nodes() else: nmap = None node_dim = 0 # Create the edge mapping if G.graph['edge_dyn'] == True: for idx, e in enumerate(G.edges()): emap[e] = max_node_idx + (idx * edge_dim) else: emap = None edge_dim = 0 # Generate the initial conditions (from G 'state') y = np.zeros(max_node_idx + (G.number_of_edges() * edge_dim)) if nmap != None: for n in G.nodes(): y[nmap[n]:(nmap[n] + node_dim)] = G.node[n]['state'] if emap != None: for e in G.edges(): y[emap[e]:(emap[e] + edge_dim)] = G.edge[e[0]][e[1]]['state'] # Save the initial conditions res.append(y) # Cycle through the steps required for t in range(1, max(ts)+1): # Create a new state vector dy = np.zeros(len(y)) if nmap != None: # Call all the node update functions for n in G.nodes(): G.node[n]['dyn'](G, n, t, y, dy, nmap, emap) if emap != None: # Call all the edge update functions for e in G.edges(): G.edge[e[0]][e[1]]['dyn'](G, e, t, y, dy, nmap, emap) # Save the state if in the output list if t in ts: res.append(dy) y = dy # Save the final state to G if save_final_state: if nmap != None: for n in G.nodes(): G.node[n]['state'] = res[:][-1][nmap[n]:(nmap[n] + node_dim)] if emap != None: for e in G.edges(): G.edge[e[0]][e[1]]['state'] = res[:][-1][emap[e]:(emap[e] + edge_dim)] return np.array(res), nmap, emap def state_reporter (G, t): """Simple simulation state reporter that outputs the current time and node states. Parameters ---------- G : NetworkX graph It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). t : float Time point of the simulation. """ output = 't = ' + str(t) + ', state = ' for i in G.nodes(): output += str(G.node[i]['state']) + ', ' print output def rnd_uniform_node_states (G, state_range): """Set all node states in a network to a uniformly random value. To allow for states of dimension > 1, state ranges should be provided for each element in the state vector. Parameters ---------- G : NetworkX graph It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). state_range : list(tuples) List of tuples that hold the min and max value to randomly pick a value between e.g., state_range = [(1min, 1max), (2min, 2max)...]. """ if len(state_range) == 1: r1 = state_range[0][0] r2 = state_range[0][1] for n in G.nodes(): G.node[n]['state'] = random.uniform(r1, r2) else: for n in G.nodes(): n_state = [] for s in range(len(state_range)): n_state.append(random.uniform(state_range[s][0], state_range[s][1])) G.node[n]['state'] = np.array(n_state) def rnd_uniform_edge_states (G, state_range): """Set all edge states in a network to a uniformly random value. To allow for states of dimension > 1, state ranges should be provided for each element in the state vector. Parameters ---------- G : NetworkX graph It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). state_range : list(tuples) List of tuples that hold the min and max value to randomly pick a value between e.g., state_range = [(1min, 1max), (2min, 2max)...]. """ if len(state_range) == 1: r1 = state_range[0][0] r2 = state_range[0][1] for e in G.edges(): G.edge[e[0]][e[1]]['state'] = random.uniform(r1, r2) else: for e in G.edges(): e_state = [] for s in range(len(state_range)): e_state.append(random.uniform(state_range[s][0], state_range[s][1])) G.edge[e[0]][e[1]]['state'] = np.array(e_state) def set_all_node_dynamics (G, dyn_fn): """Set the dynamics for all nodes. Parameters ---------- G : NetworkX graph It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). dyn_fn : function Function to be used for every nodes dynamics. """ for n in G.nodes(): G.node[n]['dyn'] = dyn_fn def set_all_edge_dynamics (G, dyn_fn): """Set the dynamics for all edges. Parameters ---------- G : NetworkX graph It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). dyn_fn : function Function to be used for every edges dynamics. """ for e in G.edges(): G.edge[e[0]][e[1]]['dyn'] = dyn_fn def no_node_dyn (G, n, t, state): """Null node dynamics (does nothing). To be used when you want some nodes to have no dynamics. """ return 0.0 def no_edge_dyn (G, e, t, state): """Null edge dynamics (does nothing). To be used when you want some edges to have no dynamics. """ return 0.0 def random_rewire (G, n, allow_self_loops=False): """Randomly rewire edges. This function performs a full rewire i.e., it will ensure the newly created edge contains all the same properties as the original. Parameters ---------- G : NetworkX graph It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). n : int Number of edges to randomly rewire. allow_self_loops : boolean (default=False) Flag as to whether self loops are allowed. """ nodes = G.nodes() edges = G.edges() for i in range(n): # Pick a random edge (u, v) = edges[int(random.random()*G.number_of_edges())-1] # Attempt to find a new random edge (maximum 1000 trials) trial = 0 while trial < 1000: new_u = int(random.random()*len(G)) new_v = int(random.random()*len(G)) if allow_self_loops: if G.has_edge(nodes[new_u], nodes[new_v]) == False: break else: if new_u != new_v and \ G.has_edge(nodes[new_u], nodes[new_v]) == False: break trial += 1 # Rewire if max trials not reached if trial >= 1000: print 'WARNING: Could not rewire edge - max trials exceeded' else: # Rewire it G.remove_edge(u, v) G.add_edge(nodes[new_u], nodes[new_v]) def evo_sa_reporter (G, G_perf, iteration): """Simple evolutionary state reporter for the simulated annealing evolver. Outputs the current iteration and performance value for the network. Parameters ---------- G : NetworkX graph It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). G_perf : float Performance of the network. iteration : int Iteration of the evolutionary process. """ print 'Iteration: ' + str(iteration) + ', Performance = ' + str(G_perf) def boltzmann_accept_prob (d_perf, temperature): """Boltzmann accepting probability function for the simulated annealing evolver. Parameters ---------- d_perf : float Change in performance value in last iteration. temperature : float Current temperature of the simulated annealing process. """ return math.exp(d_perf / temperature); def evolve_sa (G, perf_fn, mut_fn, max_iter=100000, max_no_change=100, initial_temp=100000000000.0, min_temp=0.001, reporter=None, cooling_rate=0.99, accept_prob_fn=boltzmann_accept_prob): """Simulated annealing based evolver. Starting wit Parameters ---------- G : NetworkX graph Starting network to evolve. It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). perf_fn : function Performance function to evalulate each candidate network. Lower performance values are better - evolution minimizes. mut_fn : function Mutation function to generate new candidate networks from an existing network. max_iter : int (default=100000) Maximum number of iterations to perform. max_no_change : int (default=100) Maximum number of consecutive iterations with no change before halting. initial_temp : float (default=100000000000.0) Initial temperature of the simulated annealing process. min_temp : float (default=0.001) Minimum temperature of the simulated annealing process before halting. reporter : function (optional default=None) Optional reporter called after each evolutionary step. cooling_rate : float (default=0.99) The fraction of the temperature used in following iterations. accept_prob_fn : function (default=boltzmann_accept_prob) Function defining the accepting probability at a particular temperature. Returns ------- iteration : int Final iteration reached cur_G : NetworkX graph Resultant network from the evolutionary process """ # Copy the system and set initial process variables cur_G = G.copy() iteration = 0 cur_temp = initial_temp # Calculate the initial performance cur_perf = perf_fn(cur_G) # Observe the inital system if reporter != None: reporter(cur_G, cur_perf, iteration) no_change = 0 if cur_temp > 0.0: while no_change <= max_no_change and cur_temp > min_temp and \ iteration <= max_iter: iteration += 1 # Run a trial accept, new_G, G_perf = evolve_sa_trial(cur_temp, cur_perf, cur_G, mut_fn, perf_fn, accept_prob_fn) if accept: cur_G = new_G cur_perf = G_perf no_change = 0 else: no_change += 1 # Observe the current system if reporter != None: reporter(cur_G, cur_perf, iteration) # Reduce the temperature cur_temp *= cooling_rate else: print 'WARNING: Initial temperature was <= 0.0' return iteration, cur_G def evolve_sa_trial (cur_temp, cur_perf, G, mut_fn, perf_fn, accept_prob_fn): # Internal function that calculates a simulated annealing trial # Make a copy of the system G_copy = G.copy() # Mutate the system mut_fn(G_copy) # Estimate performance new_perf = perf_fn(G_copy) if new_perf == float('inf'): # Do not accept change return False, G, cur_perf d_perf = cur_perf - new_perf if d_perf > 0.0: # Accept improvement return True, G_copy, new_perf else: # Ensure positive temperature if cur_temp > 0.0: # Randomly accept in relation to temperature if random.random() <= accept_prob_fn(d_perf, cur_temp): return True, G_copy, new_perf else: print 'WARNING: Zero or negative temperature (evolve_sa_trail)' # Mutation not accepted return False, G, cur_perf def evo_ga_reporter (G_pop_perf, iteration): """Simple evolutionary state reporter for the genetic algorithms evolver. Outputs the current iteration and performance values for the network populations. Parameters ---------- G_pop_perf : list([NetworkX graph, float]) Current evolving network population with the performance value. iteration : int Iteration of the evolutionary process. """ out_str = 'Iteration: ' + str(iteration) + ', Performance = ' for perf in G_pop_perf: out_str += str(perf[1]) + ', ' print out_str def evolve_ga (G_pop, perf_fn, reproduce_fn, max_iter=1000, reporter=None): """ Evolves a population of networks using a genetic algorithm. Outputs the evolved population with the accociated performance values. Parameters ---------- G_pop : list(NetworkX graph) Initial network population. perf_fn : function Performance function to evalulate each candidate network. Lower performance values are better - evolution minimizes. reproduce_fn : function Function to generate new candidate networks from an existing population with performance values. max_iter : int (default = 1000) Maximum number of iterations (generations) to produce. reporter : function (optional default=None) Optional reporter called after each evolutionary step. """ # Copy the population (we don't make changes to the initial one) cur_pop_perf = [] for g in G_pop: cur_pop_perf.append([g, 0.0]) for it in range(0, max_iter): # Calculate the performance perf_fn(cur_pop_perf) # Report the current performance if reporter != None: reporter(cur_pop_perf, it) # Mate the graphs and update the current population cur_pop_perf = reproduce_fn(cur_pop_perf) # Report the final performance if reporter != None: reporter(cur_pop_perf, max_iter) return cur_pop_perf def evolve_ga_reproduce (G_pop_perf, n_dup_prob=0.02, n_del_prob=0.02, e_dup_prob=0.02, e_del_prob=0.02, points=1): """ A basic reproduce function that will randomly duplicate and delete nodes and edges, and perform network crossover on a population of networks to generate a new candidate population for the genetic algorithm. Can be used with default values or called from a user defined function that specifies particular probabilities and crossover points to use. Due to the reproduction often being highly constrainted in natural and engineered systems, we recommend creating custom versions for the specific system being studied. Outputs the new candidate population set (all performance values set to 0). Parameters ---------- G_pop_perf : list([NetworkX graph, float]) Current evolving network population with the performance value. n_dup_prob : float (default = 0.02) Node duplication probability. n_del_prob : float (default = 0.02) Node deletion probability. e_dup_prob : float (default = 0.02) Edge duplication probability. e_del_prob : float (default = 0.02) Edge deletion probability. points : int (default = 1) Number of crossover points. """ print 'WARNING: Currently not implemented.' def graph_crossover (G1, G2, points=1): """ Performs a network based crossover operation on two graphs. Outputs the crossovered graph (new object). Parameters ---------- G1 : NetworkX graph Graph 1 to crossover. G2 : NetworkX graph Graph 2 to crossover. points : int (default = 1) Number of crossover points. """ # Pick a node number of perform the crossover with nodes_1 = G1.nodes() nodes_2 = G2.nodes() # Randomly choose crossover points (should include check that loop will end) if points >= G1.number_of_nodes(): print 'ERROR: Too many crossover points (defaulting to 1).' points = 1 n_cross_points = [0] for p in range(points): new_p = int(random.random()*G1.number_of_nodes()) while new_p not in n_cross_points: new_p = int(random.random()*G1.number_of_nodes()) n_cross_points.append(new_p) n_cross_points = sorted(n_cross_points) # Sets of nodes to extract for each graph g_num = 1 ns_1 = [] ns_2 = [] for p_idx in range(1,len(n_cross_points)): p1_idx = n_cross_points[p_idx-1] p2_idx = n_cross_points[p_idx] if g_num == 1: ns_1 += nodes_1[p1_idx:p2_idx] g_num = 2 else: ns_2 += nodes_2[p1_idx:p2_idx] g_num = 1 # Handle the case where both lists might include the same nodes (clean up) for i in ns_2: if i in ns_1: # Remove node from list 2 ns_2.remove(i) # Generate new network that is a crossover of the two G_cross = nx.create_empty_copy(G1) # Copy graph properties for k in G1.graph.keys(): G_cross.graph[k] = G1.graph[k] # Remove all nodes not in ns_1 list for n in ns_1: G_cross.add_node(n) # Copy all properties from G1 g1_n = G1.node[n] g1_n_keys = g1_n.keys() for k in g1_n_keys: G_cross.node[n][k] = g1_n[k] # Add all nodes from ns_2 for n in ns_2: G_cross.add_node(n) # Copy all properties from G2 g2_n = G2.node[n] g2_n_keys = g2_n.keys() for k in g2_n_keys: G_cross.node[n][k] = g2_n[k] # Add edges present where nodes still exist in crossovered graph #for n in ns_1: # Check that source and target in new graph, if so add with properties # TODO # pass #for n in ns_2: # TODO # pass return G_cross def write_to_file (G, path, format='gml', node_keys=[], edge_keys=[]): """Writes a NetEvo graph to a suitably formatted file for use in external applications such as Cytoscape. This should be used instead of the networkx functions as Cytoscape does not correctly handle non-string based labels or lists (often used for parameters). Parameters to convert can be specified. Outputs a file in the designated format. Parameters ---------- G : NetworkX graph It is assumed that this is configured for use with NetEvo, with defined dynamics for each node or edge (as appropriate). path : string Filename and path of the output file. format : string "gml"|"graphml" (default="gml") Output format. node_keys : list(string) List of node attribute keys to convert to strings. edge_keys : list(string) List of edge attribute keys to convert to strings. """ G_copy = G.copy() for n in G_copy.nodes(): G_copy.node[n]['label'] = str(n) if G_copy.graph['node_dyn'] == True: G_copy.node[n]['dyn'] = str(G_copy.node[n]['dyn']) for k in node_keys: G_copy.node[n][k] = str(G_copy.node[n][k]) for n in G_copy.edges(): if G_copy.graph['edge_dyn'] == True: G_copy.edge[e[0]][e[1]]['dyn']=str(G_copy.edge[e[0]][e[1]]['dyn']) for k in edge_keys: G_copy.edge[e[0]][e[1]][k] = str(G_copy.edge[e[0]][e[1]][k]) if format == 'gml': nx.write_gml(G_copy, path) elif format == 'graphml': nx.write_graphml(G_copy, path) else: print 'WARNING: Unsupported file format (', format, ')'
nilq/baby-python
python
# Generated by Django 3.2.8 on 2021-11-02 22:22 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('tasks', '0009_alter_task_task_description'), ] operations = [ ]
nilq/baby-python
python
from processes.models import Workflow import factory from faker import Factory as FakerFactory from .owned_model_factory import OwnedModelFactory from .run_environment_factory import RunEnvironmentFactory faker = FakerFactory.create() class WorkflowFactory(OwnedModelFactory): class Meta: model = Workflow name = factory.Sequence(lambda n: f'workflow_{n}') run_environment = factory.SubFactory(RunEnvironmentFactory, created_by_user=factory.SelfAttribute("..created_by_user"), created_by_group=factory.SelfAttribute("..created_by_group")) max_age_seconds = 3600 default_max_retries = 0 latest_workflow_execution = None aws_scheduled_execution_rule_name = '' aws_scheduled_event_rule_arn = '' aws_event_target_rule_name = '' aws_event_target_id = ''
nilq/baby-python
python
""" """ from .utils import install_issubclass_patch __version__ = "0.10.2" install_issubclass_patch()
nilq/baby-python
python
import torch.nn as nn from .fcn import FCNHead def build_segmentor(opt): n_class = opt.n_class # channels = [18, 36, 72, 144] channels = [128] classifier = FCNHead( sum(channels), sum(channels), n_class, num_convs=1, kernel_size=1 ) return classifier def build_linear(opt): n_class = opt.n_class arch = opt.arch if arch.endswith('x4'): n_feat = 2048 * 4 elif arch.endswith('x2'): n_feat = 2048 * 2 else: n_feat = 2048 classifier = nn.Linear(n_feat, n_class) return classifier
nilq/baby-python
python
############################################################################## # Copyright (c) 2016 HUAWEI TECHNOLOGIES CO.,LTD and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## import re import os import yaml import sys import traceback def load_file(file): with open(file) as fd: try: return yaml.safe_load(fd) except: traceback.print_exc() return None def err_print(info): print '\033[0;31m%s\033[0m' % info def is_valid_ip(ip): """return True if the given string is a well-formed IP address currently only support IPv4 """ if not ip: return False res = re.search( "^(0?\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}(\/(\d|[1-2]\d|3[0-2]))?$", # noqa ip) is not None return res def is_valid_mac(mac): """return True if the given string is a well-formed MAC address """ if not mac: return False res = re.search("^([a-zA-Z0-9]{2}:){5}[a-zA-Z0-9]{2}$", mac) is not None return res def check_network_file(network): invalid = False for i in network['ip_settings']: if not is_valid_ip(i['cidr']): err_print('''invalid address: ip_settings: - name: %s cidr: %s''' % (i['name'], i['cidr'])) invalid = True if not is_valid_ip(i['ip_ranges'][0][0]): err_print('''invalid address: ip_settings: - name: %s ip_ranges: - - %s''' % (i['name'], i['ip_ranges'][0][0])) invalid = True if not is_valid_ip(i['ip_ranges'][0][1]): err_print('''invalid address: ip_settings: - name: %s ip_ranges: - %s''' % (i['name'], i['ip_ranges'][0][1])) invalid = True if i['name'] == 'external' and not is_valid_ip(i['gw']): err_print(i['gw']) err_print('''invalid address: ip_settings: - name: %s gw: %s''' % (i['name'], i['gw'])) invalid = True for i in network['public_net_info'].keys(): if i in ('external_gw', 'floating_ip_cidr', 'floating_ip_start', 'floating_ip_end'): if not is_valid_ip(network['public_net_info'][i]): err_print('''invalid address: public_net_info: %s: %s''' % (i, network['public_net_info'][i])) invalid = True if not invalid: return True else: return False def check_dha_file(dha): invalid = False if dha['TYPE'] == 'baremetal': for i in dha['hosts']: if not is_valid_mac(i['mac']): err_print('''invalid address: hosts: - name: %s mac: %s''' % (i['name'], i['mac'])) invalid = True for j in i['interfaces']: if not is_valid_mac(j.values()[0]): err_print('''invalid address: hosts: - name: %s interfaces: - %s: %s''' % (i['name'], j.keys()[0], j.values()[0])) # noqa: E501 invalid = True if not is_valid_ip(i['ipmiIp']): err_print('''invalid address: hosts: - name: %s ipmiIp: %s''' % (i['name'], i['ipmiIp'])) invalid = True if not invalid: return True else: return False if __name__ == "__main__": has_invalid = False if len(sys.argv) != 3: err_print('input file error') sys.exit(1) _, dha_file, network_file = sys.argv if not os.path.exists(dha_file): err_print("DHA file doesn't exist") sys.exit(1) else: dha = load_file(dha_file) if not dha: err_print('format error in DHA: %s' % dha_file) has_invalid = True else: if not check_dha_file(dha): err_print('in DHA: %s' % dha_file) has_invalid = True if not os.path.exists(network_file): err_print("NETWORK file doesn't exist") sys.exit(1) else: network = load_file(network_file) if not network: err_print('format error in NETWORK: %s' % network_file) has_invalid = True else: if not check_network_file(network): err_print('in NETWORK: %s' % network_file) has_invalid = True if has_invalid: sys.exit(1)
nilq/baby-python
python
from collections import defaultdict from typing import Optional import ether.topology from ether.core import Node, Connection DockerRegistry = Node('registry') class Topology(ether.topology.Topology): def __init__(self, incoming_graph_data=None, **attr): super().__init__(incoming_graph_data, **attr) self._node_index = dict() def init_docker_registry(self): """ Attaches the global "dockerhub.com" DockerRegistry to all internet helper nodes in the topology. """ if DockerRegistry not in self.nodes: self.add_node(DockerRegistry) for node in self.nodes: if isinstance(node, str) and node.startswith('internet'): self.add_connection(Connection(node, DockerRegistry)) def route_by_node_name(self, source_name: str, destination_name: str): """ Resolves a route between compute nodes given their names. Raises a value error if either source or destination do not exist. :param source_name: the source node name :param destination_name: the destination node name :return: a Route """ source = self.find_node(source_name) if source is None: raise ValueError('source node not found: ' + source_name) destination = self.find_node(destination_name) if destination is None: raise ValueError('destination node not found: ' + destination_name) return self.route(source, destination) def find_node(self, node_name: str) -> Optional[Node]: """ Looks up a compute node by its unique name. :param node_name: the node name :return: the node or none if it does not exist """ if node_name in self._node_index: return self._node_index[node_name] for node in self.get_nodes(): if node.name == node_name: self._node_index[node_name] = node return node return None class LazyBandwidthGraph: """ Behaves like a two-dimensional dictionary that lazily resolves the bandwidth between nodes. Can be called like this: >>> bw = LazyBandwidthGraph(topology) >>> bw['server_0']['dockerhub.com'] == 1000 # will resolve the route >>> bw['server_0']['dockerhub.com'] == 1000 # served from the cache """ topology: Topology def __init__(self, topology: Topology) -> None: super().__init__() self.cache = defaultdict(dict) self.topology = topology def __getitem__(self, source): return self._Resolver(self, source) class _Resolver: def __init__(self, bwg: 'LazyBandwidthGraph', source: str) -> None: super().__init__() self.bwg = bwg self.source = source def __getitem__(self, destination: str) -> Optional[float]: if destination in self.bwg.cache[self.source]: return self.bwg.cache[self.source][destination] if self.source == destination: # FIXME: should this case maybe be handled in the scheduler/priorities? return 1.25e+8 route = self.bwg.topology.route_by_node_name(self.source, destination) if not route or not route.hops: return None bandwidth = min([link.bandwidth for link in route.hops]) self.bwg.cache[self.source][destination] = bandwidth return bandwidth
nilq/baby-python
python
import os from collections import Counter from datetime import datetime import matplotlib.pyplot as plt import pandas as pd def process_logfile(log_file) -> list: with open(log_file, mode='r', encoding='utf-8') as file: lines = file.readlines() return [line.split(" : ")[0] for line in lines] if __name__ == '__main__': # extract datetime strings from log files query_timestamps = [] # logs_dir = os.path.join(os.environ['RAVEN_HOME'], 'resources', 'sql_logs-customer4', '4', 'logs') logs_dir = os.path.join(os.environ['RAVEN_HOME'], 'resources', 'sql_logs-customer1-3') for filename in os.listdir(logs_dir): query_timestamps += process_logfile(os.path.join(logs_dir, filename)) # print(query_timestamps) conv_time = [datetime.strptime(_, '%Y-%m-%d %H:%M:%S') for _ in query_timestamps] query_timestamps = [dt.strftime('%Y-%m-%d %H:%M:%S') for dt in conv_time] query_timestamps.sort() for t in query_timestamps: print(t) # print(query_timestamps) # mylist = dict(Counter(query_timestamps)).items() # dt = [datetime.strptime(t[0], '%Y-%m-%d %H:%M') for t in mylist] # qps = [t[1] / 60.0 for t in mylist] # df = pd.DataFrame({'qps': qps}, index=pd.DatetimeIndex(dt)) # df['qps'].plot(xlabel='time', ylabel='QPS') # plt.ylim(0, 2.0) # plt.show() # # convert strings into datetime objects # conv_time = [datetime.strptime(_, '%Y-%m-%d %H:%M:%S') for _ in query_timestamps] # # print(conv_time) # # # define bin number # bin_nr = 150 # fig, ax = plt.subplots(1, 1) # # # create histogram, get bin position for label # _counts, bins, _patches = ax.hist(conv_time, bins=bin_nr) # # # set xticks at bin edges # plt.xticks(bins) # # # reformat bin label into format hour:minute # # ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M")) # # plt.show()
nilq/baby-python
python
from instagrapi import Client import requests import json username = "USERNAME" password = "PASSWORD" def instagram_json(): response = requests.get(f"https://www.instagram.com/{username}/?__a=1") data = response.json() data1 = json.dumps(data) data2 = json.loads(data1) followers = data2['graphql']['user']['edge_followed_by']['count'] bio = data2['graphql']['user']['biography'] print(followers) return followers, bio def bio(): followers, bio = instagram_json() bio_followers = [int(i) for i in bio.split() if i.isdigit()][0] if followers != bio_followers: ig = Client() ig.login(username, password) ig.account_edit(biography=f"I have {followers} followers 😇") ig.logout if __name__ == "__main__": bio()
nilq/baby-python
python
# Modules from termenu import PlainMenu # Initialize our menu menu = PlainMenu() # Main option list @menu.option("Check out GitHub!") def check_github(): print("You selected 'Check out GitHub!'.") @menu.option("Read some documentation!") def read_docs(): print("You selected 'Read some documentation!'.") @menu.option("Chill!") def go_chill(): print("You selected 'Chill!'.") # Handle after invoke # This executes after an option callback is fired @menu.after_invoke() def handle_enter(): print("[press enter to continue]") input() # Loop menu menu.mainLoop()
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Provides the Action class as part of the PokerNowLogConverter data model""" from dataclasses import dataclass from player import Player @dataclass class Action: """ The Action class represents a single action made by a player in the active phase of the game. Args: player (:obj:`Player`): The player object who made this action action (str): A string stating which type of action this is. Valid actions include: "bet", "check", "fold", "call", "raise", "uncalled bet", "show", "collect bet_amount (float, optional): If the action includes a bet amount, it is provided here. bet_difference (float, optional): The difference between the bet and the previous bet by this player. cards_shown (str, optional): If this is a "show" action, this variable contains the cards shown. Note: This variable is a single string, not a Card object or list of Card objects. """ player: Player action: str bet_amount: float = 0 bet_difference: float = 0 cards_shown: str = ''
nilq/baby-python
python
from calc import calculate_reverse_polish_notation print( calculate_reverse_polish_notation(input().split(' ')) )
nilq/baby-python
python
# -*- coding: utf-8 -*- """Functions to load and write datasets.""" __all__ = [ "load_airline", "load_arrow_head", "load_gunpoint", "load_basic_motions", "load_osuleaf", "load_italy_power_demand", "load_japanese_vowels", "load_longley", "load_lynx", "load_shampoo_sales", "load_UCR_UEA_dataset", "load_unit_test", "load_uschange", "load_PBS_dataset", "load_japanese_vowels", "load_gun_point_segmentation", "load_electric_devices_segmentation", "load_acsf1", "load_macroeconomic", "generate_example_long_table", "load_from_arff_to_dataframe", "load_from_long_to_dataframe", "load_from_tsfile", "load_from_tsfile_to_dataframe", "load_from_ucr_tsv_to_dataframe", "make_multi_index_dataframe", "write_dataframe_to_tsfile", "write_ndarray_to_tsfile", "write_results_to_uea_format", "write_tabular_transformation_to_arff", ] from sktime.datasets._data_io import ( generate_example_long_table, load_from_arff_to_dataframe, load_from_long_to_dataframe, load_from_tsfile, load_from_tsfile_to_dataframe, load_from_ucr_tsv_to_dataframe, make_multi_index_dataframe, write_dataframe_to_tsfile, write_ndarray_to_tsfile, write_results_to_uea_format, write_tabular_transformation_to_arff, ) from sktime.datasets._single_problem_loaders import ( load_acsf1, load_airline, load_arrow_head, load_basic_motions, load_electric_devices_segmentation, load_gun_point_segmentation, load_gunpoint, load_italy_power_demand, load_japanese_vowels, load_longley, load_lynx, load_macroeconomic, load_osuleaf, load_PBS_dataset, load_shampoo_sales, load_UCR_UEA_dataset, load_unit_test, load_uschange, )
nilq/baby-python
python